In the official Python documentation (Python 3.7) there's the following example and I'm trying to understand how the code works. From original code I added some comments.
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()
I've two questions about this code:
- After initialize tk.Frame class with
super().__init__(master)
in Application class, which inherits tk.Frame,self.master
already contains reference to the root window. I verified that by printingid(self.master)
before and after. So, isself.master = master
necessary? Why was it added? - The mainloop() method is added to app instance of Application class, which inherits tk.Frame. But I could add the mainloop() method to root instance of tk.Tk class. The application works in both cases. What is the difference?