pythontkintertoplevelmainloop

In Tkinter, why shouldn't .mainloop() be used with Toplevel() windows, and what is the proper way of doing it?


Currently, whenever I create a new window in a Tkinter program, I use a function with Toplevel(), including .mainloop(), like this:

def MainWindow():
    root = Tk()
    #A button that calls SubWindow()
    root.mainloop()

def SubWindow():
    newWindow = Toplevel()
    #This is where I would put all of my widgets
    newWindow.mainloop()

MainWindow()

I have seen instructions that every Toplevel() window must include it's own .mainloop(). However, I have also seen instructions that every Tkinter program should only ever have a single .mainloop() assigned to the root window. In my program with many subwindows, including a .mainloop() in each of them seems to work fine.

But, if there should only be one root.mainloop(), what are the drawbacks of using many .mainloop()s, and what is the proper way of ending a Toplevel() code block without one?


Solution

  • Tkinter is single threaded, meaning it can only do one thing at a time. Thus, only a single instance of mainloop can run at a time. If you call it twice, only one will be active at a time, and will block until that loop is terminated or the root window is destroyed.

    Tkinter designers oddly decided to make it a common method, but I don't think it should have been. It's really a function of the library rather than a function tied to a specific widget. 99.99% of all tkinter programs never need to be able to call it more than once.

    The drawback of using it more than once is that the code that calls it will block until the loop is finished. Often this isn't a big deal since people tend to call it as the last statement in a function, but I think it can result in events appearing to be processed out of order.

    In my opinion, calling mainloop more than once adds complexity without providing any added value.

    For more information see this answer to Understanding mainloop better, which was written by one of the people who actually works on the underlying tk library.