tkinter root.mainloop with While True loop

tkinter needs mainloop() to work correctly – it uses it to call all needed functions again and again – ie. to get key/mouse events from system, send them to widgets, updates values, and (re)draw widgets in window.

In tkinter don’t use while True which runs forever (or runs longer time) because it blocks mainloop() in tkinter and it can’t update items in window, and it looks like it freezes.

The same problem makes sleep() – it can block mainloop() in tkinter.

You can use root.after(time_ms, function_name_without_brackets ) (before mainloop())
to run some function with delay – so it can be used like sleep(). And if function will run the same after(...) then it will work like loop. And this way tkinter will have time to update widgets in window.


So put all code from your while True (except mainloop()) in function and call it using after().
And use second after() in place of sleep().

import tkinter as tk

master = tk.Tk()

def my_mainloop():
    print "Hello World!"
    master.after(1000, my_mainloop)  # run again after 1000ms (1s)

master.after(1000, my_mainloop) # run first time after 1000ms (1s)

master.mainloop()

And if you can’t convert while-loop and use after() then you may have to run loop in separated thread. But tkinter (like many other GUIs)` doesn’t like to work in second thread and all changes in GUI you would have to do in main thread.

Leave a Comment