Sequential image presentation in Pygame

Question:

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)
Asked By: Donkey

||

Answers:

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

Answered By: OpenGLmaster1992

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

# All images in 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 currently displayed image
current_image = 0


# Main game loop

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
    
    # Display (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 the image correctly you need image_rect, like so:

# Get image_rect
image_rect = images[current_image].get_rect()

# Center the image_rect on the screen
image_rect.center = screen_rect.center

# Draw (blit) the image using 'image_rect'
screen.blit(images[current_image], image_rect)
Answered By: furas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.