您的 tkinter 程序已经运行了一个“while”循环——mainloop。在大多数情况下,您不需要该循环内的另一个循环。
使用这个循环的模式是创建一个函数来为循环体做你想做的事情。它应该只进行一次循环迭代。一旦完成,它需要安排自己在将来的某个时间使用after 再次被调用。未来多远定义了循环运行的速度。
这是一个每秒检查一次队列的示例:
import Tkinter as tk
import Queue as queue
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.queue = queue.Queue()
buttonFrame = tk.Frame(self)
for i in range(10):
b = tk.Button(buttonFrame, text=str(i),
command=lambda button=i: self.press(button))
b.pack(side="top", fill="x")
self.lb = tk.Listbox(self, width=60, height=20)
self.vsb = tk.Scrollbar(self, command=self.lb.yview)
self.lb.configure(yscrollcommand=self.vsb.set)
buttonFrame.pack(side="left", fill="y")
self.vsb.pack(side="right", fill="y")
self.lb.pack(side="left", fill="both", expand=True)
self.manage_queue()
def press(self, i):
'''Add a button to the queue'''
item = "Button %s" % i
self.queue.put(item)
self.log("push", item)
def log(self, action, item):
'''Display an action in the listbox'''
message = "pushed to queue" if action == "push" else "popped from queue"
message += " '%s' (queue size %s)" % (item, self.queue.qsize())
self.lb.insert("end", message)
self.lb.see("end")
def manage_queue(self):
'''pull an item off the queue and act on it'''
try:
item = self.queue.get_nowait()
self.log("pop", item)
except queue.Empty:
pass
# repeat again in 1 second
self.after(1000, self.manage_queue)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()