为什么 super() 会使我的 tkinter 小部件加倍?

Why does super() doubles my tkinter widgets?

我目前正在编写一个应用程序并为它创建了三个 classes。 第一个 class 包含所有函数。第二个 class 包含 'window' 小部件,第三个 class 包含导航栏。

当我从第二个 class 继承第一个 class 时,按钮工作并执行功能。我从导航 class 继承 window class 的那一刻,通过它我还继承了功能 class,突然间我的小部件加倍了。 按钮有效(两个按钮都有效)但显然我不希望它加倍。

谁能给我解释一下?

This is the output with inheritance from Start to FunctionClass

This is the output when TopMenu inherits from Start and Start from FunctionClass

我的代码是:

from tkinter import *

class FunctionClass:

    def print_text(self):
        print("This is an example!")


class Start(FunctionClass):

    def __init__(self, master):
        super().__init__()
        frame = Frame(master)
        frame.pack()

        self.label = Label(frame,text="This is just a label.").pack()
        self.label2 = Label(frame, text="This is second label.").pack()
        self.button = Button(frame, text="Magic Button", command=self.print_text).pack()


class TopMenu(Start):

    def __init__(self, master):
        super().__init__(master)
    # *******Top-Navigation Bar**********
        tnb = Menu(master)
        root.config(menu=tnb)

    # *******tnb_file*******

        tnb_file = Menu(tnb, tearoff=0)
        tnb.add_cascade(label="File", menu=tnb_file)
        tnb_file.add_command(label="Button", command=self.print_text)
        tnb_file.add_separator()
        tnb_file.add_command(label="Exit", command=root.destroy)





root = Tk()
g = Start(root)
d = TopMenu(root)

root.mainloop()

继承意味着是一个。如果 "Dog" 继承自 "Animal","Dog" 是一个 "Animal".

TopMenu继承自Start时,TopMenuStartStart 所做或可以做的任何事情都已完成或可以用 TopMenu 完成。因此,因为 Start 创建了一些小部件,所以从 Start 继承的任何东西也将创建小部件。

当你这样做时:

g = Start(root)
d = TopMenu(root)

...您首先使用 g = Start(root) 创建小部件,然后在使用 d = TopMenu 时再次创建小部件。同样,这是因为 TopMenu _是 Start.