Understanding Parent and Controller in Tkinter __init__

I want to understand what the following code means:

class PageOne(tk.Frame): def __init__(self, parent, controller): 

What is self , parent and controller ? What is the role and scope of these tools here?

I believe that self is similar to this in Java, but what is the use of parent and controller ?

Later in the code stream I see:

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

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

+5
python tkinter
Sep 30 '15 at 11:11
source share
1 answer

Roughly speaking, the source code 1 tried to use pseudo- MVC (model, view and controller). Although without the "model" part - there was only a "view" (some frames) and a "controller" (main application). Therefore, a reference to the controller object. The source code was actually written to show how to "stack" the frames, so the MVC implementation is very small and not documented enough, since this was not an example point.

To answer your specific questions:

self represents the current object. This is the usual first parameter for any class method. As you suggested, this is similar to Java.

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

the controller is another object that is designed to act as a common point of interaction for several pages of widgets. This is an attempt to separate the pages. That is, each page should not know about other pages. If he wants to interact with another page, for example, so that it is visible, he may ask the controller to make it visible.

You asked: "There is a function already defined as show_frame, but why is the controller used to call this function?" Note that show_frame is defined in a separate class, in this case the main program class. It is not defined in other classes. In order for other classes to call it, they must call it an instance of the main class. This instance is called controller in the context of these other classes.




1 Note. Despite the fact that you probably found the source code in the online tutorial, it originally came from this stackoverflow answer: Switching between two frames in tkinter

+10
Sep 30 '15 at 11:49
source share



All Articles