我在學習如何使用線程模塊。我跟着一起在這裏說明:http://effbot.org/zone/tkinter-threads.htm創建線程安全的Toplevel小部件
我希望測試腳本:
- 打印出來的「計數」每兩秒鐘
- 顯示彈出對話窗口(也每隔2秒)
- 的彈出窗口,應允許積累(如果我不點擊「OK」了一段時間,應該有 多個彈出窗口)
Howev呃,當我運行這個腳本時,它會凍結主窗口,並在一段時間後崩潰。我想我沒有正確實現線程模塊。
有人請看看並指出我做錯了什麼?
這是我到目前爲止已經試過:
from Tkinter import *
import thread
import Queue
import time
class TestApp:
def __init__(self, parent):
self.super_Parent = parent
self.main_container = Frame(parent)
self.main_container.pack()
self.top_frame = Frame(self.main_container)
self.top_frame.pack(side=TOP)
self.bottom_frame = Frame(self.main_container)
self.bottom_frame.pack(side=TOP)
self.text_box = Text(self.top_frame)
self.text_box.config(height=20, width=20)
self.text_box.pack()
self.queue = Queue.Queue()
self.update_me()
def show_popup(self):
self.my_popup = Toplevel(self.main_container)
self.my_popup.geometry('100x100')
self.popup_label = Label(self.my_popup, text="Hello!")
self.popup_label.pack(side=TOP)
self.pop_button = Button(self.my_popup, text="OK", command=self.my_popup.destroy)
self.pop_button.pack(side=TOP)
def write(self, line):
self.queue.put(line)
def update_me(self):
try:
while 1:
line = self.queue.get_nowait()
if line is None:
self.text_box.delete(1.0, END)
else:
self.text_box.insert(END, str(line))
self.text_box.see(END)
self.text_box.update_idletasks()
except Queue.Empty:
pass
self.text_box.after(100, self.update_me)
def pipeToWidget(input, widget):
widget.write(input)
def start_thread():
thread.start_new(start_test, (widget,))
def start_test(widget):
count = 0
while True:
pipeToWidget(str(count) + "\n", widget)
count += 1
time.sleep(2)
widget.show_popup()
root = Tk()
widget = TestApp(root)
start_button = Button(widget.bottom_frame, command=start_thread)
start_button.configure(text="Start Test")
start_button.pack(side=LEFT)
root.title("Testing Thread Module")
root.mainloop()
首先,作爲['thread'](http://docs.python.org/2/library/thread.html)文檔反覆就是說,['threading'](HTTP://docs.python。 org/3/library/thread.html)模塊「提供了一個更易於使用和更高級別的API」,您應該強烈考慮使用它。 – abarnert 2013-04-05 22:28:55
同時......你確定這正是你正在運行的代碼嗎?當我運行它時(OS X 10.8.3與64位Apple Python 2.7.2),它似乎完全按照描述工作,沒有凍結或崩潰。 – abarnert 2013-04-05 22:31:07
@abarnert好的,我會閱讀線程。另外,是的,我正在運行Win 7上的確切代碼Python 2.7.3 – 2013-04-05 22:38:02