我有这个脚本在tkinter中的主类/循环之前/之前执行一个长时间运行的函数 并且我创建了一个按钮,我完全使用root.destroy()来退出程序,但它关闭了gui并且函数在控制台中继续运行,甚至在创建可执行文件后作为后台进程。
如何解决这个问题?
我的剧本片段:
from tkinter import *
import threading
def download():
#downloading a video file
def stop(): # stop button to close the gui and should terminate the download function too
root.destroy()
class
...
...
...
def downloadbutton():
threading.Thread(target=download).start()
答案 0 :(得分:1)
当主线程死亡时,让线程成为守护进程让它死掉。
def downloadbutton():
t = threading.Thread(target=download)
t.daemon = True
t.start()
例如:
import tkinter as tk
import threading
import time
def download():
while True:
time.sleep(1)
print('tick tock')
def stop(): # stop button to close the gui and should terminate the download function too
root.destroy()
def downloadbutton():
t = threading.Thread(target=download)
t.daemon = True
t.start()
root = tk.Tk()
btn = tk.Button(text = "Start", command=downloadbutton)
btn.pack()
btn = tk.Button(text = "Stop", command=stop)
btn.pack()
root.mainloop()
答案 1 :(得分:0)
有没有一种方法可以一次实现呢?
到目前为止,我一直在使用它:
b_start = Button(app,text='Start',padx=8, pady=20, command=lambda:threading.Thread(target=filters).start())