Home > Enterprise >  Why is this not working? On button click it should add 1
Why is this not working? On button click it should add 1

Time:07-06

Why is this not working? On button click it should add 1.

from tkinter import *
root = Tk()
m = 0
def clicka(m):
    m = m   1
    lbl = Label(text=str(m)).place(relx=0.1, rely = 0.2)
exe = Button(text = '↵', bg = 'black', fg = 'red',command=clicka(m), relief='flat').place(relx=0.19, rely = 0.32)
lbl = Label(text=str(m)).place(relx=0.1, rely = 0.2)
root.mainloop()

CodePudding user response:

There are issues in your code:

  • command=clicka(m) will execute clicka(m) immediately and assign the result of clicka(m) (which is None) to command option. So nothing will be done when the button is clicked later.

  • passing variable of primitive type will be passed by value, so even it is modified inside the function, the original variable will not be updated.

I would suggest to change m to IntVar and associate it to lbl via textvariable option, then updating m will update lbl at once:

import tkinter as tk

root = tk.Tk()

def clicka():
    m.set(m.get() 1)

tk.Button(text='↵', bg='black', fg='red', command=clicka, relief='flat').place(relx=0.19, rely = 0.32)

m = tk.IntVar(value=0)
tk.Label(textvariable=m).place(relx=0.1, rely = 0.2)

root.mainloop()

CodePudding user response:

You could try to set the variable m as global

from tkinter import *
root = Tk()
m = 0

def clicka():
    global m
    m = m   1
    lbl = Label(text=str(m)).place(relx=0.1, rely = 0.2)
    print('Hi')
    
exe = Button(text = '↵', bg = 'black', fg = 'red',command=clicka, relief='flat').place(relx=0.19, rely = 0.32)
lbl = Label(text=str(m)).place(relx=0.1, rely = 0.2)
root.mainloop()

CodePudding user response:

Indeed like @acw1668 mentioned, you can work with lambda or you can just use global. This is much shorter.

from tkinter import *

root = Tk()
m = 0


def clicka():
    global m
    m  = 1
    lbl["text"] = str(m)


exe = Button(text='↵', bg='black', fg='red', command=clicka, relief='flat')
exe.place(relx=0.19, rely=0.32)

lbl = Label(text=str(m))
lbl.place(relx=0.1, rely=0.2)

root.mainloop()

CodePudding user response:

You could try this :

from tkinter import *

win = Tk()

myvar = IntVar()

def Adder():
    k = int(myvar.get())
    k = k   1
    lb.insert(1 , k)

win.geometry("750x750")

b = Button(win , command = Adder)
b.grid(row = 0 , column = 0)

lb = Listbox(win , width = 20)
lb.grid(row = 1 , column = 0)

win.mainloop()
  • Related