Home > Software design >  Unable to update Label text in Python Tkinter without calling pack() again
Unable to update Label text in Python Tkinter without calling pack() again

Time:11-18

from tkinter import *
from tkinter.ttk import *

root = Tk()
first_run = True


def update(txt):
    global first_run
    text1 = Label(root, text='')
    if first_run:
        text1.pack()
    text1['text'] = txt
    first_run = False

update('1')
update('2')
update('3')
root.mainloop()

When I run this, the text stays at '1', and the following 2 function calls are ignored. I find out that only if I use pack() again then it will be updated, but it creates a duplicate label and I do not want that.

Of course, I know that I am supposed to use a StringVar, but I have been using this method for all other widgets (buttons, label frames etc) and all of them works. I do not know why this particular case does not work.

Running on Python 3.9.9 on Windows 11

CodePudding user response:

You aren't updating the label, you are creating a new label each time the function is called. To update any widget, use the configure method. For that, you need to create the label outside of the function (or, leave it in the function but add logic so that it's only created once). Usually it's best to create it outside the function so that the function is only responsible for the update.

from tkinter import *
from tkinter.ttk import *

root = Tk()

def update(txt):
    text1.configure(text=txt)

text1 = Label(root, text='')
text1.pack()

update('1')
update('2')
update('3')
root.mainloop()

Note: since you call your function multiple times before the window is drawn you'll only see the final value. There are plenty of solutions to that on this site. Without knowing more about what your real program looks like it's hard to recommend the best solution to that problem.

  • Related