🐍 Python UI Programming Series — Part 2: Layouts and Frames in Tkinter
📘 Overview
In Part 1, you created a basic UI with a window, labels, buttons, and input fields. Now, it's time to learn how to organize your layout so your app doesn't look messy or hard to use.
In this article, we’ll cover:
-
Layout managers in Tkinter:
pack()
,grid()
,place()
-
Using Frames to group widgets
-
Building a cleaner and more responsive layout
🧩 Layout Managers in Tkinter
Tkinter provides 3 layout managers to place widgets:
1. pack()
– Stack widgets vertically or horizontally
2. grid()
– Place widgets in a table (rows and columns)
3. place()
– Use absolute positioning (less recommended)
Let’s explore each one.
✅ pack()
– Basic Stacking
import tkinter as tk
root = tk.Tk()
root.title("Pack Layout")
tk.Label(root, text="Top").pack()
tk.Label(root, text="Middle").pack()
tk.Label(root, text="Bottom").pack()
root.mainloop()
📦 Widgets stack from top to bottom by default.
✅ grid()
– For Tables and Alignment
import tkinter as tk
root = tk.Tk()
root.title("Grid Layout")
tk.Label(root, text="Username:").grid(row=0, column=0)
tk.Entry(root).grid(row=0, column=1)
tk.Label(root, text="Password:").grid(row=1, column=0)
tk.Entry(root, show="*").grid(row=1, column=1)
tk.Button(root, text="Login").grid(row=2, column=1)
root.mainloop()
🧮 Great for forms, settings panels, and structured UIs.
✅ place()
– Manual Coordinates (Not Recommended for Dynamic Layouts)
tk.Label(root, text="Fixed Position").place(x=50, y=100)
Best used sparingly for custom placement.
🧱 Organizing with Frames
A Frame
is like a container or group box. You can nest widgets inside it.
import tkinter as tk
root = tk.Tk()
root.title("Frames Example")
frame_top = tk.Frame(root, bg="lightblue")
frame_top.pack(fill="x")
frame_bottom = tk.Frame(root, bg="lightgreen")
frame_bottom.pack(fill="both", expand=True)
tk.Label(frame_top, text="Top Area").pack()
tk.Label(frame_bottom, text="Bottom Area").pack()
root.mainloop()
🧰 Useful for breaking UIs into logical sections.
🧠 Tip: Don’t Mix Layout Managers in the Same Container!
For example, don’t use pack()
and grid()
in the same frame — it will raise an error.
💡 Recap
In this part, you’ve learned:
-
How to use layout managers to structure your GUI
-
The difference between
pack()
,grid()
, andplace()
-
How to use Frames to group and organize widgets
🚀 Coming Up in Part 3:
“Styling Your UI: Fonts, Colors, and Themes in Tkinter”
-
Learn how to customize widget appearance and build modern-looking UIs.
No comments:
Post a Comment