Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - What is a parent/master that initialize a tkinter class?

Note

The example code is an abridged version but can run with a basic function. Please focus on class MainWindow(tk.Frame)

Questions

What kind of object can play the role of the parent or master for tkinter class initialization?

In my case, see the example code, why can not pass self as parent to ProjectInfo(...) or ConfirmItems(...) in class MainWindow(tk.Frame)? It would pop up an empty window if using self instead of self.parent.

Reference

This question originates from my comments on Best way to structure a tkinter application, which means it fails to pass self as parent.

I would like to issue a new question to follow that discussions.

import tkinter as tk
from tkinter import messagebox
from collections import OrderedDict

class ProjectInfo(tk.Frame):
    def __init__(self, parent, controller, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.controller = controller
        self.widgets_init()

    def widgets_init(self):
        tk.Label(self,
                    text = "Rock Controller!",
                    width = 10,
                    anchor = "w",
                    justify = "left").grid(row = 0, column = 0)
        tk.Label(self,
                    text = "Input Name: ").grid(row = 1, column = 0)
        self.entry = tk.Entry(self)
        self.entry.grid(row = 1, column = 1)

class ConfirmItems(tk.Frame):
    def __init__(self, parent, frames, controller, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent
        self.frames = frames
        self.controller = controller
        self.widgets_init()

    def update_entries(self):
        self.controller.project_info.name = self.controller.project_info.entry.get()

    def update_frames(self):
        self.message = 'Click Cancel go back to reset!
'
        for key, values in self.frames.items():
            for v in values:
                x = getattr(key, v)
                self.message += v + ': ' + str(x) + '
'

    def show_settings(self):
        answer = tk.messagebox.askokcancel("Check Settings", self.message)
        if answer in ["yes", 1]:
            self.quit()

    def combine_funcs(self, *funcs):
        def combined_func(*args, **kwargs):
            for f in funcs:
                f(*args, **kwargs)
        return combined_func

    def widgets_init(self):
        self.cancel = tk.Button(self,
                                text = "Cancel",
                                command = self.quit)
        self.cancel.grid(row = 0, column = 0)

        self.submit = tk.Button(self,
                                text = "Submit",
                                command = self.combine_funcs(
                                                            self.update_entries,
                                                            self.update_frames,
                                                            self.show_settings))
                                # command = lambda:[self.update_frames(), self.show_settings()]
        self.submit.grid(row = 0, column = 1)

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

        self.project_info = ProjectInfo(self.parent, self.controller)
        self.project_info.grid(row = 0)
        self.widgets_init()

        self.confirm_items = ConfirmItems(self.parent, self.frames, self.controller)
        self.confirm_items.grid(row = 1)

    def widgets_init(self):
        self.dict_list = [(self.project_info, ('name',))]
        self.frames = OrderedDict(self.dict_list)

def main():
    root = tk.Tk()
    root.title("Welcome to Controller World!")
    root.geometry("300x300")
    gui = MainWindow(root)
    root.mainloop()

if __name__ == "__main__":
    main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What kind of object can play the role of the parent or master for tkinter class initialization?

Any tkinter widget can play the role of parent or master, though most often it will be the root window, a toplevel window, or a frame.

In my case, see the example code, why can not pass self as parent to ProjectInfo(...) or ConfirmItems(...) in class MainWindow(tk.Frame)?

There is nothing in your code preventing you from passing self as the parent.

It would pop up an empty window if using self instead of self.parent.

In the case of using self as the parent for ProjectInfo, self refers to the instance of MainWindow. I don't see anywhere where you are calling pack or grid on that instance. If the parent is not visible, none of its children will be visible.

You need to call pack or grid on the gui variable. Since it is designed to be the only widget in the root window, pack makes the most sense.

def main():
    ...
    gui = MainWindow(root)
    gui.pack(side="top", fill="both", expand=True)
    ...

As a general rule of thumb, if you have a class that inherits from a widget and it creates other widgets, those widgets should always be children of self or one of its descendants, never its own parent. Having a class put child widgets in its parent completely defeats the purpose of inheriting from tk.Frame.

The whole point of inheriting from tk.Frame is to create a new class that behaves exactly like standard widgets. You can add it to other widgets with pack or place or grid, it has some standard options such as borderwidth and relief, and is entirely self-contained.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...