[Python] Tkinter - resize parent after grid_remove()

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Either I did misread some of the documentation or I still do not quite understand some concepts of Tkinter.

    If I add widgets (e.g. Labels) to a frame using grid() the frame gets resized to fit them. (so far as expected)

    If I call grid_remove on all the children (using frame.winfo_children() to adress all of them) the frame does not get resized again (what I would like to have).

    Is there any specific reason why after these actions

    1. add 20 elements
    2. grid_remove() all of them
    3. add 10 again

    these results occur?

    1. The frame resizes to fit 20.
    2. Does not resize on removal.
    3. Shrinks after adding 10 to only fit them?

    Replication Code:


    import tkinter as tk
    from tkinter import ttk

    root = tk.Tk()
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)

    app = ttk.Frame(root)
    app.grid(row=0, column=0, columnspan=2, sticky=tk.NW+tk.SE)

    def add(start=None):
    start = start or len(app.winfo_children())
    for i in range(start,start+10):
    ttk.Label(app, text=f"{i}").grid(row=i, column=0, sticky=tk.NW+tk.SE)

    def rem():
    for _f in app.grid_slaves():
    _f.grid_remove()

    ttk.Button(root, text='+', command=add).grid(row=1, column=0)
    ttk.Button(root, text='-', command=rem).grid(row=1, column=1)

    root.mainloop()

    Continue reading...

Compartilhe esta Página