我的应用具有以下结构:
import tkinter as tk
from threading import Thread
class MyWindow(tk.Frame):
... # constructor, methods etc.
def main():
window = MyWindow()
Thread(target=window.mainloop).start()
... # repeatedly draw stuff on the window, no event handling, no interaction
main()
该应用程序运行完美,但是如果我按下X(关闭)按钮,它会关闭窗口,但不会停止该过程,有时甚至会抛出TclError
。
编写这样的应用程序的正确方法是什么?如何以线程安全的方式或没有线程编写它?
答案 0 :(得分:1)
主要事件循环应该在主线程中,而绘制线程应该在第二个线程中。
编写此应用程序的正确方法是这样的:
import tkinter as tk
from threading import Thread
class DrawingThread(Thread):
def __init__(wnd):
self.wnd = wnd
self.is_quit = False
def run():
while not self.is_quit:
... # drawing sth on window
def stop():
# to let this thread quit.
self.is_quit = True
class MyWindow(tk.Frame):
... # constructor, methods etc.
self.thread = DrawingThread(self)
self.thread.start()
on_close(self, event):
# stop the drawing thread.
self.thread.stop()
def main():
window = MyWindow()
window.mainloop()
main()