Search code examples
pythontkintermainloop

tk.mainloop() vs root.mainloop()?


I have tried to find some Q/A or article about the use of tk.mainloop() vs root.mainloop() with no success.

My question is this: Is there any difference between the 2 uses. It seams to me the correct method would be to use tk_instance_variable_name.mainloop() vs just doing tk.mainloop() but from what I can see both appear to work just fine. Is there any reason one would need to avoid tk.mainloop() or is it just a preference.

If this has been asked before please provide the Q/A link as I cannot seam to find it. I feel like it would have been asked already but no luck search for it.

Can someone maybe explain why tk.mainloop() will work here when I feel like it should not work as it is not being used on the tk instance variable name.

Example using root work just as expected:

import tkinter as tk

root = tk.Tk()
tk.Label(root, text="Test").pack()
root.mainloop() # using the variable name root

Example using tk works fine as well as far as I can tell:

import tkinter as tk

root = tk.Tk()
tk.Label(root, text="Test").pack()
tk.mainloop() # using tk

Solution

  • I have tried to find some Q/A or article about the use of tk.mainloop() vs root.mainloop() with no success.

    My question is this: Is there any difference between the 2 uses.

    Short answer: there is no difference in the normal use case.

    Every widget has an associated tcl interpreter that is created when a root widget is created, whether either explicitly or implicitly. When you call mainloop from any widget, it will run the mainloop function in the interpreter associated with the root window of that widget.

    If you call the mainloop method that is part of the tkinter module (eg: tk.mainloop() in your example), it will call the mainloop function of the default interpreter. The default interpreter is the first interpreter that was created. Thus, in the normal case of a single instance of Tk, tk.mainloop() and root.mainloop() call the exact same code.