Telarius Chromack
Telarius Chromack

Reputation: 77

Moving forward and backward between images files

Trying to make a simple image gallery where I can flip through a group of images I got far enough to load each image by a single keystroke. how can I tell python to flip through a group of images with arrows as in an image gallery

import pygame

# --- constants --- (UPPER_CASE)

WIDTH = 1366
HEIGHT = 768

# --- main ---

# - init -

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), 
pygame.NOFRAME)
pygame.display.set_caption('Katso')

# - objects -   

penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()

x = 0 # x coordnate of image
y = 0 # y coordinate of image

# - mainloop - 

running = True

while running: # loop listening for end of game
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                #screen.fill( (0, 0, 0) )
                screen.blit(mickey,(x,y))
                pygame.display.update()
            elif event.key == pygame.K_RIGHT:
                #screen.fill( (0, 0, 0) )
                screen.blit(penguin,(x,y))
                pygame.display.update()

# - end -

pygame.quit()

Upvotes: 1

Views: 254

Answers (1)

skrx
skrx

Reputation: 20438

Put the images into a list and then just increment an index variable, use it to get the next image in the list and assign it to a variable (image) which you blit each frame.

import pygame


WIDTH = 1366
HEIGHT = 768

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
clock = pygame.time.Clock()  # Needed to limit the frame rate.
pygame.display.set_caption('Katso')
# Put the images into a list.
images = [
    pygame.image.load('download.png').convert(),
    pygame.image.load('mickey.jpg').convert(),
    ]
image_index = 0
image = images[image_index]  # The current image.

x = 0  # x coordnate of image
y = 0  # y coordinate of image

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                image_index -= 1  # Decrement the index.
            elif event.key == pygame.K_RIGHT:
                image_index += 1  # Increment the index.

            # Keep the index in the valid range.
            image_index %= len(images)
            # Switch the image.
            image = images[image_index]

    screen.fill((30, 30, 30))
    # Blit the current image.
    screen.blit(image, (x, y))

    pygame.display.update()
    clock.tick(30)  # Limit the frame rate to 30 fps.

pygame.quit()

Upvotes: 1

Related Questions