Appearance
D3 · Event-Driven Programming
Spec reference: Section D - Programming Languages
Key idea: Programs respond to events - user actions or system signals - rather than following a fixed sequence.
What is event-driven programming?
Event-driven programming is a paradigm where the flow of the program is determined by events - user actions, messages from other programs, or sensor/system signals - rather than a predetermined sequential order.
Key definition
Event-driven programming - a paradigm where program execution is triggered by events (such as mouse clicks, key presses, or network messages) rather than following a fixed sequential flow.
The program spends most of its time waiting in an event loop, listening for events and responding to them.
Core concepts
Events
An event is anything that happens that the program should know about:
| Event type | Examples |
|---|---|
| User input | Mouse click, key press, button tap, scroll |
| System events | Timer fires, file downloaded, network message received |
| Programme events | Another object signals a change in state |
Event handlers (listeners)
An event handler (also called an event listener or callback) is a function that is automatically called when a specific event occurs.
python
# Web-style concept (simplified pseudocode)
WHEN button_clicked:
CALL on_button_click()
PROCEDURE on_button_click()
SEND "Button was clicked!" TO DISPLAY
END PROCEDUREEvent loop
The event loop is the core of every event-driven program. It continuously:
- Waits for an event.
- Identifies which handler should respond.
- Calls that handler.
- Returns to waiting.
START
│
▼
[Event loop - waiting...]
│
├── User clicks button → call on_click()
├── User presses key → call on_keypress()
├── Timer fires → call on_timer()
└── Window closed → call on_close() → EXITStructure of an event-driven program
An event-driven program has three main parts:
- Initialisation - set up the interface and register event handlers.
- Event handlers - define what happens for each event.
- Event loop - wait for events and dispatch them to the correct handler.
Python example with Tkinter (GUI)
python
import tkinter as tk
# 1. Initialisation
window = tk.Tk()
window.title("Event-Driven Demo")
count = 0
# 2. Event handlers
def on_button_click():
global count
count += 1
label.config(text=f"Clicked {count} times")
def on_key_press(event):
label.config(text=f"Key pressed: {event.char}")
# Create widgets
button = tk.Button(window, text="Click me!", command=on_button_click)
label = tk.Label(window, text="Waiting...")
button.pack(pady=10)
label.pack(pady=10)
window.bind("<Key>", on_key_press) # register key press handler
# 3. Event loop - runs until window is closed
window.mainloop()Key features of event-driven programming
| Feature | Description |
|---|---|
| Event handlers | Functions called in response to specific events |
| Event loop | Continuously polls for events and dispatches them |
| Trigger | The specific event that causes a handler to run |
| Non-sequential execution | Code doesn't run in a fixed order - order depends on what the user does |
| Responsive | Program can respond to multiple different events |
Event-driven vs procedural vs OOP
| Procedural | OOP | Event-driven | |
|---|---|---|---|
| Flow controlled by | Sequence of calls | Object interactions | Events from user/system |
| Entry point | Main procedure | Main method | Event loop |
| Best for | Scripts, sequential tasks | Complex systems, modelling | GUIs, games, web apps |
| Example | Data processing | Banking system | Calculator app |
Real-world examples of event-driven programs
- GUI applications - every button click, menu selection, scroll is an event.
- Web browsers - clicking a link, submitting a form, loading a page.
- Games - key press = move character; collision = trigger sound and score.
- Smartphone apps - tap, swipe, pinch are all events.
- IoT devices - a motion sensor detecting movement fires an event.
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Natural for user interfaces | Can be hard to trace/debug (execution order is unpredictable) |
| Responsive - reacts to what users do | Risk of events being missed if handlers are slow |
| Handles many different inputs | Complex to design correctly for large numbers of events |
| Non-blocking - program doesn't freeze | Difficult to test systematically |
Test Yourself
Question 1 of 5
What triggers code execution in an event-driven program?