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
tk.mainloop()
is a helper function that looks up the root instance and callsroot.mainloop()
. See it here..tk.mainloop()
knows to loop onroot
when its not being told to. Also wouldn't this be a problem for multiple instances of tk. There are some case uses for having more than one instance of tk up so wouldtk.mainloop()
fail in this case?Tk()
instance, the global variabletkinter._default_root
is set if it isn't already. Therefore _default_root is the first instance ofTk()
created. Code here. If you have multiple instances ofTk()
(which you shouldn't) thentkinter.mainloop()
is an alias to themainloop()
method of the firstTk()
instance you created.