Vince
Vince

Reputation: 41

tKinter Multithreading Stopping a Thread

I have created a Python GUI with tKinter in my simple example I have a button that triggers a simple loop that increments a counter. I have succesfully threaded the counter so my GUI won't freeze, however I am having issues with getting it to stop counting. Here is my code:

# threading_example.py
import threading
from threading import Event
import time
from tkinter import Tk, Button


root = Tk()

class Control(object):

    def __init__(self):
        self.my_thread = None
        self.stopThread = False

    def just_wait(self):
        while not self.stopThread:
            for i in range(10000):
                time.sleep(1)
                print(i)

    def button_callback(self):
        self.my_thread = threading.Thread(target=self.just_wait)
        self.my_thread.start()

    def button_callbackStop(self):
        self.stopThread = True
        self.my_thread.join()
        self.my_thread = None


control = Control()
button = Button(root, text='Run long thread.', command=control.button_callback)
button.pack()
button2 = Button(root, text='stop long thread.', command=control.button_callbackStop)
button2.pack()


root.mainloop()

How can I safely make the counter stop incrementing and gracefully close the thread?

Upvotes: 1

Views: 1053

Answers (2)

Novel
Novel

Reputation: 13729

So you want a for loop AND a while loop to run in parallel? Well they can't. As you have them, the for loop is running and won't pay attention to the while loop condition.

You need to make only a single loop. If you want your thread to auto terminate after 10000 cycles, you could do it like this:

def just_wait(self):
    for i in range(10000):
        if self.stopThread:
            break # early termination
        time.sleep(1)
        print(i)

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 386342

You have to check for self.stopThread inside the for loop

Upvotes: 1

Related Questions