time.sleep() not working as expected last

Viewed 48

I have a canvas with 30 labels, the text is updated (always different) using a button. I have 2 questions:

1.-why the command time.sleep doesn't work as I expect?

i = 0
while len(words) >= 1:
if i = 1:
    canvas.itemconfig(label1, text  = "text")
    time.sleep(3)

if i = 2: 
    canvas.itemconfig(label2, text  = "text")
    time.sleep(3)

if i = 3:
    canvas.itemconfig(label3, text  = "text")
    time.sleep(3)

if i = 4:
    canvas.itemconfig(label4, text  = "text")
    time.sleep(3)

if i = 5:
    canvas.itemconfig(label5, text  = "text")
    time.sleep(3)
i+= 1

And so on until 30, I want to set the label and then wait 3 seconds to set the next label and so on, but the code waits 15 seconds and sets all the labels at the same time at the end.

2.-is there a way to refer to my labels using "for" to avoid writing 30 lines? All my labels are called label1, label2, label3... I have done this in other language with something like this

For i in range(1,31):
    canvas.itemconfig(label[i], text = "text")

Sorry if I wrote something wrong since I did it in my phone

1 Answers

When you use sleep in tkinter, you're freezing the program so nothing happens. If you want to make a change after a given time, use the after method.

root.after(1000, myfunction)   # call myfunction after 1 second

As for the label updates, you are correct. Creating a label array would make it easier.

With the current label names, you can add them all to a list then iterate the list.

lbllst = [label1, label2, label3, ......]
for lbl in lbllist:
    canvas.itemconfig(lbl, text = "text")
Related