Tyler Tyler - 8 days ago 6
Python Question

Key press is not being recognised by python's 'pygame.key.get_pressed()' module

I am trying to create a function where if a key is pressed, variables are changed. This will be put into a class that moves a sprite on a screen. The while loop is broken out of when the key is released. However, nothing happens. The while loop is running and I get no error. Does anyone know why this might be happening? I am not sure if I am using the module 'pygame.key.get_pressed()' correctly.

import pygame
from pygame.locals import *
def move():
for event in pygame.event.get():
if event.type == QUIT:
pygame.QUIT()
sys.exit()
while True:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
print("something happens")
#runs this, but when up arrow key is pressed does nothing
if event.type == KEYUP:
False

screen = pygame.display.set_mode((512,384))
move()
pygame.display.update()

Answer

get_pressed() returns list with information about pressed keys but this list is updated by pygame.event.get() and other event functions so you have to execute pygame.event.get() all the time. And this is why we do it in while-loop

import pygame   

pygame.init()
screen = pygame.display.set_mode((512,384))

while True:

    # get events and (somewhere in background) update list
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # get current list.
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]:
        print("UP")
Comments