Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread doesn't restart after it is killed in Python with Tkinter

I have a simple GUI to test threading as shown below:

enter image description here

Basically when I click button 1 the thread starts and button 2 kills the thread. But after the thread is killed, clicking button 1 doesn't start the thread anymore.

Below is the entire code

from tkinter import*
import time
from threading import *
import threading

x = 0

root = Tk()
root.title("Test")

e = Entry(root, width=35, bg="blue", fg="white", borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)


    
def myThread():
    # Call work function
    t1=Thread(target=callback)
    t1.start()        
    
stop_event = threading.Event()    
def callback():
  
    #print("sleep time start")
  
    for i in range(10):
        #print(i)
        e.insert(0, i)
        time.sleep(1)
        if stop_event.is_set():
            break
        
def stop():
  
    stop_event.set()
  
    
button_1 = Button(root, text="1", padx=40, pady=20, command = myThread)
button_2 = Button(root, text="2", padx=40, pady=20, command = stop)

#put buttons on the screen

button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)

root.mainloop()

What could be done?

like image 372
ty_1917 Avatar asked Feb 22 '26 00:02

ty_1917


1 Answers

When you press the stop button, stop_event is set. When you press the start button again, stop_event is still set, so after inserting 0 it will stop. To fix this, add stop_event.clear() to the start of myThread and move the definition of stop_event before myThread:

stop_event = threading.Event()  
    
def myThread():
    # Call work function
    stop_event.clear()
    t1=Thread(target=callback)
    t1.start()    
like image 70
Henry Avatar answered Feb 24 '26 14:02

Henry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!