How to efficiently hold a key in Pygame?

Related searches

I've found two related questions:

  • Pygame hold key down causes an infinite loop
  • pygame - on hold button down

But I want to be specific. How to?

while not done:
    for e in event.get():
        if e.type == KEYDOWN:
            keys = key.get_pressed()
            if e.type == QUIT or keys[K_ESCAPE]:
                done = True
            if keys[K_DOWN]:
                print "DOWN"

When I press the down arrow, it prints, but it prints just once. If I want to print it another time, I need to press it again.

If I use the while keyword instead,

while keys[K_DOWN]:
    print "DOWN"

I get an infinite loop for some obscure reason.

This logical alternative is also useless:

if ((e.type == KEYDOWN) and keys[K_DOWN]):
    print "DOWN"

And there is this other one that somehow cleans the events and you can use while:

while not done:
    for e in event.get():
        if e.type == KEYDOWN:
            keys = key.get_pressed()
            if e.type == QUIT or keys[K_ESCAPE]:
                done = True
            while keys[K_DOWN]:
                print "DOWN"
                event.get()
                keys = key.get_pressed()

But you press the down key for less than one second and it prints thousands of times. (Moving a player would be impossible, and adjusting clock for this does not seem to be the right way to deal with it (And I've tried and I've failed miserably.)).

To press and execute the block thousands of times is useless. What I want, is to press the key and keep going with the action while I don't release it, within the defined game clock speed.


Don't mix up event.get() and key.get_pressed().


If you press or release a key, and event is put into the event queue, which you query with event.get(). Do this if you're actually interested if a key was pressed down physically or released (these are the actual keyboard events. Note that KEYDOWN get's added multiple time to the queue depending on the key-repeat settings).

Also, there's no need to query the state of all keys while handling a KEYDOWN event, since you already know which key is pressed down by checking event.key


If you're interested in if a key is hold down (and ignoring the key-repeat, which you probably want), then you should simply use key.get_pressed(). Using a bunch of flags is just unnecessary and will clutter up your code.

So your code could simplified to:

while not done: 
    keys = key.get_pressed() 
    if keys[K_DOWN]: 
        print "DOWN" 
    for e in event.get(): 
        pass # proceed other events. 
             # always call event.get() or event.poll() in the main loop

How do you enable holding keys in pygame? : pygame, This allows the user to press and hold the left key and continuously move left, and pygame.mouse.get_pos() to update the list of pressed keys and tuple of� The other way is to use pygame.keys.get_pressed() and pygame.mouse.get_pos() to update the list of pressed keys and tuple of mouse coordinates on each while loop iteration and perform your command after each of these functions with the data they return. the get_pressed() method essentially returns a dictionary where the keys are the pygame


I am not familiar with Pygame, but, as I see, the program in it should have an event-based architecture. Unless you get the incoming events and process them, nothing happens. That's why your simple loop becomes infinite: it just does not process events.

while keys[K_DOWN]: # Nobody updates the keys, no events are processed
    print "DOWN"

Then concerning the get_pressed() call. What it returns is a list of keys. So, you are trying to just loop until the key is released. That's a problem. According to this, pygame.event.get() returns immediately even if there are no events in the queue. The call to get() means: my code still has what to do, but I don't want to block the events, so please process the pending events before I continue. If your code is just waiting for an event, that means it has nothing to do.

The function to WAIT (without blocking the inner loop of Pygame) for an event is pygame.event.wait() (the logic is: I have nothing to do in my code until something happens). However, if you use it, you will have to get information about keys pressed or released from the event itself, not from get_pressed().

Here is an example from the comments to the doc page:

for event in pygame.event.get() :
  if event.type == pygame.KEYDOWN :
    if event.key == pygame.K_SPACE :
      print "Space bar pressed down." #Here you should put you program in the mode associated with the pressed SPACE key
    elif event.key == pygame.K_ESCAPE :
      print "Escape key pressed down."
  elif event.type == pygame.KEYUP :
    if event.key == pygame.K_SPACE :
      print "Space bar released."
    elif event.key == pygame.K_ESCAPE :
      print "Escape key released." #Time to change the mode again

How to efficiently hold a key in Pygame?, 发布时间:2019-02-18 23:49. [EDIT] I've posted the solution down there. [/EDIT]. I' ve found two related questions: Pygame hold key down causes an infinite loop� Lines of code like pressed_keys["left"] = True update the value that matches with the key left in pressed_keys whenever a keypress occurs according to pygame. After I get all of the events that happened in pygame (window closing, mouse movement, keyboard presses, etc.) at that particular instant of time, I now can check the status of my pressed


I like to take a slightly different approach to this problem. Instead of checking if the key is pressed and taking some action when it is, set a flag on key down and unset it on key up. Then in the function to update the player's position, check the flag and update accordingly. The following pseudo-Python explains what I'm getting at:

if down_key_pressed:
    down_flag = True
elif down_key_released:
    down_flag = False
elif right_key_pressed:
    etc...

This should be done in a separate loop that takes the player's input. Then in update_player_position() you can do:

if down_flag:
    move_player_down()
elif right_flag:
    move_player_right()

This example assumes four-directional movement, but you could extend it to eight-directional fairly easily by just using if down_flag and right_flag instead.

pygame key hold down - For Beginners, K_DOWN: box_y += 5 if event.key == pygame.K_UP: box_y How do I make it so that you can hold the button down and it continue to move? I have the ability to move the banshee (I used an image from Halo for my ship) using WASD, but I have to repetitively tap keys, whereas I want to be able to move it by holding down the keys. Here's the code; import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((1440,900)) pygame.display.update() black=(0,0,0


You can get keydown event repeatedly if you use pygame.key.set_repeat(# millisecond) to set the time limitation for each key event. Quote: when the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay is the number of milliseconds before the first repeated pygame.KEYDOWN will be sent. After that another pygame.KEYDOWN will be sent every interval milliseconds. If no arguments are passed the key repeat is disabled. When pygame is initialized the key repeat is disabled. please see following link for detail http://www.pygame.org/docs/ref/key.html#pygame.key.set_repeat

pygame, For this to work properly, you have to set the variable previous_key = pygame.key .get_pressed() before the game loop, otherwise you'll receive a NameError . It's way easier to use pygame.key.get_pressed() to check if a key is held down, since you don't need keep track of the state of the keys yourself with events. I usually create a dictionary that maps keys to the direction they should move the object. This way, it's easy to query the result of pygame.key.get_pressed().


I am using a different approach on holding down a key that I am using in the specific task of moving an object left or right.

I do not care about the computer knowing that a key is actually held down.

When I press a key, a variable that I define for that key (EG: left arrow) is set to True. Until that key is unpressed (with the event pygame.KEYUP) the "movement to left" is performed.

Better Move By Keyboard — Python Arcade Library 2.4.2a1 , This code tracks which key is down or up, and handles it properly. os.chdir( file_path) # Variables that will hold sprite lists self.player_list = None # Set up the � I don't know python or pygame, but assuming you're using a game library there should be a way to poll the state of the key, such as if it's currently down or not instead of if it was pressed since last update.


The following are 30 code examples for showing how to use pygame.QUIT().These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.