Update Tkinter Label from variable Update Tkinter Label from variable tkinter tkinter

Update Tkinter Label from variable


The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().


GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *root = Tk()var = StringVar()var.set('hello')l = Label(root, textvariable = var)l.pack()t = Entry(root, textvariable = var)t.pack()root.mainloop() # the window is now displayed

I like the following reference: tkinter 8.5 reference: a GUI for Python


Here is a working example of what you were trying to do:

from tkinter import *from time import sleeproot = Tk()var = StringVar()var.set('hello')l = Label(root, textvariable = var)l.pack()for i in range(6):    sleep(1) # Need this to slow the changes down    var.set('goodbye' if i%2 else 'hello')    root.update_idletasks()

root.update Enter event loop until all pending events have been processed by Tcl.


Maybe I'm not understanding the question but here is my simple solution that works -

# I want to Display total heads bent this machine so I define a label -TotalHeadsLabel3 = Label(leftFrame)TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))TotalHeadsLabel3.pack(side=TOP)# I update the int variable adding the quantity bent -TotalHeads = TotalHeads + headQtyBent # update ready to write to file & displayTotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty

I agree that labels are not automatically updated but can easily be updated with the

<label name>.config(text="<new text>" + str(<variable name>))

That just needs to be included in your code after the variable is updated.


This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.

    from tkinter import *    master = Tk()        def change_text():        my_var.set("Second click")        my_var = StringVar()    my_var.set("First click")    label = Label(mas,textvariable=my_var,fg="red")    button = Button(mas,text="Submit",command = change_text)    button.pack()    label.pack()        master.mainloop()