在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 实例中。该应用程序在两种情况下均有效。有什么区别?