PyComplete Python Course
Intermediate 50 min

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.

Syntax
import tkinter as tk
 
root = tk.Tk()
label = tk.Label(root, text="Hello")
label.pack()
root.mainloop()

Examples

Your first window Very Easy

Your first window
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()
Output(opens a small window containing the text 'Hello, Tkinter!')

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

A button with a callback
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()
Output(the label text changes to 'Button was clicked!' when the button is pressed)

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

Reading an Entry field
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()
Output(typing a name and clicking Greet displays a personalized greeting)

entry.get() reads whatever text the user has typed into the Entry widget at the moment the button is clicked.

Visual Explanation

Create window (Tk())Add widgets (Label, Button, Entry)root.mainloop() starts β€” window becomes responsiveUser clicks a buttonThat button's callback function runs
A GUI app spends most of its life inside mainloop(), waiting for events.
πŸ’‘ 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

βœ— Common mistake 1

Forgetting root.mainloop() means the window either never appears or closes immediately, because the event loop that keeps it alive never starts.

βœ— Avoid this
This raises the script runs and exits instantly β€” no window stays visible
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hi")
label.pack()
# forgot root.mainloop()
βœ“ Better approach
Fixed
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hi")
label.pack()
root.mainloop()
βœ“ Best practices
  • 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
Python
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?

root.start()
root.mainloop()
root.run()
It starts automatically
mainloop() keeps the window open and listening for events until it's closed.

2. What is a 'callback' in event-driven programming?

A function that runs automatically in response to an event
A type of variable
A kind of loop
An error message
A callback is code you register to run when a specific event (like a click) happens.

3. How do you read text a user typed into an Entry widget?

entry.text
entry.value
entry.get()
entry.read()
.get() retrieves the current text from 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().

Related lessons

Saved privately in your browser β€” no account needed.