Python:tkinter关闭窗口后如何停止线程

一:使用pyinstaller打包成exe执行文件进行运行。在调试过程中,发现当gui界面的窗口关闭后,后台程序还在运行,并没有终止程序。

二:解决方法

让每一个子线程在开启之前设置一个守护线程,这样就可以在主线程结束之后,同时也能停止子线程。

Button(myWindow, text='Apply', command=self.download_customers).place()

def download_customers(self):
    thread = threading.Thread(target=self.download)
    thread.setDaemon(True)  # 设置线程为守护线程,防止退出主线程时,子线程仍在运行
    thread.start()

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Python 中,可以使用 `threading.Event()` 来创建一个事件对象,用于控制线程的启动和停止。具体来说,可以在主窗口关闭时,设置一个事件标志,然后在子线程中检查这个标志,如果检测到该标志,就停止线程。 下面是一个示例代码: ```python import threading import tkinter as tk class MyThread(threading.Thread): def __init__(self, stop_event): super().__init__() self.stop_event = stop_event def run(self): while not self.stop_event.is_set(): # 线程执行的代码 pass class MyApp: def __init__(self): self.root = tk.Tk() self.stop_event = threading.Event() self.thread = MyThread(self.stop_event) self.thread.start() self.root.protocol("WM_DELETE_WINDOW", self.on_close) self.root.mainloop() def on_close(self): self.stop_event.set() # 设置事件标志,停止线程 self.thread.join() # 等待线程结束 self.root.destroy() if __name__ == '__main__': app = MyApp() ``` 在上面的代码中,`MyThread` 类表示一个子线程,其中 `stop_event` 参数用于控制线程的启动和停止。在 `MyApp` 类中,我们创建了一个 `stop_event` 对象,并将其传递给 `MyThread` 对象。然后,在主窗口关闭时,我们调用 `on_close` 方法,该方法设置事件标志,停止线程,并等待线程结束。最后,我们销毁主窗口。 请注意,上面的代码只是一个示例,具体实现方式可能因具体情况而异。例如,如果您的线程需要执行一些长时间运行的操作,您可能需要在停止线程之前先等待其完成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值