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

问题描述

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() 有什么区别? 为什么窗口要包含在 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 作为第一个参数并不重要。仅当您有多个窗口时才重要,因为 tkinter 不知道您想要哪个窗口。

当您有 1 个窗口时,tkinter 使用该窗口。这是来自 tkinter/init.py 第 2251 行的代码:

class BaseWidget(Misc):
    def __init__(self,master,widgetName,cnf={},kw={},extra=()):
        ...
        BaseWidget._setup(self,cnf)

    def _setup(self,cnf):
        ...
            if not master: # if master isn't specified
                ...
                master = _default_root # Use the default window
        self.master = master

tkinter Label 继承自 Widget,后者继承自 BaseWidget