Peter Cunningham Peter Cunningham - 19 days ago 12
Python Question

python Tkinter Bind label to loop event

Hi Im trying to get a label in tkinter to show each item at a time as it loops through a list. My code only shows the last element in label once loop is complete. Shell works fine. Thanks

from Tkinter import*
import tkMessageBox
import time
top = Tk()
top.geometry("500x500+100+200")

w =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1620]
def bello():
for pp in w :
print(pp)
myLabel = Label(top, text=pp).grid(row=6, column=0, sticky='e')
time.sleep(1)

B1 = Button(top, text = "Say Hello", command = bello)
B1.place(x=50, y=50)
top.mainloop()

Answer

You need to use the update() method to update the GUI everytime a new value from the loop is displayed:

from Tkinter import *
import time


top = Tk()
top.geometry("500x500+100+200")

w = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1620]


def bello():
    for pp in w:
        print(pp)
        Label(top, text=pp).grid(row=6, column=0, sticky='e')

        time.sleep(1)
        top.update() #refreshes top before looping to the next element


B1 = Button(top, text="Say Hello", command=bello)
B1.place(x=50, y=50)
top.mainloop()
Comments