How do you create a Tkinter GUI stop button to break an infinite loop?

Tkinter is a Python library used to create GUI-based applications. Sometimes you need to create a loop that continuously updates the interface, like displaying text or processing data. To control such loops, you can use a global variable with Start and Stop buttons.

The key is using win.after() instead of a traditional while loop, which would freeze the GUI. This method schedules function calls without blocking the interface.

Example

Here's how to create a controllable loop with Start and Stop buttons ?

# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win = Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Define a function to print something inside infinite loop
run = True

def print_hello():
    if run:
        Label(win, text="Hello World", font=('Helvetica', 10, 'bold')).pack()
    # After 1 sec call the print_hello() again
    win.after(1000, print_hello)

def start():
    global run
    run = True

def stop():
    global run
    run = False

# Create buttons to trigger the starting and ending of the loop
start_btn = Button(win, text="Start", command=start)
start_btn.pack(padx=10)

stop_btn = Button(win, text="Stop", command=stop)
stop_btn.pack(padx=15)

# Call the print_hello() function after 1 sec.
win.after(1000, print_hello)
win.mainloop()

Output

Tkinter GUI - Stop Button Example Start Stop Hello World Hello World Hello World Hello World Click to stop the loop

How It Works

The program uses a global variable run to control the loop execution. When run is True, the function creates new labels. The win.after(1000, print_hello) schedules the function to run again after 1000 milliseconds (1 second).

The Stop button sets run = False, preventing new labels from being created, while the Start button resets run = True to resume the process.

Key Points

  • Use win.after() instead of while True to avoid freezing the GUI
  • Global variables control the loop state
  • The function continues to be scheduled but only executes when run is True

Conclusion

Use global variables with win.after() to create controllable loops in Tkinter. This approach keeps the GUI responsive while allowing you to start and stop background processes with buttons.

Updated on: 2026-03-25T22:16:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements