Skip to main content

A 2D simple animation module for pygame.

Project description

Animation 2D Frame Animation Library

A lightweight 2D sprite frame animation library developed based on Pygame. It is concise and easy to use, enabling quick implementation of character animation playback. Equipped with a camera function. Comes with a real-time online frame animation editor. It also has a built-in help function; call the animation_help() function to get assistance.

Features

  • Load sequence frame images
  • Customizable animation playback speed
  • Support alias management for multiple sets of animations
  • Automatic loop playback
  • Built-in help() function
  • AnimationSprite parent class
  • Smooth movement
  • Reverse playback
  • Get the status of the animation
  • Camera control. Only classes that inherit from AnimationSprite will be associated with the Camera.
  • Added: Real-time online frame animation editor.
  • Added: method folder, used to store practical methods.

Install Dependencies

pip install pygame

Quick Start

import pygame
from Animation import Animation, AnimationSprite

# Sprite class (ensures correct initialization)
class Player(pygame.sprite.Sprite, AnimationSprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        AnimationSprite.__init__(self)

        # Sprite image
        self.image = pygame.Surface((50, 50))
        self.image.fill((0, 255, 0))
        self.rect = self.image.get_rect(center=(x, y))

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

Animation.add_file_path(r"D:\image\player_walk_1.png", "player_walk")

# Create sprite
player = Player(400, 300)
group = pygame.sprite.Group()
group.add(player)

# Start moving automatically on run
player.move_to_position_in(100, 100, 150)

# Main loop
running = True
while running:
    # 1. Clear screen
    screen.fill((0, 0, 0))

    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 2. Update animation (must be called before draw)
    player.update_animation()

    # 3. Draw elements
    group.draw(screen)

    Animation.image_show("player_walk", 200, 300, screen)

    Animation.animation_start("player_walk", 4)

    # 4. Refresh screen (final step)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Function Description (Key Partial Functions)

add_file_path

Register animation file path and alias

def add_file_path(file_path: str, alias: str, wait: int)

image_show

Display the current animation frame at a specified position on the window

def image_show(alias: str, x: int, y: int, window: pygame.Surface)

animation_start

Drive automatic frame switching for animation, and call the callback function when the animation ends

def animation_start(alias: str, count: int, callback : Optional[Callable[[], None]] = None, add_underline: bool = True, file_type: str = "png")

animation_stop

Stop animation playback

def animation_stop(alias : str)

set_animation_frame

Set the current animation frame

def set_animation_frame(alias : str, frame : int = 1)

set_animation_speed

Set the animation playback speed

def set_animation_speed(alias : str, speed : int = 2)

animation_reverse

Reverse animation playback

def animation_reverse(alias : str)

animation_reverse_back

Restore animation playback

def animation_reverse_back(alias : str)

AnimationSprite

This class is a parent class provided by the 2D-Animation-lib. Only by inheriting this class can an object be controlled by the camera.

AnimationStatus

This class is used to get the status of the animation.
For example:
    Animation.AnimationStatus("player_walk").get_settings() # Returns the animation settings in json format
    Animation.AnimationStauts("player_walk").get_status("")
				          ↑
    In this case, you can fill in:
        "animation_started", 
        "image_showing", 
        "animation_start", 
        "animation_end", 
        "animation_reverse"
    These status information.

Parameters:
    alias: alias

Raises:
    NotFoundAliasError - alias not found.

Camera

This module is used to control the display portion of the window.

Functions

set_screen_center
def set_screen_center(x: int, y: int)

This function must be called in the main program. It is used to set the center position of the window. If your window is named screen, simply copy the following code (requires importing pygame):

set_screen_center(screen.get_width()/2, screen.get_height()/2)
get_screen_center
get_screen_center(string: str = "x")

This function retrieves the center coordinates of the window, but only after set_screen_center() has been called.

set_minimum
set_minimum(minimum: float)

Sets the minimum camera zoom level.
The default value is 0.00000000000001, i.e., 1e-16.
The smaller this value, the smaller the maximum camera zoom.
Do not set it lower than this value; this value is optimal. Please do not change it unless absolutely necessary.

set_return_change
set_return_change(self, value: bool)

Sets whether to return the current value. This only applies to functions whose names begin with Camera.
The value is returned, not printed.

move
move(self, x: int, y: int)

Moves the camera.

set_position
set_position(self, x: int, y: int)

Sets the camera's coordinates.

get_position
get_position(self)

Gets the camera's coordinates.

add_size
add_size(self, size: int)

Increases the distance between the camera and the ground.

set_size
set_size(self, size: int)

Sets the distance between the camera and the ground.

get_size
get_size(self)

Gets the distance between the camera and the ground.

turn_left
turn_left(self, angle: int)

Rotates the camera to the left.

turn_right
turn_right(self, angle: int)

Rotates the camera to the right.

set_direction
set_direction(self, angle: int)

Sets the camera's direction.

get_direction
get_direction(self)

Gets the camera's direction.

- def get_status(status : Literal["animation_started", 
                                          "image_showing", 
                                          "animation_start", 
                                          "animation_end", 
                                          "animation_reverse"])

Real-time Online Frame Animation Editor

method folder

This folder is used to store practical methods.

line_coll

from method.line_coll import Line

line = Line(x1, y1, x2, y2)

This creates a line segment object that supports various operations.

image_scrolling

WINDOW_WIDTH, WINDOW_HEIGHT = screen.get_size()
# Settings: Display area at the bottom right corner
grid_width = 320  # Width
grid_height = 500  # Height
# Position: Bottom right corner with margins reserved
margin = 20
grid_x = WINDOW_WIDTH - grid_width - margin
grid_y = WINDOW_HEIGHT - grid_height - margin - 15
# Create a grid (display in 2 columns)
grid = image_scrolling.InfiniteImageGrid(
    x=grid_x, 
    y=grid_y, 
    width=grid_width, 
    height=grid_height,
    columns=2,          # 2 columns
    thumbnail_size=130, # Thumbnail size
    spacing=12          # Spacing
)

This creates an infinitely scrollable grid for displaying images.

Exception Types

  • NotFoundFileError: File does not exist
  • UnboundWindowError: Window not bound
  • ImageNotShowError: Image not displayed
  • NotFoundAliasError: Animation alias not found
  • ValueError: Thrown when input data is invalid
  • TypeError: Type mismatch error

Notice

  • Further updates may be released later, suggestions are welcome

  • QQ Email: watermeloncode@foxmail.com

  • [1.4.0] 2026.5.30

    • Non-destructive changes
    • Added the online animation editor of AnimationEngine
    • Added the method folder to store various utility functions.
  • [1.3.0] 2026.5.10

    • Non-destructive changes
    • Added Camera module
    • Only classes that inherit from AnimationSprite will be controlled by the camera
    • Added practical example: 'run-Animation-example-camera' to run the camera example
  • [1.1.0] 2025.5.3

    • Base class available: classes can inherit AnimationSprite
    • Added smooth movement feature
    • Added reverse playback feature
    • Added get the status of the animation
    • Added example: 'run-Animation-example' to execute example
  • [1.0.0] 2026.5.2

Author

WatermelonJuiceCode Bilibili: WatermelonJuiceCode WeChat: WatermelonJuiceCode QQ: 3931840613

Animation 2D 帧动画库

基于 Pygame 开发的轻量级 2D 序列帧动画库,简洁易用,快速实现角色动画播放。拥有摄像机功能。拥有实时在线帧动画编辑器。 以及拥有内置的寻求帮助,使用 animation_help() 函数去寻求帮助。

功能

  • 加载序列帧图片
  • 自定义动画播放速度
  • 支持别名管理多组动画
  • 自动循环播放
  • 内置 help() 函数
  • AnimationSprite 父类
  • 平滑移动
  • 倒序播放动画
  • 可获取动画的当前状态
  • Camera 摄像机操控。仅对是以 AnimationSprite 继承的类才会与 Camera 产生关联
  • 新增:实时在线帧动画编辑器(注:此编辑器不包含在包内,需额外下载 exe 可运行程序)
  • 新增:method 文件夹,用于存放一些实用方法。

安装依赖

pip install pygame

快速使用

import pygame
from Animation import Animation, AnimationSprite

# 精灵类(保证初始化正确)
class Player(pygame.sprite.Sprite, Animation.AnimationSprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        Animation.AnimationSprite.__init__(self)

        # 精灵图片
        self.image = pygame.Surface((50, 50))
        self.image.fill((0, 255, 0))
        self.rect = self.image.get_rect(center=(x, y))

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

Animation.add_file_path(r"D:\image\player_walk_1.png", "player_walk")

# 创建精灵
player = Player(400, 300)
group = pygame.sprite.Group()
group.add(player)

# 一运行就自动开始移动
player.move_to_position_in(100, 100, 150)

# 主循环
running = True
while running:
    # 1. 清屏
    screen.fill((0, 0, 0))

    # 事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 2. 更新动画(必须写在 draw 前面)
    player.update_animation()

    # 3. 绘制
    group.draw(screen)

    Animation.image_show("player_walk", 200, 300, screen)

    Animation.animation_start("player_walk", 4)

    # 4. 刷新屏幕(最后一步)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

函数说明

add_file_path

注册动画文件路径与别名

def add_file_path(file_path: str, alias: str, wait: int)

image_show

在窗口指定位置显示当前动画帧

def image_show(alias: str, x: int, y: int, window: pygame.Surface)

animation_start

驱动动画自动切换帧,与动画结束后调用 callback 回调函数

def animation_start(alias: str, count: int, callback : Optional[Callable[[], None]] = None, add_underline: bool = True, file_type: str = "png")

animation_stop

停止动画播放

def animation_stop(alias : str)

set_animation_frame

设置动画当前帧

def set_animation_frame(alias : str, frame : int = 1)

set_animation_speed

设置动画播放速度

def set_animation_speed(alias : str, speed : int = 2)

animation_reverse

反转动画播放

def animation_reverse(alias : str)

animation_reverse_back

恢复动画播放

def animation_reverse_back(alias : str)

AnimationSprite

这个类是 2D-Animation-lib 提供的父类,只有继承这个类才能被摄像机操控

AnimationStatus

这个类用于获取动画的状态。 例如: Animation.AnimationStatus("player_walk").get_settings() # 返回json格式的动画设置 Animation.AnimationStauts("player_walk").get_status("") ↑ 在这里可以填: "animation_started", "image_showing", "animation_start", "animation_end", "animation_reverse" 这些状态信息。

    参数:
        alias: 别名

    引发:
        NotFoundAliasError - 别名不存在。

Camera

这个用于控制窗口的显示部分

函数

set_screen_center
def set_screen_center(x : int, y : int)

这个函数在主程序中必须要写,用于设置该窗口的中心位置。假如你的窗口是 screen 的,那么直接复制一下代码即可(需要导入 pygame)

set_screen_center(screen.get_width()/2, screen.get_height()/2)
get_screen_center
get_screen_center(string : str = "x")

这个函数是获取窗口的中心坐标,但前提是已经设置 set_screen_center(string : str = "x") 了

set_minimum
set_minimum(minimum : float)

设置最小摄像机缩放。 默认是 0.00000000000001,也就是 1e-16。 这个值越小,摄像机的最大缩放就越小。 但不要小过这个值,这个值是最佳的,如果不是必须,请别碰它。

set_return_change
set_return_change(self, value : bool)

设置是否返回当前的值,仅限以 Camera 开头的函数。 是返回,不是打印(print)。

move
move(self, x : int, y : int)

移动摄像机

set_position
set_position(self, x : int, y : int)

设置摄像机的坐标

get_position
get_position(self)

获取摄像机的坐标。

add_size
add_size(self, size : int)

增加摄像机与地面的距离。

set_size
set_size(self, size : int)

设置摄像机与地面的距离。

get_size
get_size(self)

获取摄像机与地面的距离

turn_left
turn_left(self, angle : int)

向左转摄像机

turn_right
turn_right(self, angle : int)

向右转摄像机

set_direction
set_direction(self, angle : int)

设置摄像机的方向。

get_direction
get_direction(self)

获取摄像机的方向

这个函数返回的是一个json格式的字符串,包含了动画的大部分信息。

- def get_status(status : Literal["animation_started", 
                                          "image_showing", 
                                          "animation_start", 
                                          "animation_end", 
                                          "animation_reverse"])

这个函数返回的是当前动画的一些状态信息。 比如: animation_started -> bool image_showing -> bool animation_start -> bool animation_end -> bool animation_reverse -> bool

获取实时在线帧动画编辑器

QQ获取:

method 文件夹

这个文件夹用于存放一些实用方法。

line_coll

from method.line_coll import Line

line = Line(x1, y1, x2, y2)

这样就可以创建一个线段对象,可以进行很多操作。

image_scrolling

WINDOW_WIDTH, WINDOW_HEIGHT = screen.get_size()
# 设置:显示区域在右下角
grid_width = 320  # 宽度
grid_height = 500  # 高度
# 位置:右下角,留出边距
margin = 20
grid_x = WINDOW_WIDTH - grid_width - margin
grid_y = WINDOW_HEIGHT - grid_height - margin - 15
# 创建网格(2列显示)
grid = image_scrolling.InfiniteImageGrid(
    x=grid_x, 
    y=grid_y, 
    width=grid_width, 
    height=grid_height,
    columns=2,          # 2列
    thumbnail_size=130, # 缩略图大小
    spacing=12          # 间距
)

这样就可以创建一个无限滚动的网格,可以显示图片。

异常类型

  • NotFoundFileError: 文件不存在
  • UnboundWindowError:未绑定窗口
  • ImageNotShowError: 图片未显示
  • NotFoundAliasError:未找到动画别名
  • ValueError: 填写的数据不符合事实时抛出
  • TypeError: 类型错误

消息

  • 后续可能会继续更新,欢迎提出建议

  • QQ邮箱:watermeloncode@foxmail.com

  • [1.4.0] 2026.5.30(第四个版本)

    • 无破坏性变更
    • 新增 AnimationEngine 在线动画编辑器
    • 新增 method 文件夹,用于存放一些实用方法。
  • [1.3.0] 2026.5.10 (第三个版本)

    • 无破坏性变更
    • 新增 Camera 摄像机模块
    • 只有继承 AnimationSprite 的类才会被摄像机操控
    • 新增实示例:'run-Animation-example-camera' 来执行摄像机示例
  • [1.2.0] 2026.5.3 (第二个版本)

    • 基类,class可继承 AnimtionSprite
    • 新增平滑移动
    • 新增倒序播放动画
    • 新增获取动画状态
    • 使用示例:'run-Animation-example' 来执行示例
  • [1.0.0] 2026.5.2 (第一个版本)

作者

西瓜汁Code B站:西瓜汁Code 微信:WatermelonJuiceCode QQ:3931840613

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

2d_animation_lib-1.5.0.tar.gz (10.8 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

2d_animation_lib-1.5.0-py3-none-any.whl (10.8 MB view details)

Uploaded Python 3

File details

Details for the file 2d_animation_lib-1.5.0.tar.gz.

File metadata

  • Download URL: 2d_animation_lib-1.5.0.tar.gz
  • Upload date:
  • Size: 10.8 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.4

File hashes

Hashes for 2d_animation_lib-1.5.0.tar.gz
Algorithm Hash digest
SHA256 3bb4407dff9eac049abc83ff171d09118bb9b04b2f2bb60aa20aa89b4625463c
MD5 327f9a2a9dce8a54c139cdc81475fab7
BLAKE2b-256 b7a87d411ebd6863c2f70d2ee215e9f958645cee606fcbd0e0ca61562b9b636a

See more details on using hashes here.

File details

Details for the file 2d_animation_lib-1.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for 2d_animation_lib-1.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9bd310175f5fe7bc2062f9731c9bb97a5dfc6a60243dad331c859cba615b3bfc
MD5 0a217b46a2381f237f024b3e3679a972
BLAKE2b-256 3d4eb11da16e684ba877f2e20647acb7a3a6cdb8b5a07cadba06c6c5aa021328

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page