Is there any way to stop a 'tkinter's mainloop' thread in python?

Viewed 151

I am new to GUI programming, I wanted to create a simple waiting screen in my program, I tried and this is what I came upto. The problem is the waiting screen for the process 'func' won't stop even if the process func terminates. Is there any way of stopping the thread 't', or is there a better solution to the problem?

from threading import Thread
from tkinter import *
from tkinter.ttk import Progressbar
from tkinter import ttk

def func():
    t = Thread(target = waiting).start()
    for i in range(1000):
        print(i)
    #myProgress.stop()



def waiting():
    root = Tk()
    root.geometry('400x250')

    myProgress = ttk.Progressbar(root ,orient =  HORIZONTAL, length = 200 , mode = 'determinate' )
    myProgress.pack(pady = 50)

    #myButton = Button(root , text = ' Button ' , command = func).pack()
    myProgress.start(10)
    root.mainloop()

func()
1 Answers

You should NOT "stop" a thread by killing it or whatever. It should be stopped on itself from function for example with variable stop_threads. For example if var is True let's stop the thread. Code:

import threading 
import time 
  
def run(): 
    while True: 
        print('thread running') 
        global stop_threads 
        if stop_threads: 
            break
  
stop_threads = False
t1 = threading.Thread(target = run) 
t1.start() 
time.sleep(1) 
stop_threads = True
t1.join() 
print('thread killed') 
Related