Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 40 ยท Widgets Basics

Tkinter Frame, LabelFrame and Toplevel

Group widgets with Tkinter Frame and LabelFrame, nest containers, scroll big forms with a Canvas, and open extra windows with Toplevel. Includes widget tree tools.

A Frame is an invisible rectangle whose only job is to hold other widgets. That sounds modest, but frames are the most important layout tool in Tkinter: they let you group related controls, use a different geometry manager in each group, and move or hide a whole section with a single call. This lesson covers Frame, LabelFrame, scrollable areas and Toplevel windows, and finishes with the tools for inspecting the widget tree.

Frame

Python
import tkinter as tk

root = tk.Tk()

header = tk.Frame(root, bg="#264653", height=50)
header.pack(fill="x")
tk.Label(header, text="My App", fg="white", bg="#264653",
         font=("Segoe UI", 14, "bold")).pack(side="left", padx=12, pady=10)

body = tk.Frame(root, padx=16, pady=16)
body.pack(fill="both", expand=True)
tk.Label(body, text="Content goes here").pack()

root.mainloop()

Children are created with the frame as their parent (tk.Label(header, ...)), so their coordinates are relative to the frame. Frame options: bg, width/height (ignored if the frame holds widgets managed by pack or grid, because it shrinks to fit), relief, bd (border), padx/pady, highlightthickness.

Two idioms you will use all the time:

  • pack_propagate(False) or grid_propagate(False) stops a frame from shrinking to its content, so width and height are honoured, for example for a fixed-width sidebar.
  • Different managers in different frames. Never mix pack and grid in the same parent, but a parent using pack may contain a child frame that uses grid for its own children. Frames are what make this possible.
Python
sidebar = tk.Frame(root, width=180, bg="#e9ecef")
sidebar.pack(side="left", fill="y")
sidebar.pack_propagate(False)           # keep 180 px wide even when empty

LabelFrame

LabelFrame (and ttk.LabelFrame) is a frame with a border and a caption. It is the natural container for a titled group of options.

Python
group = tk.LabelFrame(root, text="Shipping", padx=12, pady=8)
group.pack(fill="x", padx=12, pady=8)

method = tk.StringVar(value="standard")
for label, value in [("Standard", "standard"), ("Express", "express")]:
    tk.Radiobutton(group, text=label, variable=method, value=value).pack(anchor="w")

labelanchor moves the caption ("nw" default, "n", "ne", "sw"...). You can even use a widget as the label with labelwidget=, for example a Checkbutton that enables the whole group.

Nesting: a settings screen

Real windows are trees of frames. The stand-in builds a tree for a settings form and prints it with indentation, which is exactly what you would see with the debugging functions shown further down. It uses the same ideas as the earlier widget tree stand-in, and adds a count of how many widgets sit under each container.

Python Stand-in: nested containers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each small frame (the label-and-entry "row") can use pack(side="left") internally while the parent stacks rows with pack or grid. Grouping rows like this is easier to read than one giant grid of every widget.

Hiding and showing a section

Because a frame is one object, hiding it hides everything inside:

Python
details = tk.Frame(root)
visible = tk.BooleanVar()

def toggle():
    if visible.get():
        details.pack(fill="x")
    else:
        details.pack_forget()

tk.Checkbutton(root, text="Show advanced options", variable=visible, command=toggle).pack()

Use pack_forget(), grid_remove() (remembers grid options) or place_forget() depending on the manager. To remove a frame for good, call destroy(). A neat "wizard" screen keeps several frames in the same grid cell and calls tkraise() on the one to show:

Python
pages = {}
for name in ("Welcome", "Details", "Finish"):
    page = tk.Frame(container)
    page.grid(row=0, column=0, sticky="nsew")
    tk.Label(page, text=name, font=("Segoe UI", 20)).pack(pady=40)
    pages[name] = page

pages["Welcome"].tkraise()           # show a page

Scrollable frames

A Frame cannot scroll itself. The standard trick is to put the content frame inside a Canvas, which can scroll, and tell the canvas the size of the frame:

Python
import tkinter as tk

root = tk.Tk()
outer = tk.Frame(root)
outer.pack(fill="both", expand=True)

canvas = tk.Canvas(outer, highlightthickness=0)
scrollbar = tk.Scrollbar(outer, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)

inner = tk.Frame(canvas)
window_id = canvas.create_window((0, 0), window=inner, anchor="nw")

inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<Configure>", lambda e: canvas.itemconfigure(window_id, width=e.width))

for i in range(40):
    tk.Label(inner, text=f"Row {i}").pack(anchor="w", padx=10)

root.mainloop()

The first binding keeps scrollregion equal to the content's bounding box; the second stretches the inner frame to the canvas width. Mouse-wheel support is added in Keyboard and Mouse Events. Chapter 6 explains canvases in depth.

Toplevel: more windows

tk.Toplevel(root) opens another window, owned by the same program. It is a container just like Frame, with window methods (title, geometry, resizable, protocol).

Python
def open_about():
    win = tk.Toplevel(root)
    win.title("About")
    win.geometry("300x160")
    win.transient(root)          # stays above the parent, no extra taskbar entry
    win.grab_set()               # modal: input goes only to this window
    tk.Label(win, text="Tkinter demo\nversion 1.0").pack(pady=20)
    tk.Button(win, text="Close", command=win.destroy).pack()

tk.Button(root, text="About", command=open_about).pack()

transient() ties the window to its parent and grab_set() makes it modal; wait_window(win) pauses the caller until it closes. Dialog windows and the built-in dialogs are the subject of chapter 5.

Inspecting the tree

Every widget knows its place, which helps with debugging:

Python
widget.winfo_children()      # direct children
widget.winfo_parent()        # parent path name as a string
widget.master                # parent widget object
str(widget)                  # path name such as ".!frame.!button"
widget.winfo_class()         # "Button"
widget.winfo_x(), widget.winfo_y(), widget.winfo_width(), widget.winfo_height()

A recursive print of winfo_children() gives you the same output as the stand-in above and is often the quickest way to find out why a widget is not where you expect. Remember update_idletasks() before asking for sizes (Your First Window).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do frames make it possible to use pack and grid in the same window?

    Mixing pack and grid inside the same parent causes errors or endless layout loops, but different frames are different parents.
  2. 2. What does frame.pack_propagate(False) do?

    By default a frame sizes itself to its contents. Turning propagation off keeps the requested size.
  3. 3. How do you make a frame scroll?

    Only some widgets scroll. The Canvas-plus-window technique makes a scrollable container for any content.
  4. 4. What does win.grab_set() do for a Toplevel dialog?

    grab_set directs all events to the window, which is how modal dialogs work.

Summary

  • Frame groups widgets; LabelFrame adds a border and caption; both are parents with their own layout.
  • Use one geometry manager per parent, and separate frames when you need to combine styles.
  • pack_propagate(False) and grid_propagate(False) keep a requested size.
  • Hide with pack_forget()/grid_remove(), stack pages with tkraise(), scroll with Canvas plus Scrollbar.
  • Toplevel opens extra windows; winfo_children() and path names help inspect the tree.

Next: The pack Layout Manager