如何解决Pygame找不到图片
我的问题是pygame无法找到我的图片(bg.png)
class Background(pygame.sprite.Sprite):
def __init__(self,image_file,location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left,self.rect.top = location
BackGround = Background ('bg.PNG',[0,0] )
解决方法
图像文件路径必须相对于当前工作目录。工作目录可能与python文件的目录不同。
文件名和路径可以通过__file__
获取。当前工作目录可以通过os.getcwd()
获取,也可以通过os.chdir(path)
进行更改。
一种解决方案是更改工作目录:
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
另一种解决方案是找到绝对路径。 如果图像相对于python文件的文件夹(甚至在同一文件夹中),则可以获取文件目录并连接图像文件名。例如:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
class Background(pygame.sprite.Sprite):
def __init__(self,image_file,location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
imgPath = os.path.join(sourceFileDir,image_file)
self.image = pygame.image.load(imgPath)
# [...]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。