简体   繁体   English

如何在顶层使用父 class

[英]How to use parent class, in Toplevel

I defined a GeneralFrame class that inherits from tk.LabelFrame, which contains other widgets like labels and entries:我定义了一个继承自 tk.LabelFrame 的 GeneralFrame class,它包含其他小部件,如标签和条目:

class GeneralFrame(tk.LabelFrame):
    def __init__(self, master, eCount, lCount):
        super().__init__()

        self.grid(padx=5, pady=5)
        self.entry_widget(eCount)
        self.label_widget(lCount)
      

    def entry_widget(self, eCount):
        self.e = {}
        for i in range(0, eCount):
            self.e[i] = tk.Entry(self, width=6)
            self.e[i].grid(row=i, column=1, sticky='w')
            self.e[i].delete(0, tk.END)

    def label_widget(self, lCount):
        self.l = {}
        for i in range(0, lCount):
            self.l[i] = tk.Label(self)
            self.l[i].grid(row=i, column=0, sticky='w')


How can I use this class in a TopLevel window?如何在 TopLevel window 中使用此 class? I've tried like this but it places the frame_save in parent window not TopLevel:我试过这样,但它将 frame_save 放在父 window 而不是 TopLevel:

def openNewWindow():
    newWindow = Toplevel(window)
    newWindow.title('Saved Data')
    newWindow.geometry('200x200')

    frame_save = GeneralFrame(newWindow, eCount=5, lCount=5)
    frame_save.configure(text='Saved data',font=("Helvetica",14,"bold"))
    frame_save.grid(row=0, column=0)

    labels_text = ['label1','label2','label3','label4','label5']
    [frame_save.l[i].configure(text=labels_text[i]) for i in range(0,5)]

And general use in parent window:在父 window 中一般使用:

window = tk.Tk()
window.geometry("980x500")
window.resizable(1,1)
window.title('Calculator')

class GeneralFrame(tk.LabelFrame):
[code]

frame_1 = GeneralFrame(window, eCount=5, lCount=5)
frame_2 = GeneralFrame(window, eCount=5, lCount=5)

def Frame_1():
 [code]
def Frame_2():
 [code]

Frame_1()
Frame_2()
window.mainloop()

It works if I do this:如果我这样做,它会起作用:

class GeneralFrame(tk.LabelFrame):
    def __init__(self, master, eCount, lCount):
        #super().__init__()
        tk.LabelFrame.__init__(self,master)

You need to pass master when calling super().__init__ .调用super().__init__时需要传递master Otherwise, the actual frame has a default master, and the default master is the root window.否则,实际帧有一个默认主,默认主是根window。

super().__init__(master)

Also, I encourage you to not call self.grid .另外,我鼓励您不要调用self.grid The way tkinter widgets are designed, it's expected that the code that creates the widgets also calls pack , place , or grid on the widget. tkinter 小部件的设计方式,预计创建小部件的代码也会在小部件上调用packplacegrid Otherwise your class can only ever be used in a parent that uses grid .否则,您的 class 只能在使用grid的父级中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM