繁体   English   中英

Python Tkinter Threading-如何在用户关闭GUI时结束/杀死/停止线程

[英]Python Tkinter Threading - How to end / kill / stop thread when user closes GUI

如果我有一个非for循环线程任务与tkinter一起运行,例如time.sleep(seconds)如何在任务结束之前或time.sleep()结束之前安全地结束该任务。

如果运行该程序并单击按钮,然后关闭GUI窗口,则几秒钟后仍将在解释器窗口中打印finished

请注意,在这种情况下, time.sleep()只是长时间运行的非for循环函数的占位符。

# python 3 imports
import tkinter as tk
import threading
import queue
import time

def center_app(toplevel):
    toplevel.update_idletasks()
    w = toplevel.winfo_screenwidth() - 20
    h = toplevel.winfo_screenheight() - 100
    size = tuple(int(Q) for Q in toplevel.geometry().split("+")[0].split("x"))
    toplevel.geometry("%dx%d+%d+%d" % (size + (w / 2 - size[0] / 2, h / 2 - size[1] / 2)))

class app(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.protocol("WM_DELETE_WINDOW", self.USER_HAS_CLOSED_WINDOW)
        self.b1 = tk.Button(self, text = "*** Start Thread ***", font = ("Arial",25,"bold"), command = self.func_1)
        self.b1.pack(side = "top", fill = "both", expand = True)
        center_app(self)
        self.queue = queue.Queue()

    def USER_HAS_CLOSED_WINDOW(self, callback = None):
        print ("attempting to end thread")
        # end the running thread
        self.destroy()

    def func_1(self):
        self.b1.config(text = " Thread Running ")
        self.b1.update_idletasks()
        t = ThreadedFunction(self.queue).start()
        self.after(50, self.check_queue)

    def check_queue(self):
        try:
            x = self.queue.get(0) # check if threaded function is done
            self.b1.config(text = "*** Start Thread ***")
            self.b1.update_idletasks()
        except:
            self.after(50, self.check_queue)

class ThreadedFunction(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self, daemon = True)
        self.queue = queue
    def run(self):
        time.sleep(10) # how to end this if user closes GUI
        print ("finished")
        self.queue.put("result")

a = app()
a.mainloop()

我已经创建了一个函数USER_HAS_CLOSED_WINDOW来捕获关闭窗口的用户,我当时以为我可以放一些东西来结束正在运行的线程,但是我不确定如何做。

我猜另一个选择是在线程上放置适当的timeout并以某种方式使用.join() 但是我也不知道该怎么做

似乎在使用要中断的time.sleep时,应该使用Event对象并使用wait()方法,而不是time.sleep

可能可以帮助您:

  1. https://stackoverflow.com/a/5205180
  2. https://stackoverflow.com/a/38828735

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM