LazyDingo27 LazyDingo27 - 2 months ago 13
Python Question

Python - Tkinter - Label Not Updating

Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change.

from tkinter import *

root = Tk(className="Page Calculator")

read = IntVar()

total = IntVar()

left = IntVar()

read.set(1)

total.set(1)

left.set(1)

read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)

total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)

read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)

total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)

def func1():
left.set(total.get() - read.get())
print(left.get())

calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)

percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)

left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)

percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)

leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)

root.mainloop()

Answer

To make the function do the job, you'd rather have your label:

leftresult_label = Label(root, textvariable=left)

Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,

def func1():
    left.set(total.get() - read.get())
    percent.set(int(read.get()*100/total.get()))

left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.

Here is full code:

from tkinter import *

root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()

read.set(1)
total.set(1)
left.set(1)
percent.set(1)

def func1():
    left.set(total.get() - read.get())
    percent.set(int(read.get()*100/total.get()))

read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)

read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)

total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)

total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)


calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)

percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)

left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)

percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)

leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)

root.mainloop()