Consider a case of running a process in a loop and we want to stop the loop whenever a button is clicked. Generally, in programming languages, to stop a continuous while loop, we use a break statement. However, in Tkinter, in place of the while loop, we use after() to run the defined function in a loop. To break the continuous loop, use a global Boolean variable which can be updated to change the running state of the loop.
For the given example,
Create a global variable that works similar to the flag in a loop.
Define two buttons, Start and Stop, to start and stop the execution.
Define two functions, on_start() and on_stop(), to deliver the update on the loop.
Example
# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") running = True # Define a function to print the text in a loop def print_text(): if running: print("Hello World") win.after(1000, print_text) # Define a function to start the loop def on_start(): global running running = True # Define a function to stop the loop def on_stop(): global running running = False canvas = Canvas(win, bg="skyblue3", width=600, height=60) canvas.create_text(150, 10, text="Click the Start/Stop to execute the Code", font=('', 13)) canvas.pack() # Add a Button to start/stop the loop start = ttk.Button(win, text="Start", command=on_start) start.pack(padx=10) stop = ttk.Button(win, text="Stop", command=on_stop) stop.pack(padx=10) # Run a function to print text in window win.after(1000, print_text) win.mainloop()
Output
Run the above code to test the loop for a certain condition.
If we will run the above code and click the Start button, then it will print "Hello World" text in a loop that can be stopped by clicking the "Stop" Button.
Hello World Hello World Hello World Hello World Hello World Process finished with exit code 0