Reputation: 427
from tkinter import *
window = Tk()
sample = Label(text="some text")
sample.pack()
sample2 = Label(text="some other text")
sample2.pack()
sample.mainloop()
Whats the difference between sample.mainloop()
and window.mainloop()
?
Why should window be included in sample(window, text ="some text")
as the program runs without it.
Upvotes: 1
Views: 157
Reputation: 7680
sample.mainloop
and window.mainloop
call the same function internally so they are the same. They both go in a while True
loop while updating the GUI. They can only exit from the loop when .quit
or window.destroy
is called.
This is the code from tkinter/__init__.py
line 1281:
class Misc:
...
def mainloop(self, n=0):
"""Call the mainloop of Tk."""
self.tk.mainloop(n)
Both Label
and Tk
inherit from Misc
so both of them use that same method. From this:
>>> root = Tk()
>>> root.tk
<_tkinter.tkapp object at 0x00000194116B0A30>
>>> label = Label(root, text="Random text")
>>> label.pack()
>>> label.tk
<_tkinter.tkapp object at 0x00000194116B0A30>
You can see that both of the tk
objects are the same object.
For this line: sample = Label(text="some text")
, it doesn't matter if you put window
as the first arg. It only matters if you have multiple windows as tkinter wouldn't know which window you want.
When you have 1 window, tkinter uses that window. This is the code from tkinter/init.py line 2251:
class BaseWidget(Misc):
def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
...
BaseWidget._setup(self, master, cnf)
def _setup(self, master, cnf):
...
if not master: # if master isn't specified
...
master = _default_root # Use the default window
self.master = master
tkinter Label
inherits from Widget
which inherits from BaseWidget
.
Upvotes: 4