在 Python Class 中创建按钮时 "self" 和 "root" 是否不同?

Are "self" and "root" different when creating buttons in a Python Class?

在下面的脚本中,button_01 和 button_02 分别在 "self" 和 "root" 中创建。它们的创建位置有什么功能上的区别吗?无论哪种方式,GUI 看起来都一样。

import Tkinter as tk

class App(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        frame1 = tk.Frame(root, padx=2, pady=2, borderwidth=2, relief="raised")
        frame1.pack(side=tk.RIGHT)

        button_01 = tk.Button(self, text ="tk Button 1") # self with tk.Button
        button_01.config(width=15, fg="black", bg="lightskyblue")
        button_01.pack(side=tk.BOTTOM)

        button_02 = tk.Button(root, text ="tk Button 2") # root with tk.Button
        button_02.config(width=15, fg="black", bg="lime")
        button_02.pack(side=tk.BOTTOM)

        button_03 = tk.Button(frame1, text ="tk Button 3") # frame1 with tk.Button
        button_03.config(width=15, fg="black", bg="lightcoral")
        button_03.pack(side=tk.TOP)

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    app.pack(fill="both", expand=True)
#
    root.mainloop()

不,selfroot 不一样。小部件位于 tree-like 层次结构中,具有单个根。当您调用 tk.Tk() 时,您正在创建此根 window.

self代表方法所属的object。在这种情况下,小部件是 tk.Frame 的子类,它是 root 的 child。

尝试给框架一个背景颜色(例如:self.configure(background="red"),你会看到按钮有不同的 parents。在这个具体的例子中,无论你使用 [=11,gui 看起来都一样=] 或 self 只是因为它是一个非常简单的图形用户界面,布局非常简单。