我的代码中有一个小问题。我有以下代码:
import os,pygame
class npc:
ntype = 0
image = None
x = 0
y = 0
text = ""
name = ""
def Draw(self,screen):
screen.blit(self.image, [self.x*32,self.y*32])
def __init__(self,name,nx,ny):
f = open(name)
z = 0
for line in f:
if z == 0:
name = line
if z == 1:
ntype = line
if z == 2:
text = line
if z == 3:
self.image = pygame.image.load(os.path.join('img', line))
self.x = nx
self.y = ny
z=z+1
我正在加载的文件格式如下:
The Shadow
0
Hello. I am evil.
shadow.png
最后一行有问题。当我尝试使用 pygame.image.load 加载该 png 时,我收到一条错误消息,指出它无法加载该图像。但是,如果我将 pygame 加载代码更改为 self.image = pygame.image.load(os.path.join('img', "shadow.png"))
,它会完美运行。我已经多次查看文件,但找不到导致此错误的任何原因。有人能看出我做错了什么吗?
回溯:
Traceback (most recent call last):
File "./main.py", line 26, in <module>
rmap = g.Load_Map("l1.txt",char)
File "/home/josiah/python/rpg/generate.py", line 31, in Load_Map
npcs.append(npc.npc(str.split(bx,',')[1],x,y))
File "/home/josiah/python/rpg/npc.py", line 23, in __init__
self.image = pygame.image.load(os.path.join('img', line))
pygame.error: Couldn't open img/shadow.png
最佳答案
您可能有一个尾随换行符。尝试剥离线:
self.image = pygame.image.load(os.path.join('img', line.strip()))
更好的是,以不同的方式加载文件。除了循环,您还可以这样做(假设每个文件的格式相同,并且行数至少相同):
name, ntype, text, filename = [l.strip() for l in open(name).readlines()[:4]]
# Now use the variables normally, for example:
self.image = pygame.image.load(os.path.join('img', filename))
关于python - 奇怪的pygame图像错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328290/