从Tkinter应用程序的Frame和mainloop继承

official Python documentation(Python 3.7)中,有以下示例,我试图了解代码的工作方式。在原始代码中,我添加了一些注释。

import tkinter as tk


class Application(tk.Frame):
    def __init__(self,master=None):
        super().__init__(master)  # Initialize the tk.Frame class
        self.master = master  # Is it necessary?
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self,text="QUIT",fg="red",command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there,everyone!")


def main():
    # Instance of the root window
    root = tk.Tk()
    # Instance of the main frame
    app = Application(master=root)
    # Infinite loop used to run the application
    app.mainloop()  # mainloop() on tk.Tk() instance (root) or tk.Frame() instance (app)?


if __name__ == '__main__':
    main()

关于此代码,我有两个问题:

  • Application 类中的super().__init__(master)初始化 tk.Frame 类之后,该类继承了 tk.Frame ,{{1} }已经包含对根窗口的引用。我通过在前后打印self.master进行了验证。因此,id(self.master)是否必要?为什么添加它?
  • mainloop()方法添加到 Application 类的 app 实例中,该实例继承了 tk.Frame 。但是我可以将 mainloop()方法添加到 tk.Tk 类的 root 实例中。该应用程序在两种情况下均有效。有什么区别?
loveb123 回答:从Tkinter应用程序的Frame和mainloop继承

从tkinter类继承不需要

self.master = master。在这种情况下是多余的。另外,您不需要超级大师。只需执行super().__init__()就可以在这里工作。

不应在框架内使用几何管理器将其自身放置在父容器上。而是从课外调用它。假设您需要将其从pack()更改为grid(),则必须在类中进行更改,而不是简单地将其在主代码中的位置更新。

您的mainloop应该引用根实例。

在创建按钮时,我将传递所有初始参数。只需添加更多代码行即可分别更新每个参数。

最后一件事。如果您稍后将在代码中编辑变量/小部件,请使用self.前缀将其设置为类属性,但是如果没有,则没有理由使用self.,因此我们可以将其从按钮。

重做的代码:

import tkinter as tk


class Application(tk.Frame):
    def __init__(self):
        super().__init__()
        tk.Button(self,text="Hello World\n(click me)",command=self.say_hi).pack(side="top")
        tk.Button(self,text="QUIT",fg="red",command=self.master.destroy).pack(side="bottom")

    def say_hi(self):
        print("hi there,everyone!")


def main():
    root = tk.Tk()
    Application().pack()
    # app = MaxiTeam(root) # not sure what this is unless you meant Application?
    root.mainloop()


if __name__ == '__main__':
    main()
本文链接:https://www.f2er.com/3165082.html

大家都在问