I have a problem with the termination of the while loop which is started via the thread option.
The stop variable has the values True and False. Should I start the Stop option via a thread?
The complete program starts, a loop is started that prints the word TEST every second, clicking the STOP button I get nothing!
I even think my stop is disabled when the loop is in progress!
import tkinter as tk
import threading
import time
class App(tk.Tk):
def __init__(self):
super().__init__()
global stop
stop = False
# If the STOP button is pressed then terminate the loop
def button_stop_command():
global stop
stop = True
# Start loop
def button_start_command():
global stop
stop = False
while stop == False:
print("TEST")
time.sleep(1)
# Button starter with thread
def button_starter():
t = threading.Thread(target=button_start_command)
t.start()
# self windows size
window_width = 1024
window_height = 600
# get the screen dimension
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)
# set the position of the window to the center of the screen
self.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
# Resize main window xy, on/off, 0 or 1 .
self.resizable(0, 0)
# Main window on top of stack.
self.attributes('-topmost', 1)
# Windows transparency.
self.attributes('-alpha', 1)
# Button START
# self.button = tk.Button(self, text='START', width = 20, height = 10, command = self.button_clicked)
self.button = tk.Button(self, text='START', width = 20, height = 10, command = button_start_command)
self.button.place(x = 600, y = 350)
# Button STOP
# self.button = tk.Button(self, text='START', width = 20, height = 10, command = self.button_clicked)
self.button_stop = tk.Button(self, text='STOP', width = 20, height = 10, command = button_stop_command)
self.button_stop.place(x = 800, y = 350)
if __name__ == "__main__":
app = App()
app.mainloop()
Stop loop with STOP button!
Answer to your question "should I start the Stop option via a thread?" is "Yes,I think you should.You've almost done!!"
Only change command = button_start_command
to command = button_starter
and this worked in my envronment!!