'How can I execute a function when a specific key is pressed and released in python [duplicate]
I'm trying to write a 2D game in Python and I'm trying to call a function when I press and release Spacebar from my keyboard. If I'm using the function "is_pressed()" from keyboard it will be continuously called and glitch my program. Can you help, please?
Solution 1:[1]
You have to use the keyboard events instead. pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement. The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
e.g.:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# do something
# [...]
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
# do something
# [...]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rabbid76 |
