Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 40 ยท Layout Managers

Responsive Tkinter Layouts and Resizing

Make Tkinter windows resize gracefully: weights, minsize, PanedWindow splitters, reflowing card grids on Configure events, DPI scaling and layout debugging tips.

A window that looks fine at 400 by 300 pixels but breaks when maximized, or crops when someone uses a bigger font, is a common sign of a layout built without resizing in mind. This lesson pulls the layout tools together into a checklist, then adds the techniques that go beyond pack and grid: split panes, reflowing grids and DPI awareness.

The resize checklist

Work through these questions for every window.

  1. What should grow? Usually one main area (a text box, canvas, table). Everything else keeps its size.
  2. Does the parent give it room? With grid: a nonzero weight on its row and column. With pack: fill="both", expand=True.
  3. Does the widget use the room? With grid: sticky="nsew". With pack: fill.
  4. What is the smallest sensible window? Set root.minsize(w, h) so the layout never collapses to nothing.
  5. Do nested frames pass the weights down? A frame placed in a weighted cell also needs its own columnconfigure/rowconfigure for its children.

The last point trips people up: weights apply to one parent's direct children only.

Python
import tkinter as tk

root = tk.Tk()
root.geometry("520x360")
root.minsize(360, 240)

root.columnconfigure(0, weight=1)         # level 1: the root's only column grows
root.rowconfigure(1, weight=1)            # the middle row grows

tk.Label(root, text="Toolbar", bg="#dee2e6").grid(row=0, column=0, sticky="ew")

content = tk.Frame(root)
content.grid(row=1, column=0, sticky="nsew")
content.columnconfigure(0, weight=1)      # level 2: the frame's own children
content.rowconfigure(0, weight=1)
tk.Text(content).grid(row=0, column=0, sticky="nsew")   # now it really grows

tk.Label(root, text="Status", anchor="w", bd=1, relief="sunken").grid(row=2, column=0, sticky="ew")
root.mainloop()

If the text box refuses to grow, count the levels: every container between the window and the widget needs weights.

Resizing the layout's shape: min sizes and uniform columns

columnconfigure(col, minsize=120) stops a column collapsing; uniform="a" keeps equal columns; pad adds fixed room. Together with weights these cover most dashboards:

Python
for column in range(3):
    root.columnconfigure(column, weight=1, uniform="cards", minsize=140)

PanedWindow: user-resizable panes

A PanedWindow splits an area into panes separated by draggable sashes. Use it for editors with a file tree and for master/detail views.

Python
import tkinter as tk

root = tk.Tk()
panes = tk.PanedWindow(root, orient="horizontal", sashrelief="raised", sashwidth=6)
panes.pack(fill="both", expand=True)

left = tk.Listbox(panes)
for i in range(30):
    left.insert("end", f"File {i}")
right = tk.Text(panes)

panes.add(left, minsize=120, width=180)
panes.add(right, minsize=240, stretch="always")   # only this pane grows with the window
root.mainloop()

stretch can be "always", "never" or "first"/"last"/"middle". ttk.PanedWindow offers the same with weight instead; pane methods are add, forget, paneconfigure and sash_place.

Reflowing a grid of cards

Fixed columns waste space on wide windows and overflow on narrow ones. A reflow layout recalculates the number of columns from the window width, like CSS flexbox wrapping. In Tkinter you bind <Configure> (fires on any size change) and re-grid the cards.

The calculation is plain arithmetic, so test it here first:

Python Stand-in: columns for a given width

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.

Now the Tkinter code that uses it. The handler re-grids only when the column count changes, because re-gridding on every pixel of dragging would make resizing sluggish:

Python
import tkinter as tk

CARD_W, GAP = 160, 12

root = tk.Tk()
root.geometry("700x400")
area = tk.Frame(root)
area.pack(fill="both", expand=True, padx=GAP, pady=GAP)

