Error in the pygame.key.get_pressed() method

1.5k Views Asked by At

I have no idea why the following is giving the error: name 'K_SPACE' is not defined. Importing pygame also imports the keyboard constants which includes 'K_SPACE'.

My code:

if pygame.key.get_pressed()[K_SPACE]:
    pygame.quit

Thanks

3

There are 3 best solutions below

1
jgritty On BEST ANSWER

if you just did this:

import pygame

Then you need to do this:

if pygame.key.get_pressed()[pygame.K_SPACE]:
    pygame.quit
0
jcollado On

If the interpreter complains about the symbol not being defined, probably you need to fully qualify the name:

if pygame.key.get_pressed()[pygame.K_SPACE]:
    pygame.quit

or explicitly import it:

from pygame import K_SPACE
...
if pygame.key.get_pressed()[K_SPACE]:
    pygame.quit
0
Thijs Meijerink On

Add:

from pygame.locals import *

to the beginning of your program, this will import the key variables.