In Tkinter, the fill
option is commonly used with the pack()
geometry manager. It controls how a widget expands to fill the space allocated to it. This helps you build responsive and adaptive layouts by controlling expansion in horizontal, vertical, or both directions.
Using fill with pack()
The fill
parameter can take the following values:
NONE
: (default) The widget retains its natural size.X
: The widget fills horizontally.Y
: The widget fills vertically.BOTH
: The widget fills both horizontally and vertically.
Example: fill in X direction
import tkinter as tk
root = tk.Tk()
root.geometry("300x150")
label = tk.Label(root, text="Fills in X", bg="lightblue")
label.pack(fill=tk.X, padx=10, pady=10)
root.mainloop()
In this example, the label stretches horizontally but keeps its default vertical size.
Example: fill in both directions
import tkinter as tk
root = tk.Tk()
root.geometry("300x150")
label = tk.Label(root, text="Fills in both directions", bg="lightgreen")
label.pack(fill=tk.BOTH, expand=True)
root.mainloop()
Here, the label expands to fill both the width and height of the parent window, adjusting dynamically as the window is resized.
fill vs. expand
The fill
option tells the widget how to expand within the space allocated, while expand=True
tells the geometry manager to allocate extra space to the widget. You often use both together for best results.
fill with grid()
The grid()
manager does not have a fill
option directly, but you can mimic fill behavior by using the sticky
option:
import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
frame.grid(row=0, column=0, sticky="nsew")
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
label = tk.Label(frame, text="Sticky Fill", bg="orange")
label.grid(sticky="nsew")
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
root.mainloop()
In this example, sticky="nsew"
causes the label to expand in all directions within its cell, achieving a “fill” effect.
The fill
option in Tkinter gives you control over how widgets adjust to available space. When used with pack()
and expand
, it enables dynamic, flexible layout design. For grid()
, use sticky
and weight configuration to mimic fill behavior.