Pygame Sprite Sheet: Load, Slice and Animate in Python

· 8 min read · Loopixel team

Code run on pygame 2.6.1 with the SDL dummy driver (no window); all images are that run's output

Four captures of a Pygame scene showing a pixel character in four directions at different animation frames

A sprite sheet is one image with many frames in it. In Pygame you load it once, cut it into surfaces, and show a different surface as time passes. This guide does exactly that with a real Loopixel sheet: load it with transparency, slice 8 frames, slice the four rows of a 4-direction sheet, switch frames at 10 fps without depending on your frame rate, enlarge the pixels without blurring them, and read the frame size from the atlas JSON instead of hard-coding it.

On this page · 9

Load the sheet

The sheet below is the 64 px walk sheet of one Loopixel 4-direction download: sprite_64.png, 512 × 256 px, with 4 rows of 8 frames, and atlas_64.json next to it. If you want to follow along, download the sprite_64.png and the atlas_64.json used here, or use the files from any Loopixel ZIP.

The PNG has real transparency, so use convert_alpha(). It converts the image to the display’s pixel format and keeps the alpha channel, which makes blitting faster. It needs a display mode, so call set_mode first: when we ran it before, Pygame raised No video mode has been set.

Slice the frames

There is no padding, offset, trimming or rotation in a Loopixel sheet, so the frames sit on a perfect grid: the width of the sheet is 8 times the frame size. That makes slicing arithmetic. Surface.subsurface(rect) returns a surface that shares its pixels with the parent, so it costs almost nothing, and you keep one big image in memory.

slice_row: no atlas needed
def slice_row(sheet, row, size=64, count=8):
    """No atlas needed: a Loopixel sheet has no padding, so frame i of row r is at (i * size, r * size)."""
    return [sheet.subsurface(pygame.Rect(i * size, row * size, size, size)) for i in range(count)]

We checked it: the 32 frames cut this way are pixel-identical to the cells of the sheet and to the rectangles in the atlas.

Eight frames of a pixel character with a yellow hoodie, cut from a sprite sheet in Pygame, labelled frames[0] to frames[7] with x offsets 0 to 448
Pygame run output: the 8 front frames cut with subsurface() and redrawn at 2×. Each frame starts 64 px after the previous one.

Four directions, four rows

A 4-direction sheet has 4 rows of 8 frames, in the order front, right, back, left. Ask for a row by index with slice_row(sheet, row), or by name through the atlas as in the next sections. Loopixel’s 4-direction mode makes a walk cycle only; the 4-direction sprite sheet page describes what you get, and a single-direction action is one row.

All 32 frames of a four direction walk sheet rebuilt in Pygame: rows front, right, back and left with 8 frames each
Pygame run output: all 32 frames rebuilt from the atlas names, row by row. The frames equal the original sheet cells.

Animate at 10 fps

Do not advance the frame once per display frame. A monitor at 60 Hz would play your 8 frames in 133 ms, and a slow machine would play them slowly. Count milliseconds instead. Clock.tick(60) limits the loop to 60 frames per second and returns the milliseconds since the previous call; add them up and divide by the frame length.

