Concept Explanation
A layout is a photograph. Events turn it into an application.
Every GUI framework runs an event loop: an endless cycle that asks the operating system "did anything happen?", finds the widget concerned, and calls the function you registered for it. In Tkinter that loop is root.mainloop(), and everything your app does happens inside it, in response to something.
This inverts how you have written Python so far. Your script no longer drives the sequence — the user does. You supply callbacks and wait to be called.
Two Ways to Hook Up a Response
| Mechanism | Syntax | Use for |
|---|---|---|
command= | ttk.Button(root, command=save) | The widget's one obvious action |
.bind() | entry.bind("<Return>", on_enter) | Keys, mouse, focus, anything else |
Note what you pass to command: the function object, not a call. command=save registers it. command=save() runs it immediately at start-up and registers the return value — a bug that looks like "my button fired before I clicked it."
Passing Arguments to a Callback
Since you cannot write command=greet("Ada"), use one of these:
from functools import partial
ttk.Button(root, text="A", command=lambda: greet("Ada")) # lambda
ttk.Button(root, text="B", command=partial(greet, "Grace")) # partial -- clearer
The Event Object
A bind callback receives one argument describing what happened:
| Attribute | Meaning |
|---|---|
event.widget | Which widget it happened to |
event.x, event.y | Mouse position inside the widget |
event.keysym | Key name, e.g. "Return", "Escape", "a" |
event.char | The character typed, if any |
Common Event Patterns
| Pattern | Fires on |
|---|---|
<Button-1> | Left mouse click |
<Double-Button-1> | Double click |
<Return> | Enter key |
<Escape> | Escape key |
<KeyRelease> | Any key released — good for live search |
<FocusOut> | Widget lost focus — good for validation |
<Configure> | Widget was resized |
Control Variables: The Reactive Layer
tk.StringVar, IntVar, BooleanVar, and DoubleVar are values the UI watches. Attach one to a widget and setting the variable updates the widget automatically — no manual redraw.
status = tk.StringVar(value="Ready")
ttk.Label(root, textvariable=status).pack()
status.set("Saving...") # the label changes by itself
Add a trace_add and you get the reverse direction too: run code whenever the value changes.
Code Example #1 (Basic)
A click counter, a keyboard shortcut, and a live status line.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Events")
root.geometry("300x150")
count = tk.IntVar(value=0)
status = tk.StringVar(value="Click the button or press Enter")
def increment(event=None):
"""Works as a command= callback AND as a bind callback.
The event=None default is the trick: command= passes no arguments,
bind passes exactly one.
"""
count.set(count.get() + 1)
status.set(f"Clicked {count.get()} time(s)")
ttk.Label(root, textvariable=status).pack(pady=10)
ttk.Button(root, text="Click me", command=increment).pack()
ttk.Label(root, textvariable=count, font=("", 24)).pack(pady=6)
root.bind("<Return>", increment) # Enter anywhere in the window
root.bind("<Escape>", lambda e: root.destroy()) # Escape closes the app
root.mainloop()
Code Example #2 (Intermediate)
Live filtering, field validation, and a confirmed exit.
import tkinter as tk
from tkinter import ttk, messagebox
FRUITS = ["Apple", "Apricot", "Banana", "Blueberry", "Cherry", "Grape", "Mango"]
root = tk.Tk()
root.title("Live Search")
root.geometry("360x300")
query = tk.StringVar()
results = tk.Variable(value=FRUITS)
def refilter(*_args):
"""Called by trace_add on every keystroke -- no button needed."""
needle = query.get().strip().lower()
matches = [f for f in FRUITS if needle in f.lower()]
results.set(matches or ["(no matches)"])
query.trace_add("write", refilter) # the reactive hook
ttk.Label(root, text="Search:").pack(anchor="w", padx=12, pady=(12, 0))
box = ttk.Entry(root, textvariable=query)
box.pack(fill="x", padx=12)
box.focus_set() # cursor starts here
listbox = tk.Listbox(root, listvariable=results, height=8)
listbox.pack(fill="both", expand=True, padx=12, pady=12)
def on_pick(event):
sel = event.widget.curselection()
if sel:
messagebox.showinfo("Picked", event.widget.get(sel[0]))
listbox.bind("<Double-Button-1>", on_pick)
listbox.bind("<Return>", on_pick)
# --- Validation on focus loss ---
age_row = ttk.Frame(root)
age_row.pack(fill="x", padx=12, pady=(0, 12))
ttk.Label(age_row, text="Age:").pack(side="left")
age = ttk.Entry(age_row, width=8)
age.pack(side="left", padx=6)
def check_age(event):
text = age.get().strip()
if text and not text.isdigit():
messagebox.showwarning("Invalid", "Age must be a whole number.")
age.focus_set() # send them back to fix it
age.bind("<FocusOut>", check_age)
def confirm_quit():
if messagebox.askokcancel("Quit", "Close without saving?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", confirm_quit) # intercept the X button
root.mainloop()
Three professional touches here: trace_add gives search-as-you-type with no button, <FocusOut> validates at the moment the user leaves a field, and WM_DELETE_WINDOW lets you catch the window's close button instead of losing unsaved work.
Common Mistakes
command=save()instead ofcommand=save: the parentheses call it now. Your callback fires once at start-up and never again.- The lambda-in-a-loop trap:
for i in range(3): Button(command=lambda: pick(i))— all three buttons report2, because the lambda captures the variable, not its value. Fix withlambda i=i: pick(i)orpartial(pick, i). - Wrong callback arity:
command=calls your function with no arguments;bindcalls it with one. Reusing a function for both needsdef handler(event=None). - Blocking the event loop: a
time.sleep(5)or a large file download in a callback freezes the entire window — no repaints, no clicks. Useroot.after()for delays and athreading.Threadfor slow work. - Updating widgets from a background thread: Tkinter is not thread-safe. Have the thread put results on a
queue.Queueand poll it from the main thread withroot.after(). - Binding to the wrong widget:
root.bind("<Return>")is global;entry.bind("<Return>")only fires when that entry has focus. Choose deliberately. - Using
<Key>to read an Entry's contents: the event fires before the character is inserted, so you read a stale value. Use<KeyRelease>or aStringVartrace.
Best Practices
- Keep callbacks short: validate inputs, call a plain function that holds the real logic, update the UI. Business logic in a callback is untestable.
- Use
root.after(ms, fn)instead oftime.sleep: it schedules work without freezing the loop. - Prefer control variables to manual
.config(text=...): oneStringVarcan drive several widgets and keeps state in one place. - Give keyboard users a path: bind
<Return>to your primary action and<Escape>to cancel. It costs two lines. - Debounce expensive live handlers: on a large dataset, cancel and reschedule with
after_cancel/afterso you filter once per pause, not once per keystroke. - Intercept
WM_DELETE_WINDOWwhenever there is unsaved state. - Set an initial
focus_set(): the user should be able to start typing immediately.
Practice Exercises
- The Temperature Converter: Two entries, Celsius and Fahrenheit. Using
StringVartraces, typing in either one updates the other live — and non-numeric input shows a message instead of crashing. - The Loop Buttons: Create five buttons in a
forloop, each of which must print its own index. First reproduce the closure bug where all five print4, then fix it two different ways and comment on which you prefer. - The Non-Freezing Task: Add a "Process" button that simulates five seconds of work. First do it with
time.sleepand observe the window locking up completely; then rewrite it withroot.afterchunks so a progress label keeps updating and the window stays responsive.