Python GUI Development with Tkinter
Create desktop apps with windows, widgets, and interactive elements!
1. Setting Up a Basic Window
Tkinter is Python’s built-in GUI toolkit. Start by creating a window:
import tkinter as tk
# Create the main window
window = tk.Tk()
window.title("My App")
window.geometry("400x300") # Width x Height
# Start the event loop
window.mainloop()
2. Essential Widgets
Widgets are UI elements like buttons, labels, and input fields.
Common Widgets
Widget | Description | Example Code |
---|---|---|
Label | Display text/images | tk.Label(window, text="Hello!") |
Button | Clickable button | tk.Button(window, text="Click Me") |
Entry | Single-line text input | tk.Entry(window) |
Text | Multi-line text input | tk.Text(window, height=5) |
Checkbutton | Toggle checkbox | tk.Checkbutton(window, text="Agree") |
Listbox | List of selectable items | tk.Listbox(window) |
Example: Login Form
window = tk.Tk()
window.title("Login")
# Username
tk.Label(window, text="Username:").grid(row=0, column=0)
username_entry = tk.Entry(window)
username_entry.grid(row=0, column=1)
# Password
tk.Label(window, text="Password:").grid(row=1, column=0)
password_entry = tk.Entry(window, show="*")
password_entry.grid(row=1, column=1)
# Login Button
def login():
username = username_entry.get()
password = password_entry.get()
print(f"Username: {username}, Password: {password}")
tk.Button(window, text="Login", command=login).grid(row=2, column=1)
window.mainloop()
3. Event Handling
Bind actions to user interactions like clicks or key presses.
Button Click Event
def say_hello():
label.config(text="Hello, Tkinter! 👋")
label = tk.Label(window, text="Click the button!")
label.pack()
button = tk.Button(window, text="Greet", command=say_hello)
button.pack()
Keyboard Event
def on_key_press(event):
print(f"You pressed: {event.char}")
window.bind("", on_key_press)
4. Layout Management
Arrange widgets using geometry managers:
1. pack()
Simplest layout (stacks widgets vertically/horizontally):
tk.Label(window, text="Top").pack()
tk.Label(window, text="Bottom").pack()
2. grid()
Organize widgets in rows and columns (most flexible):
tk.Label(window, text="Row 0, Column 0").grid(row=0, column=0)
tk.Label(window, text="Row 1, Column 1").grid(row=1, column=1)
3. place()
Precise positioning with x/y coordinates:
tk.Label(window, text="(100, 50)").place(x=100, y=50)
5. Real-World Project: To-Do List
Combine widgets and events to build a functional app:
window = tk.Tk()
window.title("To-Do List")
tasks = []
def add_task():
task = entry.get()
if task:
tasks.append(task)
listbox.insert(tk.END, task)
entry.delete(0, tk.END)
def remove_task():
selected = listbox.curselection()
if selected:
listbox.delete(selected[0])
# Widgets
entry = tk.Entry(window, width=30)
entry.grid(row=0, column=0, padx=5, pady=5)
add_btn = tk.Button(window, text="Add Task", command=add_task)
add_btn.grid(row=0, column=1, padx=5, pady=5)
listbox = tk.Listbox(window, width=40)
listbox.grid(row=1, column=0, columnspan=2)
remove_btn = tk.Button(window, text="Remove Task", command=remove_task)
remove_btn.grid(row=2, column=1, padx=5, pady=5)
window.mainloop()
6. Common Mistakes
- ❌ Forgetting
mainloop()
: The window won’t display. - ❌ Mixing layout managers: Use one (
grid
,pack
, orplace
) consistently. - ❌ Blocking the main thread: Use threading for long tasks to avoid freezing the GUI.
Best Practices
Organize code with classes:
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("My App")
self.create_widgets()
def create_widgets(self):
self.label = tk.Label(self, text="Hello!")
self.label.pack()
Use frames to group widgets:
frame = tk.Frame(window, borderwidth=2, relief="groove")
frame.pack(padx=10, pady=10)
tk.Label(frame, text="Inside Frame").pack()
Style your app with colors and fonts:
tk.Label(window, text="Styled Text",
font=("Arial", 12, "bold"),
fg="white", bg="blue").pack()
Key Takeaways
- ✅ Widgets: Labels, buttons, entries, and more build your UI.
- ✅ Events: Use
command
orbind()
to handle interactions. - ✅ Layout: Choose
grid()
,pack()
, orplace()
for organizing widgets. - ✅ Structure: Use classes and frames for maintainable code.
What’s Next?
Learn custom styling with ttkthemes or explore advanced widgets like Treeview for tables!