cards = [tk.Label(area, text=f"Card {i}", bg="#a8dadc", width=18, height=4) for i in range(10)]
current = {"cols": 0}

def reflow(event):
    cols = max(1, min(6, (event.width + GAP) // (CARD_W + GAP)))
    if cols == current["cols"]:
        return
    current["cols"] = cols
    for index, card in enumerate(cards):
        row, column = divmod(index, cols)
        card.grid(row=row, column=column, padx=GAP // 2, pady=GAP // 2, sticky="nsew")
    for column in range(6):
        area.columnconfigure(column, weight=1 if column < cols else 0)

area.bind("<Configure>", reflow)
root.mainloop()

Two useful details. First, event.width is the width of the widget that fired the event; bind on the container, not the window, or you will get events from every child as well. Second, the weights of columns that are no longer used are reset to 0, otherwise they keep claiming space.

Responding to the window size

<Configure> is also how you switch between layouts at a breakpoint, such as a side-by-side view on wide windows and a stacked view on narrow ones:

Python
def on_resize(event):
    if event.widget is not root:
        return
    wide = event.width >= 640
    if wide != state["wide"]:
        state["wide"] = wide
        relayout(wide)

Check event.widget because the root's <Configure> binding also receives events from its descendants (a binding on the toplevel applies to all widgets inside it via the toplevel's bindtag).

The breakpoint rule itself, with a small hysteresis so a window hovering near the limit does not flip back and forth, is easy to model:

Python Stand-in: breakpoints with hysteresis

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.

Scaling for DPI and font sizes

Pixel-based sizes shrink on high-DPI displays. Two habits help:

  • Size by characters and fonts (width=20 in a Label or Entry) where possible, because these scale with the font. Use pixel sizes mostly for images.
  • Scale Tk itself. root.tk.call("tk", "scaling", 1.5) changes the points-to-pixels ratio. On Windows you can also declare DPI awareness before creating the window:
Python
import sys
if sys.platform == "win32":
    from ctypes import windll
    windll.shcore.SetProcessDpiAwareness(1)    # crisp text on high-DPI screens
root = tk.Tk()

For layouts that must follow a font change, ttk widgets and padding in font units behave better than hard-coded pixels.

Debugging layouts

  • Give frames temporary colors (bg="red") to see their real extent.
  • Print winfo_children() and sizes after update_idletasks().
  • grid_bbox() returns the pixel boxes of grid cells; grid_size() the row and column count.
  • pack_propagate(False) / grid_propagate(False) are the switches to try when a frame "refuses" to take its width or height. Remember they are usually the cause of a frame being too small, not too big.
  • Remove expand/weight one at a time. An unexpected stretch is nearly always a leftover weight on some ancestor.

The next chapter turns from where widgets go to what happens when the user acts on them: events and bindings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A Text inside a Frame inside the root does not grow, even though the root's column has weight=1 and the Text has sticky='nsew'. What is missing?

    Weights apply to a parent's direct children only. Each container level between the window and the widget needs them.
  2. 2. Why bind <Configure> on the container instead of the root when reflowing cards?

    A Configure binding on the toplevel also receives events from child widgets. Binding on the container gives its own width.
  3. 3. What is hysteresis in a breakpoint?

    Switching at slightly different widths in each direction prevents rapid back-and-forth switching.
  4. 4. Which widget lets users drag a divider to resize two areas?

    PanedWindow (and ttk.PanedWindow) provides draggable sashes between panes.

Summary

  • Decide what grows, give it weights/expand, make it fill, and set a minsize; repeat at every container level.
  • PanedWindow gives users draggable splits; set which pane stretches.
  • Reflow layouts by binding <Configure> on a container and re-gridding only when the column count changes.
  • Use breakpoints (with hysteresis) to switch layout styles; size by characters and handle DPI awareness.
  • Debug with colored frames, grid_bbox(), update_idletasks() and the propagate switches.

Next: Bind and Events