Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Nested Frame using Classes

I am trying to build a GUI with the main Frame having nested frame containing header label (created with different class).

In below snippet, I am expecting frame created by FrameHeader class to be inside MainWindow.container Frame (while initialization of MainWindow.container attribute, container attribute is passed as parent).

Still, when the below code is run, FrameHeader frame is at the bottom after container frame, instead of being inside the container frame.

I am new to tkinter, can someone help me out here, what am I missing while going between different classes?

from tkinter import *

class FrameHeader(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, bg='red',relief=RAISED, borderwidth=2)
        self.pack(fill=BOTH, side=TOP)
        lblTitle = Label(self, text='Welcome to the Program!')
        lblTitle.pack(fill=BOTH)

class MainWindow(Tk):
    def __init__(self,*args):
        Tk.__init__(self,*args)
        self.geometry('400x300')

        # Main Container
        container=Frame(self, bg='black')
        container.pack(side=TOP, expand=TRUE, fill=BOTH)

        frameHeader=FrameHeader(container, self)

if __name__=='__main__':
    mainWindow=MainWindow()
    mainWindow.mainloop()
like image 257
Kunjan Vaghela Avatar asked Jul 04 '26 09:07

Kunjan Vaghela


1 Answers

You are neglecting to pass parent to Frame.__init, so the parent of FrameHeader defaults to the root window rather than the container.

The code needs to be this:

Frame.__init__(self, parent, bg='red',relief=RAISED, borderwidth=2)
like image 158
Bryan Oakley Avatar answered Jul 07 '26 08:07

Bryan Oakley