Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 40 ยท Styling with ttk

Notebook, PanedWindow, LabelFrame and Scrollable Frames

Organize a Tkinter window with ttk.Notebook tabs, resizable PanedWindow panes, LabelFrame groups, separators and a scrollable frame built from a Canvas.

Small programs fit on one screen. Real applications have settings, long forms and several views, and they need structure: tabs, groups with titles, resizable side panels and areas that scroll. Tkinter's container widgets provide that structure. This lesson covers ttk.Notebook (tabs), ttk.PanedWindow (draggable splitters), ttk.LabelFrame (titled groups), ttk.Separator, and the standard recipe for a scrollable frame.

The window code is read-only. The runnable blocks model the state logic of tabs and splitters, which is where mistakes tend to occur. Layout managers (pack, grid, place) are used throughout and are covered in their own chapter.

Notebook: tabs

Python
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("420x280")

notebook = ttk.Notebook(root)
notebook.pack(fill="both", expand=True, padx=8, pady=8)

general = ttk.Frame(notebook, padding=12)
advanced = ttk.Frame(notebook, padding=12)
about = ttk.Frame(notebook, padding=12)

notebook.add(general, text="General")
notebook.add(advanced, text="Advanced")
notebook.add(about, text="About")

ttk.Label(general, text="Username").grid(row=0, column=0, sticky="w")
ttk.Entry(general).grid(row=0, column=1)
ttk.Checkbutton(advanced, text="Enable logging").pack(anchor="w")
ttk.Label(about, text="Settings 1.0").pack()

root.mainloop()

A window with three tabs appears: "General" (a labeled entry), "Advanced" (a check box) and "About" (a version label). Each tab's content is an ordinary Frame, which is a child of the notebook and is added to it with add(). The pages are children of the notebook, not of the root; creating a page with root as its master is a classic error that shows the content outside the tabs.

Useful methods:

Method Effect
add(frame, text=, image=, compound=, state=, sticky=, padding=) append a tab
insert(position, frame, ...) add a tab at a position
forget(tab) remove a tab (the frame survives)
hide(tab) / add(tab) again hide and re-show a tab
select() current tab's widget path
select(tab) switch to a tab
index("current") position of the current tab
tab(tab, option) / tab(tab, text="New") read or change tab options
tabs() all tab widget paths
enable_traversal() Ctrl+Tab and Alt+underline switching

Reacting to a tab change uses a virtual event:

Python
def on_tab_changed(event):
    index = notebook.index("current")
    title = notebook.tab(index, "text")
    status.set(f"Showing: {title}")
    if title == "Advanced":
        load_advanced_settings()

notebook.bind("<<NotebookTabChanged>>", on_tab_changed)

This fires on every switch, including the first tab being shown at start-up. Use it to load expensive tab content lazily: a tab that fetches data from a database should do so when first selected, not when the window opens.

Which container?

Notebook Switch between pages
PanedWindow User resizes panels
LabelFrame Group with a title
Separator A thin dividing line

Frames are the building blocks of all four.

1 / 2

Modeling tab state

This stand-in is not Tkinter. It models a notebook's selection and hidden-tab rules, and the lazy loading pattern for the tab-changed event.

Python Stand-in: notebook selection and lazy loading

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.

PanedWindow: resizable panes

A PanedWindow places widgets side by side (or stacked) with draggable dividers called sashes. Editors and file managers use it for the sidebar.

Python
paned = ttk.PanedWindow(root, orient="horizontal")
paned.pack(fill="both", expand=True)

sidebar = ttk.Frame(paned, width=160)
content = ttk.Frame(paned)
paned.add(sidebar, weight=1)
paned.add(content, weight=3)

ttk.Label(sidebar, text="Files").pack(padx=8, pady=8)
text = tk.Text(content)
text.pack(fill="both", expand=True)

Two panes appear: a narrow sidebar on the left and a wide text area. Dragging the divider changes their widths. weight decides how extra space is shared when the window resizes (here 1 to 3). Nest paned windows to create a layout such as sidebar + (editor over console). Read or set a sash position with paned.sashpos(0) and paned.sashpos(0, 220). Do it after the window is drawn (for example root.after(100, ...)), because positions are only meaningful once sizes are known.

The classic tk.PanedWindow offers more options (sashwidth, sashrelief, opaqueresize) and supports minsize for each pane via add(child, minsize=100). Use it when you need a minimum size; use ttk.PanedWindow otherwise.

