Skip to content Skip to sidebar Skip to footer

How To Stop A Loop Triggered By Tkinter In Python

I'm new to Python and even more so to tkinter, and I decided to try to create a start and stop button for an infinite loop through Tkinter. Unfortunately, once I click start, it wo

Solution 1:

You're calling while True. Long story short, Tk() has it's own event loop. So, whenever you call some long running process it blocks this event loop and you can't do anything. You should probably use after

I avoided using global here by just giving an attribute to window.

e.g. -

import tkinter

def stop():

    window.poll = False

def loop():

    if window.poll:
        print("Polling")
        window.after(100, loop)
    else:
        print("Stopped long running process.")

window = tkinter.Tk()
window.poll = True
window.title("Loop")
startButton = tkinter.Button(window, text = "Start", command = loop)
stopButton = tkinter.Button(window, text = "Pause", command = stop)
startButton.pack()
stopButton.pack()
window.mainloop()

Post a Comment for "How To Stop A Loop Triggered By Tkinter In Python"