pygame.key.get_pressed() is not working

2019-01-27 21:59发布

问题:

I've read similar questions to this on Stack Overflow but they have not helped. Here is my code:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Hello World')
pygame.mouse.set_visible(1)

done = False
clock = pygame.time.Clock()

while not done:
    clock.tick(60)

    keyState = pygame.key.get_pressed()

    if keyState[pygame.K_ESCAPE]:
        print('\nGame Shuting Down!')
        done = True

Pressing escape does not exit the game or print a message. Is this a bug? If I print the value for keyState[pygame.K_ESCAPE], it is always zero.

回答1:

The problem is that you don't process pygame's event queue. You should simple call pygame.event.pump() at the end of your loop and then your code works fine:

...
while not done:
    clock.tick(60)

    keyState = pygame.key.get_pressed()

    if keyState[pygame.K_ESCAPE]:
        print('\nGame Shuting Down!')
        done = True
    pygame.event.pump() # process event queue

From the docs (emphasis mine):

pygame.event.pump()

internally process pygame event handlers

pump() -> None

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions.

This function is not necessary if your program is consistently processing events on the queue through the other pygame.event functions.

There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.

Note that you don't have to do this if you just call pygame.event.get() anywhere in your main-loop; if you do not, you should probably call pygame.event.clear() so the event queue will not fill up.



回答2:

May I suggest using an event que instead? It's probably a better idea:

while True: #game loop
    for event in pygame.event.get(): #loop through all the current events, such as key presses. 
        if event.type == QUIT:
            die()

        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE: #it's better to have these as multiple statments in case you want to track more than one type of key press in the future. 
                pauseGame()


回答3:

do something like this:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Hello World')
pygame.mouse.set_visible(1)

done = False
clock = pygame.time.Clock()

while not done:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    key = pygame.key.get_pressed()

    if key[K_ESCAPE]:
        print('\nGame Shuting Down!')

    pygame.display.flip()

you dont need the pygame.on the if statment and also you should call pygame.display.flip() so it properly shows the window then you need an event loop to exit the program



回答4:

You should provide the version of pygame and python.

I met the similar issue when I use pygame 1.9.4dev and python 3.6.5

I fix this problem after I downgrade pygame and reinstall python.

NOTE: If you use pyenv, you must make sure --enable-framework option is set when installing python.

# exit current virtualenv
$ pyenv deactivate
# reinstall python
$ PYTHON_CONFIGURE_OPTS="--enable-framework" pyenv install 3.6.5
# And reinstall pygame again.
pip install https://github.com/pygame/pygame/archive/1.9.3.zip

Use the following code to check whether it is work.

import pygame
import sys


def run():
    """Initialize pygame, settings, and screen object."""
    pygame.init()
    screen = pygame.display.set_mode((300, 200))
    pygame.display.set_caption('Keyboard Test')

    # main loop
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                print('KEY pressed is ' + str(event.key) + '.')

        # Make the most recently drawn screen visible.
        pygame.display.flip()


run()


标签: python pygame