Vasanth Nag K V Vasanth Nag K V - 1 year ago 136
Python Question

Understanding parent and controller in Tkinter __init__

I want to understand what the below code means:

class PageOne(tk.Frame):

def __init__(self, parent, controller):

What are
? What is the role and scope of these tools here?

I believe
is similar to
in Java, but what's the use of

Later in the code flow I can see:

button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))

There is a function already defined called
, but why is the controller being used to call this function?

Answer Source

Roughly speaking, the original code1 attempted to use a pseudo-MVC (model, view and controller) architecture. Though without the "model" part -- there was just a "view" (some frames) and a "controller" (the main application). Hence, the reference to a controller object. The original code was actually written to show how to "stack" frames, so it's MVC implementation is very shallow and under-documented since that wasn't the point of the example.

To answer your specific questions:

self represents the current object. This is a common first parameter for any method of a class. As you suggested, it's similar to Java's this.

parent represents a widget to act as the parent of the current object. All widgets in tkinter except the root window require a parent.

controller represents some other object that is designed to act as a common point of interaction for several pages of widgets. It is an attempt to decouple the pages. That is to say, each page doesn't need to know about the other pages. If it wants to interact with another page, such as causing it to be visible, it can ask the controller to make it visible.

You asked "There is a function already defined called show_frame, but why is the controller being used to call this function?" Notice that show_frame is defined in a separate class, in this case the main program class. It is not defined in the other classes. For the other classes to be able to call it, they must call it on an instance of the main class. That instance is named controller in the context of these other classes.

1 Note: even though you likely found the original code in an online tutorial, it originally came from this stackoverflow answer: Switch between two frames in tkinter

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download