python – While Loop causes entire program to crash in Tkinter

Tkinter hangs unless it can execute its own infinite loop, root.mainloop. Normally, you can’t run your own infinite loop parallel to Tkinter’s. There are some alternative strategies, however:

Use after

after is a Tkinter method which causes the target function to be run after a certain amount of time. You can cause a function to be called repeatedly by making itself invoke after on itself.

import tkinter

#this gets called every 10 ms
def periodically_called():
    print("test")
    root.after(10, periodically_called)

root = tkinter.Tk()
root.after(10, periodically_called)
root.mainloop()

There is also root.after_idle, which executes the target function as soon as the system has no more events to process. This may be preferable if you need to loop faster than once per millisecond.

Use threading

The threading module allows you to run two pieces of Python code in parallel. With this method, you can make any two infinite loops run at the same time.

import tkinter
import threading

def test_loop():
    while True:
        print("test")

thread = threading.Thread(target=test_loop)
#make test_loop terminate when the user exits the window
thread.daemon = True 
thread.start()

root = tkinter.Tk()
root.mainloop()

But take caution: invoking Tkinter methods from any thread other than the main one may cause a crash or lead to unusual behavior.

Leave a Comment