1
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.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
Kun.tito
  • 165
  • 1
  • 7

1 Answers1

4

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.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • Saying they stop code execution isn't what happens. No code has stopped executing. It is simply that `mainloop()` doesn't return until the window is destroyed. Code is still executing in the mean time. – Bryan Oakley Feb 13 '21 at 22:38
  • I is what I meant. I will change my answer – TheLizzard Feb 14 '21 at 10:20