You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame动画代码出现None类型不可下标错误求助

问题解决:Object of type "None" is not subscriptable

核心原因

self.images的值为None,当尝试用self.images[self.current_image]进行下标访问时触发报错。导致self.images为None有几个关键问题:

1. load_animation_images函数逻辑错误

你的return images写在了for循环内部,导致循环仅执行一次就直接返回,函数最终只加载了1张图片,且返回的是单个图片对象而非列表。如果后续将这个值存入animations字典,animations.get(sprite_name)拿到的不是预期的图片列表,甚至可能因未正确存入而返回None。

修复后的函数:

def load_animation_images(sprite_name):
    images = []
    path = f"assets/{sprite_name}/{sprite_name}"
    for num in range(1,24):
        image_path = path + str(num) + '.png'
        images.append(pygame.image.load(image_path))
    # 将return移到循环外部,确保加载所有图片后返回完整列表
    return images

2. animations字典未正确初始化填充

在实例化AnimateSprite之前,必须先调用load_animation_images将对应精灵的图片列表存入animations字典,否则animations.get(sprite_name)会返回None。

示例初始化代码:

# 定义可访问的animations字典
animations = {}
# 加载精灵动画图片并存入字典
animations["your_sprite_name"] = load_animation_images("your_sprite_name")
# 再实例化AnimateSprite
sprite = AnimateSprite("your_sprite_name")

3. 防御性检查(可选但推荐)

在animate方法中增加判断,避免self.images为空或None时出错:

def animate(self):
    # 先检查self.images是否有效
    if not self.images:
        return
    self.current_image += 1
    # 用len(self.images)替代固定的24,适配不同帧数量的动画
    if self.current_image >= len(self.images):
        self.current_image = 0
    self.image = self.images[self.current_image]

4. 验证图片路径正确性

确保assets/{sprite_name}/{sprite_name}1.png到assets/{sprite_name}/{sprite_name}23.png这些文件真实存在,文件名和路径无拼写错误。若路径错误,pygame.image.load会抛出异常,导致images列表加载不完整。


内容的提问来源于stack exchange,提问作者le big boss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:32:28