您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-错误:无法打开.png文件

Python-错误:无法打开.png文件

使用相对路径(这样做总是更好):

import os

current_path = os.path.dirname(__file__) # Where your .py file is located
resource_path = os.path.join(current_path, 'resources') # The resource folder path
image_path = os.path.join(resource_path, 'images') # The image folder path

这样,无论您将包含.py文件文件夹移动到何处,都可以访问其子目录(以及因此包含的所有子目录),而无需修改代码

最终代码

import pygame
import os
from pygame.locals import *


pygame.init()

width, height = 640, 480
screen = pygame.display.set_mode((width, height))

current_path = os.path.dirname(__file__) # Where your .py file is located
resource_path = os.path.join(current_path, 'resources') # The resource folder path
image_path = os.path.join(resource_path, 'images') # The image folder path

player_image = pygame.image.load(os.path.join(image_path, 'dude.png'))

while 1:

    screen.fill(0)

    screen.blit(player, (100,100))

    pygame.display.flip()

    for event in pygame.event.get():


        if event.type==pygame.QUIT:
            pygame.quit()
            exit(0)

对所有其他文件使用此访问方法,将避免很多问题。

python 2022/1/1 18:37:01 有236人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