How can I load an animated GIF and get all of the individual frames in Pygame?

Solution 1:

Pygame itself does not support animated gifs, which is stated in the documentation. So you'll have to

1) use some other piece of code / library to split the gif when you're loading your sprites or images. Those you would find just by googling for "python split gif" or something. E.g. Python: Converting GIF frames to PNG

2) if you created the gif yourself, just export your sprites again frame by frame

Either way, you'll have to do the animating part by hand. Which for you'll find plenty of tutorials by googling "pygame animation". E.g. Animated sprite from few images

Solution 2:

This code does it using PIL / pillow library.

from PIL import Image

def split_animated_gif(gif_file_path):
    ret = []
    gif = Image.open(gif_file_path)
    for frame_index in range(gif.n_frames):
        gif.seek(frame_index)
        frame_rgba = gif.convert("RGBA")
        pygame_image = pygame.image.fromstring(
            frame_rgba.tobytes(), frame_rgba.size, frame_rgba.mode
        )
        ret.append(pygame_image)
    return ret