Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to update Label text in Python Tkinter without calling pack() again

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading