Question

i want to show an image as long as i hold a key pressed. If the key isn't pressed (KEYUP) anymore, the image should disappear.

In my code the image appears when i hold the key down, but i does not disappears right away. Anyone knows why the image does not stay visible as long as I hold my key pressed=?

button_pressed = False
for event in pygame.event.get():
    if event.type == KEYDOWN:               
        if event.key == K_UP:
            button_pressed = True
            print"True"

    if event.type == KEYUP:
        if event.key == K_UP:
            button_pressed = False

if button_pressed:
    DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))

Thanks in advance!!

Was it helpful?

Solution

Once you blittet your image to the screen, it will stay there until you draw something over it. It won't disappear by itself.

An easy solution is to just clear the screen every iteration of your main loop, e.g. something like:

while running:
    DISPLAYSURF.fill((0, 0, 0)) # fill screen black

    for event in pygame.event.get():
        # handle events
        pass

    # I'm using 'key.get_pressed' here because using the KEYDOWN/KEYUP event
    # and a variable to track if a key is pressed totally sucks and people 
    # should stop doing this :-)
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_UP]:
        # only draw image if K_UP is pressed.
        DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))

    pygame.display.flip()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top