【问题标题】:tkinter exit/quit/killing function threading out of mainlooptkinter 退出/退出/杀死函数线程出主循环
【发布时间】:2018-11-26 17:37:32
【问题描述】:

我有这个脚本在 tkinter 的主类/循环之外/之前执行一个长时间运行的函数 我创建了一个按钮来使用 root.destroy() 完全退出程序,但它关闭了 gui,并且该函数在我创建可执行文件后继续在控制台中运行,甚至作为后台进程运行。

如何解决这个问题?

我的脚本的sn-ps:

 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()

【问题讨论】:

    标签: python multithreading python-2.7 tkinter python-multithreading


    【解决方案1】:

    有没有一种方法可以在一行中实现它?

    我目前正在使用这个:

    b_start = Button(app,text='Start',padx=8, pady=20, command=lambda:threading.Thread(target=filters).start())
    

    【讨论】:

      【解决方案2】:

      使线程成为守护进程,以便在主线程死亡时让它死亡。

      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()
      

      【讨论】:

      • 谢谢 Novel,我使用了您提供的代码并且关闭了 gui,但下载功能仍在控制台中运行我现在正在搜索与线程守护进程相关的其他类似问题...
      • @SarahJohnson 它对我有用。我编辑了我的答案以包含minimal reproducible example,请对您的问题做同样的事情。
      • 我刚刚发现我有一个混乱和过多的代码测试行调用按钮功能等,我将它们注释掉,它终于奏效了!非常感谢小说,我非常欣赏它......你为我节省了很多时间和精力~爱与光
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2019-03-08
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多