문제

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

도움이 되었습니까?

해결책

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()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top