gpt4 book ai didi

python - pygame.error "couldn' t open image.png“仅在命令提示符下

转载 作者:太空宇宙 更新时间:2023-11-03 21:30:35 25 4
gpt4 key购买 nike

我编写了一个非常简单的 python 程序来学习 pygame,除此之外我还使用了图像。

当我使用 PyCharm 运行该程序时,或者当我通过双击文件运行该程序时,它工作正常。但是,如果我尝试通过命令提示符运行它,则会收到以下错误:

C:\Users\julix>C:\Users\julix\Documents\test\pygame_tutorial.py
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\julix\Documents\test\pygame_tutorial.py", line 21, in <module>
carImg = pygame.image.load("racecar.png")
pygame.error: Couldn't open racecar.png

这是我的代码中它引用的行:

carImg = pygame.image.load("racecar.png")

图像“racecar.png”与程序位于完全相同的目录中。令人困惑的部分是我的代码似乎没问题,因为当我双击运行它时没有错误。

如果需要的话可以发布完整的代码。提前致谢

最佳答案

事实上,文件与程序位于同一目录中并不重要。如果您不提供路径,程序将在工作目录中查找该文件,该目录可能完全不同。

如果您想使用特定目录,请将路径添加到文件名中。一种灵活的方法是确定当前文件的路径并使用它。 Python 有一种方法可以做到这一点 os.path.dirname .

import os.path
print(os.path.dirname(__file__))

在这种情况下,它将导致以下代码:

import os.path
filepath = os.path.dirname(__file__)
carImg = pygame.image.load(os.path.join(filepath, "racecar.png"))
<小时/>

这是使用精彩的 pathlib 的替代实现:

import pathlib
filepath = pathlib.Path(__file__).parent
carImg = pygame.image.load(filepath / "racecar.png")

关于python - pygame.error "couldn' t open image.png“仅在命令提示符下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com