Reputation: 43
import pygame
pygame.init()
events = pygame.event.get()
while True:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this should work!!')
I am new to both python and pygame , just trying to test the keydown event but it doesn't works....please help!
Upvotes: 3
Views: 6365
Reputation: 4010
You need to set up some display properties before you can use keyboard events. No window, no key events. So add something like this before the while
loop and it should work:
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
Normally, you'd also set up a clock using clock = pygame.time.Clock()
, frames per second used in clock.tick(frames_per_second)
, some objects/players/rects etc. before the loop but I'll leave that to you.
Here's your code with a bare minimum display setup that'll enable key events:
import pygame
pygame.init()
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this DOES work! :)')
Upvotes: 1
Reputation: 23490
Because Pygame only runs on Python v3.2 and below I can't test this right now.
But if i'm not totally off my meds I think this is because you're not updating the display.
Consider this change:
import pygame
pygame.init()
events = pygame.event.get()
while True:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this should work!!')
pygame.display.flip()
This will update the display AND trigger the events occuring in the display.
If you don't do this you'll end up with a stale window that doesn't trigger, render or produce anything really except maybe a initial render.
Equally, in many GL libraries you need to empty the event buffer otherwise the same effect will occur. Meaning you'll end up with a stale window that just "hangs" because events are trying to "get in" to the buffer, but you havn't emptied it on a regular basis. (Some graphic libraries even require you to poll the event pool even if it's empty just to "release" the event queue).
So keep in mind when working with graphics:
Upvotes: 0