Tkinter: Advanced Widgets & Project
In this capstone programming lesson, we master containerization with Frames, multi-option selections with Checkbuttons and Radiobuttons, alert dialogs with messagebox, and bring all concepts together into a complete GUI project.
Learning Objectives
- 11.3.3.3 Use widgets with buttons, switches, and containers (
Frame,Radiobutton,Checkbutton) - 11.3.3.2 Use widgets to show results or messages (
messagebox) - 11.3.3.4 Solve applied problems from various subject areas
Lesson Presentation
11.4A-lesson-27-tkinter-widgets-project.pdf · Slides for classroom use
Conceptual Anchor
The Bento Box Architecture
A great user interface organizes controls into logical compartments. In Tkinter, a Frame is a bento box compartment: you can place multiple buttons or inputs inside a frame, and then position the entire frame anywhere on the window. Radiobuttons act like a radio tuner (only one station selected at a time), while Checkbuttons act like pizza toppings (select any combination).
Rules & Theory
1. Tkinter Control Variables
To connect widgets like Radiobuttons and Checkbuttons with Python data, Tkinter uses reactive variable classes:
var_str = tk.StringVar(value="Default text")
var_int = tk.IntVar(value=1)
var_bool = tk.BooleanVar(value=False)
# Read value
current = var_str.get()
# Change value (updates connected GUI widgets automatically)
var_str.set("Updated text")2. Containers: Frames
# Frame acting as a grouped container
header_frame = tk.Frame(root, padx=10, pady=10, bg="#f0f0f0", bd=2, relief=tk.GROOVE)
header_frame.pack(fill=tk.X, padx=10, pady=5)
# Place widgets inside the frame (parent is header_frame, not root!)
lbl = tk.Label(header_frame, text="Control Panel")
lbl.pack()3. Switches & Dialogs
| Feature | Syntax | Rule |
|---|---|---|
| Radiobutton (Mutual Exclusive) | tk.Radiobutton(root, text="Option A", variable=radio_var, value="A") |
All options in the same group must share the same variable, but have distinct value arguments. |
| Checkbutton (Independent Toggle) | tk.Checkbutton(root, text="Agree", variable=chk_var) |
Each Checkbutton requires its own separate IntVar() or BooleanVar(). |
| messagebox (Popups) | from tkinter import messagebox |
Standard modal popups: showinfo(), showwarning(), showerror(), askyesno(). |
Worked Examples
1 Radiobutton Quiz System with Messagebox
Interactive single-choice question with instant feedback popup:
import tkinter as tk
from tkinter import messagebox
def check_answer():
selected = selected_option.get()
if selected == "Python":
messagebox.showinfo("Result", "Correct! Python was created by Guido van Rossum.")
elif selected == "":
messagebox.showwarning("Warning", "Please select an answer first!")
else:
messagebox.showerror("Result", f"Incorrect. '{selected}' is not correct.")
root = tk.Tk()
root.title("CS Quiz")
root.geometry("380x250")
tk.Label(root, text="Which language was created by Guido van Rossum?",
font=("Arial", 11, "bold"), wraplength=340).pack(pady=15)
selected_option = tk.StringVar(value="")
options = ["Java", "C++", "Python", "JavaScript"]
for opt in options:
tk.Radiobutton(root, text=opt, variable=selected_option,
value=opt, font=("Arial", 11)).pack(anchor="w", padx=40, pady=2)
tk.Button(root, text="Submit Answer", command=check_answer,
bg="#007acc", fg="white", font=("Arial", 10, "bold")).pack(pady=15)
root.mainloop()2 Complete GUI Project: Simple Desktop Calculator
A full responsive calculator implemented with Tkinter grid layout:
import tkinter as tk
def btn_click(item):
current = display_var.get()
display_var.set(current + str(item))
def btn_clear():
display_var.set("")
def btn_equal():
try:
result = str(eval(display_var.get()))
display_var.set(result)
except Exception:
display_var.set("Error")
root = tk.Tk()
root.title("NIS Calculator")
root.geometry("300x380")
root.resizable(False, False)
display_var = tk.StringVar(value="")
# Display Screen
entry = tk.Entry(root, textvariable=display_var, font=("Arial", 20),
bd=5, relief=tk.RIDGE, justify="right")
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=15, ipady=10)
# Buttons Matrix
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('C', 4, 0), ('0', 4, 1), ('=', 4, 2), ('+', 4, 3),
]
for (text, r, c) in buttons:
if text == "=":
cmd = btn_equal
bg_col = "#00a65a"
elif text == "C":
cmd = btn_clear
bg_col = "#d9534f"
else:
cmd = lambda t=text: btn_click(t)
bg_col = "#e0e0e0"
tk.Button(root, text=text, font=("Arial", 14, "bold"), width=4, height=2,
bg=bg_col, command=cmd).grid(row=r, column=c, padx=4, pady=4)
root.mainloop()Pitfalls & Common Errors
Radiobuttons Not Mutually Exclusive
If each Radiobutton is assigned a different StringVar(), clicking one will not uncheck the others. Grouped Radiobuttons must share the exact same variable instance.
Lambda Loop Late-Binding Bug
When creating buttons in a loop with command=lambda: btn_click(text), all buttons end up using the final loop value of text! Always write lambda t=text: btn_click(t) to capture the current value as a default parameter.
Pro-Tips for Exams
Exam Checklist
- Use
messagebox.askyesno("Exit", "Are you sure?")which returns booleanTrueorFalseto confirm destructive user actions. - To arrange a layout cleanly, divide the window into 2–3
Framewidgets (e.g.top_frame,content_frame,bottom_frame). Inside each frame, you can use eitherpack()orgrid()safely. - To read a Checkbutton's state:
var.get()returns1(checked) or0(unchecked).
Graded Tasks
Which Tkinter widget groups and organizes other widgets into isolated rectangular sections?
Explain how Radiobuttons ensure mutual exclusivity through the variable property.
Create an application with 3 Checkbuttons for optional pizza toppings. Display the calculated total price as checkboxes are toggled.
Explain why messagebox.showwarning() pauses code execution until the dialog is closed (modal behavior).
Build a comprehensive Student Registration Form: Name & Surname entries, Grade level radio buttons, Extracurricular activities checkbuttons, and a Submit button with validation popups.
Self-Check Quiz
messagebox.askyesno() give?