Skip to content Skip to sidebar Skip to footer

Sequential Image Presentation In Pygame

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): seque

Solution 1:

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 mainloopwhileTrue:

    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)

Solution 2:

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

ifpicture== "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

Post a Comment for "Sequential Image Presentation In Pygame"