Key Events: Programming in Python: Events and Animation
Key Events: Programming in Python: Events and Animation
Here is a simple program that draws a circle relative to the value associated to the keys on the keyboard. The value associated to each key will also be displayed in the windows caption (as long as Num, Caps, and Scroll Lock is turned off). Most key values have already been assigned a constant by Pygame. To see the names, go to http://www.pygame.org/docs/ref/key.html.
from pygame import * init() size = width, height = 800, 600 screen = display.set_mode(size) RED = (255, 0, 0) BLACK = (0, 0, 0) # This method draws a dot on the screen relative to the value of the key pressed def drawScene(screen): keys = key.get_pressed() # gets the state of all keyboard buttons screen.fill(BLACK) for i in range(len(keys)): # go through list of keys if keys[i]: # value will be True if the key is pressed draw.circle(screen, RED, (i*2,100), 2) display.set_caption(str(i)) # puts the key value as the caption display.flip() running = True myClock = time.Clock() while running: for evnt in event.get(): if evnt.type == QUIT: running = False drawScene(screen) myClock.tick(60) quit() # checks all events that happen