When do I need to call mainloop in a Tkinter application?

The answer to your main question is, you must call mainloop once and only once, when you are ready for your application to run.

mainloop is not much more than an infinite loop that looks roughly like this (those aren’t the actual names of the methods, the names merely serve to illustrate the point):

while True:
    event=wait_for_event()
    event.process()
    if main_window_has_been_destroyed(): 
        break

In this context, “event” means both the user interactions (mouse clicks, key presses, etc) and requests from the toolkit or the OS/window manager to draw or redraw a widget. If that loop isn’t running, the events don’t get processed. If the events don’t get processed, nothing will appear on the screen and your program will likely exit unless you have your own infinite loop running.

So, why don’t you need to call this interactively? That’s just a convenience, because otherwise it would be impossible to enter any commands once you call mainloop since mainloop runs until the main window is destroyed.

Leave a Comment