Skip to content

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 typeExamples
User inputMouse click, key press, button tap, scroll
System eventsTimer fires, file downloaded, network message received
Programme eventsAnother 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 PROCEDURE

Event loop

The event loop is the core of every event-driven program. It continuously:

  1. Waits for an event.
  2. Identifies which handler should respond.
  3. Calls that handler.
  4. 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() → EXIT

Structure of an event-driven program

An event-driven program has three main parts:

  1. Initialisation - set up the interface and register event handlers.
  2. Event handlers - define what happens for each event.
  3. 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

FeatureDescription
Event handlersFunctions called in response to specific events
Event loopContinuously polls for events and dispatches them
TriggerThe specific event that causes a handler to run
Non-sequential executionCode doesn't run in a fixed order - order depends on what the user does
ResponsiveProgram can respond to multiple different events

Event-driven vs procedural vs OOP

ProceduralOOPEvent-driven
Flow controlled bySequence of callsObject interactionsEvents from user/system
Entry pointMain procedureMain methodEvent loop
Best forScripts, sequential tasksComplex systems, modellingGUIs, games, web apps
ExampleData processingBanking systemCalculator 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

AdvantagesDisadvantages
Natural for user interfacesCan be hard to trace/debug (execution order is unpredictable)
Responsive - reacts to what users doRisk of events being missed if handlers are slow
Handles many different inputsComplex to design correctly for large numbers of events
Non-blocking - program doesn't freezeDifficult to test systematically

Test Yourself

Question 1 of 5

What triggers code execution in an event-driven program?

Ad

PassMaven - revision made simple.