Updating labels each time function is called (Tkinter)

So I'm trying to make it so that my labels update every time my button is clicked, but the text stays the same. It works for the first button click, but it doesn't update each time afterwards.

          for x in range(24):
            print(ret_val[x])
            new_L = Label(root, text=ret_val[x] + "\n")
            new_L.pack()

I'm looping through a fixed-size list and trying to display the contents of the list each time around.

Posted May 12, 2022, 9:09 PM UTC

14
socal_nerdtastic•

First, make 24 blank Labels and store them in a list in your setup section somewhere.

labels = []
for x in range(24):
    new_L = Label(root)
    new_L.pack()
    labels.append(new_L)

Then, in your function, update each label with the appropriate text:

# could use zip() here for some more cool points
for x in range(24):
    labels[x].configure(text=ret_val[x] + "\n")
2
shiftybyte•

This loops creates 24 new labels.

You need to use .configure to change the text.

https://stackhowto.com/how-to-change-label-text-on-button-click-in-tkinter/

1
LanceBPCOP•

Would I have to create the 24 labels before I call the function?

1
shiftybyte•

Yes, you create the labels once, and then you change them every time you want the text to be changed.

Take a look at the examples and explanations in the link i posted on the previous comment.

1