I am using tkinter. Here is my code. There are two buttons on the GUI. STRAT and STOP. If I press START then a counter up to 30 should be printed on the shell but if I press STOP anytime before the counter reach 30 then the loop should terminate and back to the man loop of GUI. Where should I add thread t ?
import time
from tkinter import *
root = Tk()
root.title("Loop Terminate")
time.sleep(0.5)
# Function button_stop
def button_stop():
# If the STOP button is pressed then terminate the loop
i = 1
# Function button_start
def button_start():
j = 1
while j <= int(20):
print("Loop Index = " + str(j))
time.sleep(0.1)
j = j+1
# Button START
button_start = Button(root, text = "START", padx=30, pady=20, command=button_start)
button_start.grid(columnspan=1, row=1,column=0)
# Button STOP
button_stop = Button(root, text = "STOP", padx=33, pady=20, command=button_stop)
button_stop.grid(row=2,column=0)
Try the following. You can have a global variable stop that’s used to control whether the loop stops. When you click the START button, a new thread is created so that the loop runs in a background thread. Note that I renamed your functions because previously, you had functions and Button objects with the same name, which caused problems when I was trying to refer to the function after the Button object of the same name had been created.
import time
import threading
from tkinter import *
root = Tk()
root.title("Loop Terminate")
time.sleep(0.5)
stop = False
def button_stop_command():
# If the STOP button is pressed then terminate the loop
global stop
stop = True
def button_start_command():
global stop
stop = False
j = 1
while j <= 20 and not stop:
print("Loop Index = " + str(j))
time.sleep(0.1)
j = j+1
def button_starter():
t = threading.Thread(target=button_start_command)
t.start()
# Button START
button_start = Button(root, text="START", padx=30, pady=20, command=button_starter)
button_start.grid(columnspan=1, row=1,column=0)
# Button STOP
button_stop = Button(root, text="STOP", padx=33, pady=20, command=button_stop_command)
button_stop.grid(row=2, column=0)
root.mainloop()