I'm using Tkinter for the first time and can't seem to update the text on a label. I've tried using text variable and it still doesn't work. I've done some without the function but it still doesn't update. Here's my full code:
from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
global money
money = IntVar()
money.set(0)
global num
num = 0
def button_clicked():
num += 1
money.set(num)
ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
ttk.Label(frm, text = money.get()).grid(column=0, row=1)
ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
ttk.Button(frm, text="Add Money", command=lambda: button_clicked).grid(column=1, row=1)
root.mainloop()
Tried updating the variable in the command section of the button, didn't change anything, still displayed zero. Converted it from IntVar to StrVar and didn't work, Added the Num variable and didn't change anything either.
IntVar()
is a bidirectional binding between a UI element and a variable. So, when assigning IntVar()
to a label, you have to use the textvariable
argument, not the text
argument. Change text = money.get()
to textvariable = money
inside the label definition.
You also cannot use lambda
as it's used for calling functions with arguments.
As @Caleb as pointed out, there's no need to use the global keyword as defining a variable in the main body of the program makes it global by default.
Instead of using money.set(0)
, you have assign the value while defining the IntVar()
like so: money = IntVar(value=0)
Inside the button_clicked()
function you have to define num
as global. This'll let Python know that you are changing the value of the previously defined num
variable and not a local variable inside the function.
Modified code:
from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
money = IntVar(value=0)
num = 0
def button_clicked():
global num
num += 1
money.set(num)
ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
ttk.Label(frm, textvariable = money).grid(column=0, row=1)
ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
ttk.Button(frm, text="Add Money", command=button_clicked).grid(column=1, row=1)
root.mainloop()