我的应用程序具有以下结构:
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
.
编写这样的应用程序的正确方法是什么?如何以线程安全或无线程的方式编写?
主事件循环应该在主线程中,绘图线程应该在第二个线程中。
编写这个应用程序的正确方法是这样的:
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)