Home > Net >  Classes and tkinter. What does this expression mean?
Classes and tkinter. What does this expression mean?

Time:11-28

I am learning to make applications using tkinter and at the same time I am learning the language itself. I found in one book a description of how to create a second window (settings window). But I don't understand why self.parent = view.parent.

Where does the parent value come from if it is not specified in class PreferencesWindow(): and what is the point separating the two variables(self.parent = view.parent) for? What is view?

My main module (class View):

import preferenceswindow

class View():
    def __init__(self, parent, controller):
        self.controller = controller
        self.parent = parent
        self.create_gui()
    
    def create_edit_menu(self):
        self.edit_menu.add_command(label="Preferences", command=self.on_preference_menu_clicked)

    def on_preference_menu_clicked(self):
        preferenceswindow.PreferencesWindow(self)    

    def create_gui(controller_instance):
        root = Tk()
        root.title("APP")

View(root, controller_instance)
root.mainloop()

And preferences class looks like this:

class PreferencesWindow():
    def __init__(self, view):
        self.parent = view.parent
        self.view = view
        self.create_prefereces_window()
    
    def create_prefereces_window(self):
        self.pref_window = Toplevel(self.parent)
        self.pref_window.title("preferences")
        self.pref_window.transient(self.parent)

In my book this moment is not explained.

CodePudding user response:

These are basic questions relating to how Python (the language) works.

You are asking about parameter passing and class attributes.

Where does the parent value come from if it is not specified in class PreferencesWindow ()

def on_preference_menu_clicked(self):
        preferenceswindow.PreferencesWindow(self) 

This says "Create a new PreferencesWindow, and give it a reference to myself, the calling View class instance."

This is then received by: def __init__(self, view): which means "Initialise the new PreferencesWindow, and refer to anything from the calling View class by name 'view'". This allows PreferencesWindow to access variables from the calling class instance, such as the attribute 'parent'".

self.parent = view.parent - this action is common as a convenience, to avoid having to keep manually passing 'view' around. It captures the value of 'parent' from view.parent which was set in class View ... self.parent = parent

  • Related