Adrian
Adrian

Reputation: 317

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:

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? I've tried like this but it places the frame_save in parent window not 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 = 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()

Upvotes: 0

Views: 417

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386020

You need to pass master when calling super().__init__. Otherwise, the actual frame has a default master, and the default master is the root window.

super().__init__(master)

Also, I encourage you to not call self.grid inside the __init__. 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. Otherwise your class can only ever be used in a parent that uses grid.

Upvotes: 1

Adrian
Adrian

Reputation: 317

It works if I do this:

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

Upvotes: 0

Related Questions