Tkinter: GUI Basics & Layout
Until now, our Python programs interacted through the console (CLI). A Graphical User Interface (GUI) replaces textual input with visual windows, text boxes, and buttons. Python includes Tkinter in its standard library — the fastest way to build desktop graphical applications.
Learning Objectives
- 11.3.3.1 Use widgets for data entry (
Entry) - 11.3.3.2 Use widgets to show results or messages (
Label) - 11.3.3.4 Solve applied problems from various subject areas
Conceptual Anchor
Linear Flow vs Event-Driven Programming
In console scripts, execution is sequential: line 1, then line 2, then wait for input(). In a GUI, execution is event-driven: the application creates a window, displays buttons and text fields, and sits in an infinite loop (mainloop()) waiting for user actions (clicks, keypresses) to trigger corresponding callback functions.
Rules & Theory
1. The Tkinter Skeleton
import tkinter as tk
# 1. Initialize root window
root = tk.Tk()
root.title("My First GUI")
root.geometry("400x250") # width x height in pixels
root.resizable(False, False) # prevent window resizing
# 2. Add widgets here...
# 3. Start the infinite event loop
root.mainloop()2. Core Widgets: Label, Entry, Button
| Widget | Creation Syntax | Key Methods & Properties |
|---|---|---|
| Label (Display text/image) | lbl = tk.Label(root, text="Hello", font=("Arial", 14)) |
lbl.config(text="New Text") to update text dynamically. |
| Entry (Single-line input) | entry = tk.Entry(root, width=25, font=("Arial", 12)) |
entry.get() reads text; entry.delete(0, tk.END) clears. |
| Button (Action trigger) | btn = tk.Button(root, text="Click Me", command=on_click) |
command=func_name attaches callback function (without parentheses). |
3. Geometry Managers: pack() vs grid()
| Manager | Description | Common Arguments |
|---|---|---|
pack() |
Simple stacking (vertical or horizontal) | side=tk.TOP, padx=10, pady=5, fill=tk.X |
grid() |
Structured 2D spreadsheet layout (rows & columns) | row=0, column=1, columnspan=2, sticky="w" |
Worked Examples
1 Interactive Greeting App (Pack Layout)
Read a user's name from an Entry field and display a personalized greeting on button click:
import tkinter as tk
def greet_user():
name = name_entry.get().strip()
if name:
result_label.config(text=f"Welcome to NIS, {name}! 🎉", fg="#00a65a")
else:
result_label.config(text="Please enter your name!", fg="#d9534f")
root = tk.Tk()
root.title("Greeting App")
root.geometry("350x200")
# Widgets
prompt = tk.Label(root, text="Enter your name:", font=("Arial", 11))
prompt.pack(pady=10)
name_entry = tk.Entry(root, font=("Arial", 12), width=20)
name_entry.pack(pady=5)
greet_button = tk.Button(root, text="Greet Me", font=("Arial", 11, "bold"),
bg="#007acc", fg="white", command=greet_user)
greet_button.pack(pady=10)
result_label = tk.Label(root, text="", font=("Arial", 12, "bold"))
result_label.pack(pady=5)
root.mainloop()2 Temperature Converter: Celsius to Fahrenheit (Grid Layout)
Structured two-column form using grid() layout:
import tkinter as tk
def convert_temp():
try:
celsius = float(entry_c.get())
fahrenheit = celsius * 9 / 5 + 32
label_result.config(text=f"{fahrenheit:.1f} °F", fg="blue")
except ValueError:
label_result.config(text="Invalid input!", fg="red")
root = tk.Tk()
root.title("Temperature Converter")
root.geometry("320x160")
# Row 0: Input
tk.Label(root, text="Celsius (°C):", font=("Arial", 11)).grid(row=0, column=0, padx=15, pady=15, sticky="e")
entry_c = tk.Entry(root, font=("Arial", 11), width=10)
entry_c.grid(row=0, column=1, padx=15, pady=15, sticky="w")
# Row 1: Convert Button
btn_convert = tk.Button(root, text="Convert", command=convert_temp, font=("Arial", 10, "bold"))
btn_convert.grid(row=1, column=0, columnspan=2, pady=5)
# Row 2: Result
tk.Label(root, text="Fahrenheit:", font=("Arial", 11)).grid(row=2, column=0, padx=15, pady=10, sticky="e")
label_result = tk.Label(root, text="--", font=("Arial", 12, "bold"))
label_result.grid(row=2, column=1, padx=15, pady=10, sticky="w")
root.mainloop()Pitfalls & Common Errors
Passing command=func() Instead of command=func
Writing command=convert() with parentheses executes the function immediately when the window opens and assigns its return value (None) to the button. Always pass the function name without parentheses: command=convert.
Mixing pack() and grid()
Never call .pack() on one widget and .grid() on another widget within the same parent window! Doing so causes an infinite layout calculation loop and freezes the application.
Forgetting entry.get()
Remember that an Entry widget itself is a graphical object. To get the text typed by the user, you must call its method: text_value = my_entry.get().
Pro-Tips for Exams
Exam Checklist
- All user input from
entry.get()is returned as a string. Always cast toint()orfloat()inside atry...exceptblock when doing calculations. - To clear an entry box:
my_entry.delete(0, tk.END). - To update text in a label:
my_label.config(text="Updated message"). - Every Tkinter program must terminate with
root.mainloop().
Graded Tasks
Name the primary method used to start a Tkinter window's event loop and prevent it from closing.
Explain why passing command=calculate() causes bugs compared to command=calculate.
Create a GUI with an Entry field and a Button. When clicked, calculate and display the square of the entered number in a Label.
Compare the advantages of grid() over pack() when designing multi-field user registration forms.
Build an interactive Currency Converter (KZT to USD / EUR): two Entry boxes, conversion buttons, and formatted output with input error checking.
Self-Check Quiz
entry.get() return?lbl?pack() and grid() inside the same parent window?root.geometry('400x300') configure?