Python Stand-in: sharing space by weight and respecting minimum sizes

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.

At width 300 the sizes violate the total (the minimums win), which is what the real widget does when a window is made too small: the layout is clipped rather than shrunk below the minimum.

LabelFrame and Separator

A LabelFrame is a frame with a border and a title; it groups related controls:

Python
box = ttk.LabelFrame(root, text="Connection", padding=10)
box.pack(fill="x", padx=10, pady=6)
ttk.Label(box, text="Host").grid(row=0, column=0, sticky="w")
ttk.Entry(box).grid(row=0, column=1, sticky="ew")
box.columnconfigure(1, weight=1)

A titled box labeled "Connection" surrounds the host field. labelanchor="n" (or "nw", "sw"...) moves the title. A ttk.Separator(root, orient="horizontal") draws a plain line; with pack(fill="x", pady=8) it separates sections. For vertical separators use orient="vertical" and fill="y".

ttk.Sizegrip(root) adds the small resize handle at a window's bottom-right corner, and ttk.Frame with relief="groove" and borderwidth=2 makes a simple bordered box.

The scrollable frame recipe

A Frame cannot scroll. To scroll many widgets, put the frame inside a Canvas through create_window, then scroll the canvas:

Python
class ScrollableFrame(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.canvas = tk.Canvas(self, highlightthickness=0)
        self.vbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.inner = ttk.Frame(self.canvas)

        self.window = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")
        self.canvas.configure(yscrollcommand=self.vbar.set)

        self.inner.bind("<Configure>", lambda e: self.canvas.configure(
            scrollregion=self.canvas.bbox("all")))
        self.canvas.bind("<Configure>", lambda e: self.canvas.itemconfigure(
            self.window, width=e.width))                       # match the canvas width
        self.canvas.bind("<Enter>", lambda e: self.canvas.bind_all("<MouseWheel>", self._wheel))
        self.canvas.bind("<Leave>", lambda e: self.canvas.unbind_all("<MouseWheel>"))

        self.canvas.pack(side="left", fill="both", expand=True)
        self.vbar.pack(side="right", fill="y")

    def _wheel(self, event):
        self.canvas.yview_scroll(int(-event.delta / 120), "units")

# usage: add widgets to sf.inner, never to sf itself
sf = ScrollableFrame(root)
sf.pack(fill="both", expand=True)
for i in range(40):
    ttk.Label(sf.inner, text=f"Row {i + 1}").pack(anchor="w", padx=8, pady=2)

You get a window of 40 rows with a scrollbar, and the mouse wheel scrolls while the pointer is over it. There are three details worth knowing. The <Configure> binding on inner updates scrollregion whenever the content grows. The second <Configure> stretches the inner frame to the canvas width. And the wheel binding is attached only while the mouse is over the widget, so other scrollable areas do not fight for it. On Linux the wheel events are <Button-4> and <Button-5>; on macOS the delta is not a multiple of 120, so use -event.delta directly.

Children must be added to sf.inner. Adding them to sf places them beside the canvas instead and nothing scrolls.

Common mistakes

  • Making notebook pages children of the root rather than of the notebook.
  • Adding a page to two notebooks or calling add twice for the same frame without forget.
  • Reading sashpos before the window is mapped, which returns 0.
  • Forgetting to set scrollregion, so the scrollbar does nothing.
  • Packing widgets into a scrollable frame wrapper rather than into its inner frame.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event tells you the user switched notebook tabs?

    ttk.Notebook generates the virtual event <<NotebookTabChanged>>.
  2. 2. What does weight control in PanedWindow.add(child, weight=3)?

    Panes with higher weights receive proportionally more extra space.
  3. 3. Why does a scrollable frame use a Canvas?

    The inner frame is embedded with create_window, and the canvas provides the scroll views.
  4. 4. Where must widgets for a ScrollableFrame be created?

    Only widgets inside the embedded inner frame move with the canvas.

Summary

  • ttk.Notebook shows pages as tabs; pages are children of the notebook; react with <<NotebookTabChanged>>.
  • PanedWindow gives the user draggable sashes; weight shares extra space.
  • LabelFrame groups controls with a title; Separator draws a line.
  • A scrollable frame is a Canvas containing an inner Frame, with scrollregion kept up to date.
  • Load heavy tab content lazily.

Next: Structuring Tkinter Apps with Classes