python Tkinter将标签绑定到循环事件

时间:2016-11-14 07:09:13

标签: python python-2.7 tkinter

嗨我试图在tkinter中获取一个标签,以便在循环列表时一次显示每个项目。我的代码只显示一旦循环完成后标签中的最后一个元素。 Shell工作正常。感谢

 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()

1 个答案:

答案 0 :(得分:0)

每次显示循环中的新值时,您需要使用update()方法更新GUI:

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()