Animation: frame from elapsed time
class Animation:
    """Pick the frame from elapsed time, so the speed does not depend on the display frame rate."""

    def __init__(self, frames, fps):
        self.frames = frames
        self.frame_ms = 1000 / fps
        self.elapsed = 0

    def update(self, dt_ms):
        self.elapsed += dt_ms

    @property
    def index(self):
        return int(self.elapsed // self.frame_ms) % len(self.frames)

    @property
    def image(self):
        return self.frames[self.index]

At 10 fps each frame lasts 100 ms. Set directly to elapsed times, a fresh animation reported frame 0 at 0 and 99 ms, frame 1 at 100 ms, frame 7 at 799 ms and frame 0 again at 800 ms. The loop is 8 frames, 0.8 seconds, and it wraps because of the modulo.

Enlarge without blur

A 64 px sprite on a 1280×720 window is tiny. Enlarge it, but only with pygame.transform.scale and a whole number. The documentation describes it as a fast scale operation that does not sample the results: each source pixel becomes a square block. smoothscale blends neighbours, which is right for photos and wrong for pixel art.

One pixel character frame enlarged 4 times with Pygame transform.scale on the left, hard pixels, and transform.smoothscale on the right, blurred
Pygame run output: the same 64 px frame enlarged 4×. With scale() every pixel keeps alpha 0 or 255; after smoothscale() we counted 256 different alpha values, which is the soft edge.

Scale each frame once, when you load it, not on every draw. That is what the scale argument of load_frames does below. The same rule is behind the blurry pixel art guide for engines.

Read the atlas JSON

Each Loopixel size ships with an atlas_{size}.jsonin the Aseprite and TexturePacker “array” style. These are the fields in the real atlas_64.json of the sheet used here:

FieldValue in atlas_64.jsonUse
meta.frame_size.w / .h64 / 64Cell size
meta.size.w / .h512 / 256Whole sheet
meta.fps10Playback speed
meta.looptrueLoop the animation
frames[].filenamefront_00 … left_07Frame name: direction, then index
frames[].frame.x / y / w / hfor example x 64, y 0, w 64, h 64Rectangle to cut
frames[].duration100Milliseconds per frame
animationsfront, right, back, left, each a list of 8 namesFrames per direction, in order

The loader below builds a dictionary from direction to a list of surfaces, using exactly these fields. Because the rectangles and fps come from the file, the same loader works for the 32, 48, 96 and 128 px sheets; the scene code below also reads the cell size from meta, so only the file names and the scale change.

load_frames: sheet + atlas in, frames out
import json

import pygame


def load_frames(sheet_path, atlas_path, scale=1):
    """Return ({direction: [Surface x 8]}, meta). Frame rectangles come from the atlas JSON."""
    sheet = pygame.image.load(sheet_path).convert_alpha()
    with open(atlas_path) as f:
        atlas = json.load(f)
    by_name = {}
    for fr in atlas["frames"]:
        r = fr["frame"]
        frame = sheet.subsurface(pygame.Rect(r["x"], r["y"], r["w"], r["h"]))
        if scale != 1:
            # transform.scale is nearest-neighbour: hard pixel edges stay hard
            frame = pygame.transform.scale(frame, (r["w"] * scale, r["h"] * scale))
        by_name[fr["filename"]] = frame
    frames = {d: [by_name[n] for n in names] for d, names in atlas["animations"].items()}
    return frames, atlas["meta"]

The full script and its output

Put sprite_64.png, atlas_64.json and the script in one folder. main(size, scale)builds the file names from the size. The default shows the four directions at 2×, each with its own animation, and closes on the window’s close button. The window is 640 × 360, so for the 96 and 128 px sheets call main(96, 1) or main(128, 1), or make the window bigger.

draw_scene and the main loop
def draw_scene(screen, anims, font, cell):
    screen.fill((20, 20, 18))
    gap = (screen.get_width() - 4 * cell) // 5
    for i, (name, anim) in enumerate(anims.items()):
        x = gap + i * (cell + gap)
        y = (screen.get_height() - cell) // 2
        screen.blit(anim.image, (x, y))
        label = font.render(f"{name}  frame {anim.index}", True, (200, 200, 190))
        screen.blit(label, (x, y + cell + 10))


def main(size=64, scale=2):
    """size = 32, 48, 64, 96 or 128. The window is 640 x 360, so use scale=1 for 96 and 128 px."""
    pygame.init()
    screen = pygame.display.set_mode((640, 360))
    clock = pygame.time.Clock()
    font = pygame.font.Font(None, 22)
    frames, meta = load_frames(f"sprite_{size}.png", f"atlas_{size}.json", scale)
    cell = meta["frame_size"]["w"] * scale  # on-screen size of one frame
    anims = {d: Animation(fr, meta["fps"]) for d, fr in frames.items()}

    running = True
    while running:
        dt = clock.tick(60)  # milliseconds since the last tick, capped at 60 fps
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        for anim in anims.values():
            anim.update(dt)
        draw_scene(screen, anims, font, cell)
        pygame.display.flip()
    pygame.quit()


if __name__ == "__main__":
    main()

We did not open a window to test it. With SDL_VIDEODRIVER=dummy and SDL_AUDIODRIVER=dummy Pygame draws to an offscreen surface, so the loop ran for 1.5 seconds and exited on a posted quit event, and we saved the screen at a few moments. Pygame wrote these four captures (the simulated clock steps by 16 or 17 ms, about 60 fps):

Four captures of a Pygame scene with the same character shown in four directions at different moments, labelled with the animation frame of each direction
Pygame run output (dummy video driver, no window): the same scene at 0, 262, 507 and 752 ms of a simulated 60 fps clock. The label under each character is the frame the Animation class chose.

Where a frame boundary falls between two display frames, the new frame appears on the next one, so the first time we saw frame 1 was at 115 ms, not 100. That is the 60 fps granularity, not drift: the index comes from the total elapsed time.

  1. Install Pygame with pip install pygame. We used pygame 2.6.1 on Python 3.11.
  2. Save the script above as loopixel_sheet.py next to the two Loopixel files and run python loopixel_sheet.py.
  3. To try another size, change the call at the bottom to main(128, 1) (sheet and atlas of that size in the folder). If you use slice_row, pass the size as well. We ran the scene offscreen for 32, 48, 64 (2×) and 96, 128 (1×): all four characters stay inside the window and the labels do not overlap. 128 px at 2× is 256 px per character and does not fit.

Common mistakes

  • convert_alpha before set_mode. Raises No video mode has been set in our run. Create the window first.
  • Using convert() instead of convert_alpha(). The transparent background turns into a solid color.
  • Counting display frames. The animation speed then follows the frame rate of the machine.
  • Hard-coding 64. It breaks as soon as you try the 48 or 96 px sheet. Read meta.frame_size, as main() does.
  • Non-integer or smooth scaling. Use transform.scale with a whole number. If your own cut is off by a pixel, see the slicing guide.
  • Scaling every frame, every frame. Scale once at load time.

Quick answers

Do I need the atlas JSON?

No. Loopixel sheets have no padding, so slice_row works from the frame size alone. The atlas just saves you from hard-coding the frame size, the speed and the direction order.

I only have a GIF. Can I use it in Pygame?

Convert it to a sheet first with the free GIF to sprite sheet tool, then slice that. The other direction is sprite sheet to GIF.

Does this work with pygame-ce?

We only ran pygame 2.6.1, so we cannot say. The calls used here are basic Surface and transform functions.

Sources

Engine menu paths and property names above were checked against the official documentation:

Try it with one image

Upload one image and get an 8-frame pixel sprite sheet in about a minute. 1 credit per animation, credit packs from $2.99, paid once.

Create a sprite sheet