2. Nested event loops

Nested event loops are useful if you want to delegate event handling to separate functions or class methods.

The following is artificial example.

import sys
import pygame

pygame.init()
window = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

def keyboard_handler():
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            do_something()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    keyboard_handler()

    window.fill((0, 0, 0))
    pygame.display.flip()
    clock.tick(30)

This unfortunately doesn’t work. The second loop is run after first loop has been processed and thus it doesn’t contain events from first loop. Only events that were added to event queue after loop started are present in second loop.

So in most cases keyboard_handler function doesn’t get any events.

The fix is simple:

import sys
import pygame

pygame.init()
window = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

def keyboard_handler(events):
    for event in events:
        if event.type == pygame.KEYDOWN:
            do_something()

while True:
    events = pygame.events.get()
    for event in events:
        if event.type == pygame.QUIT:
            sys.exit()

    keyboard_handler(events)

    window.fill((0, 0, 0))
    pygame.display.flip()
    clock.tick(30)

Change here is that before processing events you take all current events and assign them to a variable. events in above code. Now you can pass and iterate over that events set as many times you wish.