如何在无for循环的Python线程中实现tkinter GUI线程的事件驱动终止?
如何在tkinter GUI中终止无for循环的运行线程?
我想通过设置事件从tkinter GUI应用中终止一个运行中的线程,但线程里没法用for循环,得找其他检测事件的方案。
场景说明
在tkinter GUI中点击按钮时,启动线程并设置全局变量:
self.thread = StoppableThread(caller=self) self.thread.start() is_running = 1
再次点击按钮时,检查全局变量状态,若已设置则发送停止请求:
if is_running: is_running = 0 self.thread.stop()
当前线程类代码
import threading from time import sleep class StoppableThread(threading.Thread): def __init__(self, caller=None): super(StoppableThread, self).__init__() self._stop_event = threading.Event() self.caller = caller def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() def run(self) -> None: while True: # check for stop if self.stopped(): break for i in range(10): sleep(1) print('Test') print('Worker done') break
疑问
把while循环改成for循环时一切正常,但业务逻辑里不能用for循环,所以需要其他方式检查self.stopped()的状态。能不能在while循环中实现该检测?
或者有没有其他实现方法?我试过用Process替代Thread,但出现了“process can't pickle tkinter”的错误。
感谢帮助!
内容的提问来源于stack exchange,提问作者Wathfea
相关产品推荐
相关产品推荐

