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

Pygame报错‘找不到imgs/player/Idle/2.png’的解决求助

解决方案

1. 排查文件命名与目录内容

  • 手动打开路径 /Users/admin/python1/Pygame/imgs/player/Idle,确认:
    • 存在2.png文件,文件名无拼写错误、空格或大小写差异(比如别写成2.PNG或 idle/);
    • 目录内没有系统隐藏文件(如Mac的.DS_Store)或非图片文件,这类文件会被os.listdir计入总数,导致循环读取不存在的图片编号。

2. 替换文件遍历逻辑(推荐)

原代码用os.listdir获取文件数的方式不可靠,改用glob模块精准遍历PNG文件,避免无效计数:

import glob  # 记得导入glob模块

class soldier(pygame.sprite.Sprite):
    def __init__(self, char_type, x, y, scale, speed):
        pygame.sprite.Sprite.__init__(self)
        self.alive = True
        self.char_type = char_type
        self.speed = speed
        self.direction = 1
        self.vel_y = 0
        self.flip = False
        self.jump = False
        self.animation_list = []
        self.frame_index = 0
        self.action = 0
        self.update_time = pygame.time.get_ticks()

        animation_types = ["Idle", "run", "jump"]
    
        for animation in animation_types:
            temp_list = []
            # 获取当前动画目录下所有PNG文件,按文件名排序
            img_paths = sorted(glob.glob(f"imgs/{self.char_type}/{animation}/*.png"))
            for path in img_paths:
                img = pygame.image.load(path)
                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)
    
        self.image = self.animation_list[self.action][self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

3. 验证路径正确性

在代码中添加路径打印,确认实际访问的路径与本地文件系统一致:

import os
print("当前工作目录:", os.getcwd())  # 打印当前工作目录

# 在加载图片的循环内添加
print(f"尝试加载路径: imgs/{self.char_type}/{animation}/{i}.png")

对比打印的路径,检查是否存在拼写错误(比如player写成players,Idle写成idle)。

4. 检查文件权限

如果文件存在但仍无法读取,检查文件权限:
打开终端执行:

ls -l /Users/admin/python1/Pygame/imgs/player/Idle/2.png

查看权限列是否包含r(读权限),若无则执行:

chmod +r /Users/admin/python1/Pygame/imgs/player/Idle/2.png

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:14:56