pythonuser-interfacetkintergrid-layouttkinter-layout

Error when trying to position two TFrames on the Tkinter grid


When trying to position 2 TFrames on the main TFrame grid, it ends up with a gap between the two that shouldn't exist

Here is the code:

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])

        s = ttk.Style()
        s.configure("Header.TLabel", font=("Arial", 18, "bold"))

        self.main = Main(self)
        self.main.grid(row=0, column=0, sticky="nsew")

        self.columnconfigure((0), weight=1)
        self.rowconfigure((0), weight=1)


class Header(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent, padding="10 50 10 50")
        self.create_widgets()

    def create_widgets(self):
        button = ttk.Button(self, text="Voltar")
        button.grid(row=0, column=0, sticky="ew")

        label = ttk.Label(
            self, text="Cadastro de Pessoa", anchor="center", style="Header.TLabel"
        )
        label.grid(row=0, column=1, sticky="ew")

        button = ttk.Button(self, text="Salvar")
        button.grid(row=0, column=2, sticky="ew")

        self.columnconfigure((0, 1, 2), weight=1)
        self.rowconfigure((0), weight=1)


class Body(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent, padding="10 5 10 5")
        
        self.create_widgets()

    def create_widgets(self):
        nome = ttk.Label(self, text="Nome: ", background="red")
        nome.grid(row=0, column=0, sticky="nsew")

        self.columnconfigure((0), weight=1)
        self.rowconfigure((0), weight=1)


class Main(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        
        self.create_widgets()

    def create_widgets(self):
        self.header = Header(self)
        self.header.grid(row=0, column=0, sticky="new")

        self.body = Body(self)
        self.body.grid(row=1, column=0, sticky="nsew")

        self.columnconfigure((0), weight=1)
        self.rowconfigure((0,1), weight=1)


app = App("Cadastro de Pessoa", (600, 600))
app.mainloop()

Here is the result obtained with the code: https://i.sstatic.net/ZFTdV.png

I expected this: https://i.sstatic.net/oBeh4.png

I've already tried changing the rowconfigure by putting only 0, or just 1.

I've already tried changing the row numbering of the TFrames, but it didn't help.

I've already tried changing the rowconfigure but it didn't work, if anyone can help I'd be grateful.


Solution

  • It is because you have set weight=1 for both rows 0 and 1 inside Main frame. You just need to set it for row 1 only for your required result:

    class Main(ttk.Frame):
        ...
    
        def create_widgets(self):
            ...
            self.rowconfigure(1, weight=1)