python3.5
我需要一个GUI和线程来处理重型计算。线程输出某些状态信息取决于计算结果。现在,我尝试以下代码似乎正常。但是,当我按下窗口的关闭(x)按钮时,gui冻结了。
import tkinter as tk
import threading
import time
import tkinter.scrolledtext as scrolledtext
class GUI:
def __init__(self, master):
self.master = master
self.scrolledtext = scrolledtext.ScrolledText()
self.scrolledtext['font'] = ('consolas', '12')
self.scrolledtext.pack(expand=True, fill='both')
self.scrolledtext.insert(tk.END, "testn")
self.master.protocol("WM_DELETE_WINDOW", self.closeme)
self.threadTask = ThreadedTask(self.scrolledtext)
self.threadTask.start()
def closeme(self):
self.threadTask.stop()
self.threadTask.join()
self.master.destroy()
class ThreadedTask(threading.Thread):
def __init__(self,scrolledtext):
threading.Thread.__init__(self)
self.scrolledtext = scrolledtext
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def run(self):
while(not self._stop_event.is_set()):
time.sleep(1)
# to do: something heavy computation....
self.scrolledtext.insert(tk.END, "123n")
self._stop_event.wait(1)
root = tk.Tk()
root.title("Test")
main_ui = GUI(root)
root.mainloop()
我已经更改了关闭功能。现在尝试,在我的debian上它起作用。
def closeme(self):
if self.threadTask.is_alive():
self.scrolledtext.insert(tk.END, "I', stoppingnpress close again")
self.threadTask.stop()
#self.threadTask.join()
else:
self.master.destroy()