pythonpgzero

Repeated key detection in PyGame Zero


My pgzero key press event handler does recognize a pressed key only once (until released) but does not support repeated key press events if the key is kept pressed.

How can I achieve this?

PS: Since pgzero is implemented using pygame perhaps a pygame solution could work...

import pgzrun

counter = 1

def on_key_down(key):
    global counter
    if key == keys.SPACE:
        print("Space key pressed...")
        counter = counter + 1

def draw():
    screen.clear()
    screen.draw.text("Space key pressed counter: " + str(counter), (10, 10))

pgzrun.go()

Solution

  • The event is only triggered once, when the key is pressed. You've to use state variable space_pressed which is stated when the key is pressed (in on_key_down()) and reset when the key is released (in on_key_up()). Increment the counter in update(), dependent on the state of the variable space_pressed:

    import pgzrun
    
    counter = 1
    space_pressed = False
    
    def on_key_down(key):
        global space_pressed
        if key == keys.SPACE:
            print("Space key pressed...")
            space_pressed = True
    
    def on_key_up(key):
        global space_pressed
        if key == keys.SPACE:
            print("Space key released...")
            space_pressed = False
    
    def update():
        global counter
        if space_pressed:
            counter = counter + 1
    
    def draw():
        screen.clear()
        screen.draw.text("Space key pressed counter: " + str(counter), (10, 10))
    
    pgzrun.go()