【发布时间】:2020-03-01 00:43:17
【问题描述】:
在official Python documentation (Python 3.7) 中有以下示例,我试图了解代码的工作原理。我从原始代码中添加了一些 cmets。
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()
我对这段代码有两个问题:
- 在继承tk.Frame的Application类中用
super().__init__(master)初始化tk.Frame类后,self.master已经包含引用到根窗口。我通过前后打印id(self.master)验证了这一点。那么,self.master = master有必要吗?为什么要添加它? - mainloop()方法被添加到Application类的app实例中,继承tk.Frame .但我可以将 mainloop() 方法添加到 tk.Tk 类的 root 实例中。该应用程序适用于这两种情况。有什么区别?
【问题讨论】: