Search code examples
pythonmultithreadingpython-2.7tkinterpython-multithreading

tkinter exit/quit/killing function threading out of mainloop


I have this script that execute a long running function out of/before the main class/loop in tkinter and there is a button i created to quit the program completely using root.destroy() but it close the gui and the function keep running in the console or even as a background process after i created the executable file.

How to solve this issue?

snippets of my script:

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

Solution

  • Make the thread a daemon to have it die when the main thread dies.

    def downloadbutton():
        t = threading.Thread(target=download)
        t.daemon = True
        t.start()
    

    For example:

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