无法关闭X按钮上的多线程Tkinter应用 [英] Cannot close multithreaded Tkinter app on X button
本文介绍了无法关闭X按钮上的多线程Tkinter应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用具有以下结构:
My app has the following structure:
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
.
The app runs perfectly, but if I press the X (close) button, it closes the window, but does not stop the process, and sometimes even throws a TclError
.
编写这样的应用程序的正确方法是什么?如何以线程安全的方式或没有线程的方式编写它?
What is the right way to write an app like this? How to write it in a thread-safe way or without threads?
推荐答案
主事件循环应在主线程中,绘图线程应在第二个线程中.
Main event loop should in main thread, and the drawing thread should in the second thread.
编写此应用的正确方法如下:
The right way to write this app is like this:
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()
这篇关于无法关闭X按钮上的多线程Tkinter应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文