[Python] tkinter - Class based approach. Cannot superimpose label on frame

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I am learning class-based tkinter. I need help with tkinter class-based approach.

    I have created a window, and added a frame in it. The frame is a child of the window. I now have to add a label to the frame. Label is hence child of the frame.

    When I run the code, the label text does not show up on the frame. Instead a gray small window shows up. See picture -

    [​IMG]

    What am I doing wrong?

    import tkinter as tk
    from tkinter import ttk

    class App(tk.Tk):
    def __init__(self, title, size):
    super().__init__()
    self.title(title)
    self.geometry(f'{size[0]}x{size[1]}')
    self.minsize(size[0],size[1])
    # 9 arguments below:
    # frame color, x start, y start, rel width, rel height
    # label text, text x position, text y position, label background color
    self.menu1 = Menu(self,'red',0,0,0.5,0.5,'ABC',50,50,'yellow')

    self.mainloop()

    class Menu(ttk.Frame):
    def __init__(self,parent,bg_col,x,y,relx,rely,text1,x1,y1,bg):
    super().__init__(parent)
    ttk.Label(self,background=bg_col).pack(expand=True, fill='both')
    self.place(x=x,y=y,relwidth=relx,relheight=rely)
    self.label = Labeling(self,text1,x1,y1,bg)


    class Labeling(ttk.Label):
    def __init__(self,parent,text1,x1,y1,bg):
    super().__init__(parent)
    ttk.Label(self,text=text1,background=bg)
    self.place(x=x1,y=y1)

    App('Class based App',[400,400])


    Also, is this approach correct? I am planning to create more frames in the rest of the window. These frames will have their own widgets.

    Thank you

    Continue reading...

Compartilhe esta Página