Module 18 β GUI Programming with Tkinter
Building your first windowed, clickable desktop application.
Prerequisite: Module 17 β OS & System Modules
After this lesson, you will be able to
- Create a window and add labels, buttons, and entry fields
- Respond to a button click with a callback function
- Explain event-driven programming
Concept & Syntax
Every program you've written so far ran top to bottom and finished. A GUI (graphical user interface) application is different: it draws a window, then waits β doing nothing until the user clicks something. This is event-driven programming: you write small functions ("callbacks") that run in response to specific events, like a button click.
tkinter is Python's built-in GUI toolkit β no extra installation required β making it the
natural starting point for desktop app development.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello")
label.pack()
root.mainloop()Examples
Your first window Very Easy
import tkinter as tk
root = tk.Tk()
root.title("My First App")
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(padx=20, pady=20)
root.mainloop()Tk() creates the main window; .pack() places a widget inside it; mainloop() starts the event loop that keeps the window open and responsive.
A button with a callback Easy
import tkinter as tk
def on_click():
label.config(text="Button was clicked!")
root = tk.Tk()
label = tk.Label(root, text="Waiting...")
label.pack(pady=10)
button = tk.Button(root, text="Click me", command=on_click)
button.pack(pady=10)
root.mainloop()command=on_click registers on_click as the callback β it runs automatically whenever the button is clicked. This is event-driven programming in action.
Reading an Entry field Real World
import tkinter as tk
def greet():
name = entry.get()
result_label.config(text=f"Hello, {name}!")
root = tk.Tk()
entry = tk.Entry(root)
entry.pack(pady=5)
tk.Button(root, text="Greet", command=greet).pack(pady=5)
result_label = tk.Label(root, text="")
result_label.pack(pady=5)
root.mainloop()entry.get() reads whatever text the user has typed into the Entry widget at the moment the button is clicked.
Visual Explanation
π‘ Why does this work?
Read the concept explanation above again slowly, line by line β every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.
π What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory β which is exactly what the memory panel in the tracer above is showing you.
Common Mistakes
Forgetting root.mainloop() means the window either never appears or closes immediately, because the event loop that keeps it alive never starts.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hi")
label.pack()
# forgot root.mainloop()import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hi")
label.pack()
root.mainloop()- Always end a tkinter script with root.mainloop().
- Keep callback functions short β have them call other functions for complex logic.
- Use .pack(), .grid(), or .place() consistently within one container β mixing them can cause confusing layouts.
- Wrap risky operations inside a button callback in try/except, and show errors with tkinter.messagebox instead of crashing the whole app.
Exercise & Challenge
Exercise 1 β Predict the output
In the button example above, what will the label say immediately after the window opens, before anything is clicked?
π Challenge
Build a tiny Tkinter app with an Entry field and a button that shows a message box (using tkinter.messagebox) confirming whatever the user typed.
- Use an Entry widget to collect text
- Use tkinter.messagebox.showinfo() to display it
- Give the window a title
π‘ Need a hint?
from tkinter import messagebox, then messagebox.showinfo("Title", f"You typed: {text}")
π Show a sample solution
import tkinter as tk
from tkinter import messagebox
def show_message():
messagebox.showinfo("You typed", entry.get())
root = tk.Tk()
root.title("Echo App")
entry = tk.Entry(root)
entry.pack(pady=5)
tk.Button(root, text="Show", command=show_message).pack(pady=5)
root.mainloop()Quiz
Answer every question, then submit to see your score and explanations.
1. What starts a tkinter window's event loop?
2. What is a 'callback' in event-driven programming?
3. How do you read text a user typed into an Entry widget?
Summary
- tkinter is Python's built-in GUI toolkit β no extra install required.
- GUI programs are event-driven: they wait in mainloop() and respond to user actions via callbacks.
- Label, Button, and Entry are the core widgets for displaying text, triggering actions, and collecting input.
- Always end a tkinter script with root.mainloop().