Pygame modules for interactive programs

Resizable Pygame Windows

Pygame's video windows by default are locked to the size you provide in pygame.display.set_mode(). However, you can pass the parameter pygame.RESIZABLE, which will then allow the window to be resized by the user.

For a resizable Pygame window, the special Pygame event VIDEORESIZE appears on the queue whenever the window size changes. In my tests, the event was triggered by manual window resizing (dragging the corner of the window) and by maximizing the window. Minimizing the window did not trigger a VIDEORESIZE event.

When my code receives a VIDEORESIZE event, I need to use the supplied size tuple or the w (width) and h (height) parameters to redraw my screen content appropriately. Listing 5 shows how to access the properties of VIDEORESIZE.

Listing 5

Resizing Windows

01 import pygame
03 pygame.display.init()
04 screen = pygame.display.set_mode ( ( 320 , 240 ) , pygame.RESIZABLE )
06 running = True
07 while running:
08    for event in pygame.event.get():
09       if event.type == pygame.QUIT:
10          running = False
11       elif event.type == pygame.VIDEORESIZE:
12          print "The Pygame window is now " + str ( event.w ) + " pixels wide and " + str ( event.h ) + " pixels high"

Controlling the Event Queue

In the course of running a program, a lot of events are generated. Every move of the mouse over the Pygame window creates a stream of MOUSEMOTION events, for example. This large stream of events can overload the Pygame queue. To solve this problem, I used pygame.event.set_blocked() and pygame.event.set_allowed().

These functions control which events are allowed to appear on the event queue. By default, all of the events are enabled to appear on the queue. If you want to ignore mouse movement, you can say:

pygame.event.set_blocked ( pygame.MOUSEMOTION )

This will prevent mouse movements from appearing on the event queue. To see mouse movements again, call

pygame.event.set_allowed ( pygame.MOUSEMOTION )

to enable them.

The same process works for any Pygame event. For example, suppose the program is a flight simulator, but you want to display a full-screen map. you can disable joystick events while the map is visible and restore them when you return to flying.

Both functions also accept None as an argument. Calling

pygame.event.set_allowed ( None )

will disable all Pygame events. You can then use this to enable only specific events you want to pursue. Similarly, after disabling certain events, you can call

pygame.event.set_blocked ( None )

to enable all events in one go.

Buy this article as PDF

Express-Checkout as PDF

Pages: 2

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content