How to use pygame.KEYDOWN to execute something every time through a loop while the key is held down?

Use pygame.KEYDOWN and pygame.KEYUP to detect if a key is physically pressed down or released. You can activate keyboard repeat by using pygame.key.set_repeat to generate multiple pygame.KEYDOWN events when a key is held down, but that’s rarely a good idea.

Instead, you can use pygame.key.get_pressed() to check if a key is currently held down:

while True:
    ...
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_w]:
       print("w is pressed")
    if pressed[pygame.K_s]:
       print("s is pressed")

Leave a Comment