Sequential image presentation in Pygame

2019-08-11 03:47发布

A simple problem, but i am new to Python/Pygame. I want to blit an image (old.png) and then have that image be replaced by another image (new.png) upon a keypress (spacebar): sequential presentation. Currently, the old.png remains on the surface, with new.png ending up on top of it.

Here is my code:

for event in pygame.event.get():   
    if event.type == pygame.QUIT:
        pygame.quit()
        quit()

    screen.blit(old, (display_width/2, display_height/2))
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
           screen.blit(new, (display_width/2, display_height/2))

pygame.display.flip()
clock.tick(30)

标签: python pygame
2条回答
趁早两清
2楼-- · 2019-08-11 04:15

You could for example make a variable: picture = "old" , and when spacebar is pressed you could do something like:

if picture == "old":
    picture = "new"
    screen.blit(new, (display_width/2, display_height/2))
else:
    picture = "old"
    screen.blit(old, (display_width/2, display_height/2))

So everytime spacebar is pressed the picture switches

查看更多
Lonely孤独者°
3楼-- · 2019-08-11 04:23

You can keep images on list and use index current_image to select image to display. This way you can have more than 2 images.

# all images on list

images = []

images.append(old)
images.append(new)
images.append(another_image)
#images.append(another_image_2)
#images.append(another_image_3)

# how many images we have ?
images_number = len(image)

# index of current displayed image
current_image = 0


# in mainloop

while True:

    for event in pygame.event.get():   
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:

                # get next index (if it is bigger than `images_number` then get `0`) 
                current_image = (current_image + 1) % images_number

    # clear screen
    screen.fill((0,,0)) # black

    # blit current image
    screen.blit(images[current_image], (display_width/2, display_height/2))


    pygame.display.flip()
    clock.tick(30)

--

BTW: you can use

screen_rect = screen.get_rect() 

and then you can use

screen_rect.center

instead of

(display_width/2, display_height/2)

in

screen.blit(images[current_image], screen_rect.center)

but if you want to center image correctly you need image rect

# get image rect
image_rect = images[current_image].get_rect()

# center image rect on the screen
image_rect.center = screen_rect.center

# draw image using `image_rect`
screen.blit(images[current_image], image_rect)
查看更多
登录 后发表回答