Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pygame: pygame.KEYDOWN not working

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!

like image 965
0_01_001 Avatar asked Jan 21 '26 12:01

0_01_001


1 Answers

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! :)')
like image 156
jDo Avatar answered Jan 23 '26 19:01

jDo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!