Tkinter has three main geometry managers: pack()
, grid()
, and place()
. The simplest of these is pack()
, which automatically places widgets in blocks, one after another, either vertically or horizontally.
Step 1: Basic Tkinter Window Setup
import tkinter as tk
root = tk.Tk()
root.title("Pack Example")
root.geometry("300x200")
Step 2: Add Widgets with pack()
label1 = tk.Label(root, text="Top Label", bg="lightblue")
label1.pack()
label2 = tk.Label(root, text="Middle Label", bg="lightgreen")
label2.pack()
label3 = tk.Label(root, text="Bottom Label", bg="lightcoral")
label3.pack()
What happens?
- Each widget is packed from top to bottom by default.
- They take up only as much space as they need.
Step 3: Control Widget Position with side
Use side
to change the packing direction:
label1.pack(side="top") # Default
label2.pack(side="left") # Left to right
label3.pack(side="right") # Right to left
Step 4: Add Padding with padx
and pady
Padding adds space around the widget:
tk.Button(root, text="Click Me").pack(padx=20, pady=10)
Step 5: Expand and Fill Available Space
Use fill
and expand
to make widgets grow:
tk.Label(root, text="Fills Horizontally", bg="skyblue").pack(fill="x")
tk.Label(root, text="Fills Vertically", bg="orange").pack(fill="y", side="left")
tk.Label(root, text="Fills Both", bg="lightgray").pack(fill="both", expand=True)
fill
: Accepts "x"
, "y"
, or "both"
expand=True
: Tells it to take up unused space in the window
Step 6: Group Widgets with Frame
and Pack Inside
top_frame = tk.Frame(root, bg="white")
top_frame.pack(fill="x")
tk.Button(top_frame, text="Button 1").pack(side="left", padx=5)
tk.Button(top_frame, text="Button 2").pack(side="left", padx=5)
Full Example: Simple Layout with pack()
import tkinter as tk
root = tk.Tk()
root.title("Pack Layout Demo")
root.geometry("300x250")
# Labels
tk.Label(root, text="Header", bg="#4CAF50", fg="white").pack(fill="x", pady=5)
# Content Frame
content = tk.Frame(root)
content.pack(fill="both", expand=True)
tk.Label(content, text="Left", bg="lightblue").pack(side="left", fill="both", expand=True)
tk.Label(content, text="Right", bg="lightgreen").pack(side="right", fill="both", expand=True)
# Footer
tk.Button(root, text="Submit").pack(pady=10)
root.mainloop()
Summary of pack()
Options
Option | Description |
---|---|
side | "top" (default), "bottom" , "left" , "right" |
fill | "x" , "y" , or "both" |
expand | True or False |
padx/pady | Add padding outside widget |
ipadx/ipady | Add internal padding (inside widget size) |