Terminating Threads

Hello,

This is my first multithreading Tkinter GUI and I have errors when closing.

The GUI is running 4 thread routines, and they seem to be running ok. However, when I select the shutdown button that calls the terminate_threads() fucntion, the Tkinter GUI closes but I always get errors. Can you confirm if I am terminating the threads correctly?

Also please advise if the starting and handling of the threads are incorrect?

Multi thread code running at the bottom of the Tkinter mainloop:

def do_every (interval, worker_func, iterations = 0): 
  
   if iterations != 1:
    threading.Timer (
      interval,
      do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]
    ).start ()

  worker_func ()


# call main_control every 10 seconds
do_every (10, main_control)  

# call write_to_csv every 5 seconds
do_every (5, write_to_csv)  

# call duration_timer every 1 seconds
do_every (1, duration_timer)

# call one_second_timer every 1 seconds
do_every (1, one_second_timer)  

        
root.mainloop()

Terminate threads on closing of program:

def terminate_threads():

   # terminate all threads
   root.destroy()
   sys.exit()
   root.quit()


Many thanks,

Tuurbo46

sys.exit will raise SystemExit, so root.quit() is unreachable.

2 Likes

There’s a threading.Timer().cancel() but you’ll need to adjust your code to not throw the timer object away. Something like:

def do_every (interval, worker_func, iterations = 0): 
  
   if iterations != 1:
    timer = threading.Timer (
      interval,
      do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]
    )
    timer.start ()
    return timer

main_control_timer = do_every (10, main_control)  

Then the shutdown code can call main_control_timer.cancel().