Python:Pygame keyboard input

From GPWiki
Jump to: navigation, search
40x-binary.png This tutorial was written for an older version of Python and some features may be depreciated.
For more information visit What's New In Python 3.0.

Introduction

Pygame is a Python module built on top of SDL.

This tutorial will go through a Python script that initializes Pygame, displays key press event information and exit when the escape key is detected.

Requirements: Python, Pygame

The Script

PygameKeyEvents.py

#!/usr/bin/env python 
 
import pygame
from pygame.locals import *
 
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Pygame Caption')
pygame.mouse.set_visible(0)
 
done = False
while not done:
   for event in pygame.event.get():
      if (event.type == KEYUP) or (event.type == KEYDOWN):
         print event
         if (event.key == K_ESCAPE):
            done = True

Step by step explanation

Import

import pygame
from pygame.locals import *

Import the Pygame module, throwing an exception if unable to import.

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Pygame Caption')
pygame.mouse.set_visible(0)

Initialize Pygame. Set the display mode to 640 by 480, using the default/system color depth. Set the caption to 'Pygame Caption'. Set the mouse to be invisible.

If you do not set a pygame display pygame screen, no input will get to pygame's event handling.

done = False
while not done:
   for event in pygame.event.get():
      if (event.type == KEYUP) or (event.type == KEYDOWN):
         print event
         if (event.key == K_ESCAPE):
            done = True

While not done, check for events to process. If the event is a KeyUp or KeyDown event, print it to console. If the escape key is pressed, set the 'done' flag to True, which will stop the while-loop.

This will loop until the escape key is pressed, writing key event information to console.