2

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!!

1
  • do you ever refresh the display if button_pressed is false? Commented Sep 13, 2013 at 14:04

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.