Fundamental OOP in Tkinter

Viewed 57

I'm relatively new to OOPs and thus know it theoretically. I need a project to be implemented in Tkinter. So, I was going through it. I was just playing around with the most basic code like below

# https://python-textbok.readthedocs.io/en/1.0/Introduction_to_GUI_Programming.html
import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent


root = tk.Tk()
app = MainApplication(root)
app.mainloop()

Here, I can say confidently that MainApplication inherits tk.Frame. So, the root is a TK object and it is passed in MainApplication constructor which assigns it as the parent of the MainApplication object.

So, when we call the app.mainloop(), the MainApplication object is called which in turn can invoke the root somehow because we have the root as a parent of the app object.

Correct me if I understood it wrong.

Now, as I browsed and another popular method people are using is

# https://docs.python.org/2/library/tkinter.html#a-simple-hello-world-program
import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent


root = tk.Tk()
MainApplication(root)
root.mainloop()

Here also, as I can understand the MainApplication is invoked and root becomes the parent of it. But how does that link the MainApplication object with the root object, so that when the root.mainloop() is called, it can refer back to MainApplication object?

Any help is appreciated. Thanks in advance.

1 Answers

This is more about the actual structure of the tkinter module than it is about OOP principles.

mainloop is a method of the Misc class, which is an ancestor of both Tk and Frame. When called, it essentially calls the mainloop method using a reference it has to the root Tk object, so whether you invoke it from root or app, the result is the same.

Related