我有一个Python3.11.5程序,它使用Tkinter图形用户界面接收用户输入,并在后台运行许多进程.我想知道当用户想要在后台进程仍在运行时取消它时,首选的处理方法是什么.我试图制作取消按钮,使用单独的线程和threading.Event
来表示取消,但我无法让它干净利落地退出.我希望能够点击取消,如果需要的话,花几秒钟的时间,但看到程序结束,我的终端恢复正常,没有错误.
这里有一个最小的例子:
import tkinter as tk
import time
class app(tk.Tk):
def __init__(self):
super().__init__()
self.title("An app")
self.create_widgets()
self.a_process()
def create_widgets(self):
self.text = tk.Label(self, text = "Hello World!")
self.text.pack()
self.cancelButton = tk.Button(self, text = "Cancel", command = self.destroy)
self.cancelButton.pack()
def a_process(self):
for i in range(100):
self.text.config(text = f"Message # {i}")
self.text.update()
time.sleep(1)
def destroy(self):
super().destroy()
if __name__ == "__main__":
root = app()
root.mainloop()
在消息循环运行时点击Cancel会出现以下错误:
Traceback (most recent call last):
File "C:\Users\M.Modeler\geoSieve 1.1\test.py", line 27, in <module>
root = app()
^^^^^
File "C:\Users\M.Modeler\geoSieve 1.1\test.py", line 9, in __init__
self.a_process()
File "C:\Users\M.Modeler\geoSieve 1.1\test.py", line 19, in a_process
self.text.config(text = f"Message # {i}")
File "C:\Users\M.Modeler\AppData\Local\miniconda3\envs\geoSieve\Lib\tkinter\__init__.py", line 1702, in configure
return self._configure('configure', cnf, kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\M.Modeler\AppData\Local\miniconda3\envs\geoSieve\Lib\tkinter\__init__.py", line 1692, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label"
要结束后台进程并干净地退出,我的destroy
方法缺少什么?