You need to enable JavaScript to run this app. Pygame加载动画资源提示找不到目录FileNotFoundError问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Pygame加载动画资源提示找不到目录FileNotFoundError问题求助

问题排查与修复方案

核心问题点和对应解决方法如下:

  • 命名规则不匹配
    你的代码默认待加载的图片命名为0.png、1.png…n-1.png,但实际文件夹内的图片大概率不符合这个命名规则:比如序号从1开始计数、文件名带Idle前缀(如Idle_0.png)、后缀大小写错误(如.PNG而非.png)都会触发找不到文件的报错。
  • 计数逻辑错误
    你直接用os.listdir()返回的文件数量作为总帧数,该方法会把系统隐藏文件(比如Mac系统的.DS_Store、Windows的Thumbs.db)也计入总数,导致循环次数超过实际存在的图片数量,最终加载不存在的序号文件报错。
  • 路径兼容性问题
    直接用字符串拼接路径在不同操作系统可能出现分隔符不匹配的问题,同时要确认self.char_type的值和对应文件夹的命名大小写完全一致,Linux、Mac系统对路径大小写敏感。

修复后可直接使用的代码

import os
import pygame

animation_types = ['Idle', 'Run', 'Jump']
for animation in animation_types:
    temp_list = []
    # 只筛选目录下后缀为png的文件,排除隐藏文件
    frame_files = [f for f in os.listdir(f'Assets/{self.char_type}/{animation}') 
                  if f.lower().endswith('.png')]
    # 按文件名中的数字排序,保证动画帧顺序正确
    frame_files.sort(key=lambda x: int(os.path.splitext(x)[0]))
    # 直接遍历实际存在的png文件,不用依赖序号命名
    for frame_file in frame_files:
        # 用os.path.join拼接路径适配不同操作系统
        img_path = os.path.join('Assets', self.char_type, animation, frame_file)
        img = pygame.image.load(img_path).convert_alpha() # 加convert_alpha提升渲染效率
        img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))
        temp_list.append(img)
    self.animation_list.append(temp_list)

上述代码自动过滤了非png格式的无效文件,适配从0或1开始的序号命名规则,同时解决了不同操作系统的路径分隔符兼容问题。

内容的提问来源于stack exchange,提问作者James Thompstone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:48:02