window = Tk() 在此程序中的功能是什么,因为将其省略会给出相同的输出

what is the function of window = Tk() in this program as leaving it out gives the same output

from tkinter import *
    
window = Tk()
    
sample = Label(text="some text")
sample.pack()
    
sample2 = Label(text="some other text")
sample2.pack()
    
sample.mainloop()

sample.mainloop()window.mainloop()有什么区别? 为什么 window 应该包含在 sample(window, text ="some text") 中,因为程序在没有它的情况下运行。

sample.mainloopwindow.mainloop 在内部调用相同的函数,因此它们是相同的。在更新 GUI 时,它们都进入 while True 循环。它们只能在调用 .quitwindow.destroy 时退出循环。

这是来自 tkinter/__init__.py 第 1281 行的代码:

class Misc:
    ...
    def mainloop(self, n=0):
        """Call the mainloop of Tk."""
        self.tk.mainloop(n)

LabelTk 都继承自 Misc,因此它们都使用相同的方法。来自:

>>> root = Tk()
>>> root.tk
<_tkinter.tkapp object at 0x00000194116B0A30>
>>> label = Label(root, text="Random text")
>>> label.pack()
>>> label.tk
<_tkinter.tkapp object at 0x00000194116B0A30>

您可以看到 tk 对象是同一个对象。

对于这一行:sample = Label(text="some text"),将window作为第一个参数并不重要。仅当您有多个 windows 时才重要,因为 tkinter 不知道您想要哪个 window。

当你有 1 个 window 时,tkinter 会使用那个 window。这是来自 tkinter/init.py 第 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 继承自 Widget 继承自 BaseWidget.