pygame.error“无法打开image.png";仅在命令提示符下 [英] pygame.error "couldn't open image.png" only in command prompt

查看:34
本文介绍了pygame.error“无法打开image.png";仅在命令提示符下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a very simple python program I wrote to learn pygame, and among other things I use an image.

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

When I run the program with PyCharm, or when I run it by double-clicking on the file, it works fine. However, if I try to run it through the command prompt, I get the following error:

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

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

This is the line in my code it refers to:

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

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

The image "racecar.png" is located in exactly the same directory as the program. The confusing part is that my code seems to be fine since there are no errors when I run it by double-clicking.

如有必要,可以发布完整代码.提前致谢

Can post full code if necessary. Thanks in advance

推荐答案

文件与程序在同一目录中这一事实无关紧要.如果您不提供路径,程序将在工作目录中查找可能完全不同的文件.

The fact, that the file is in the same directory as the program doesn't matter. If you don't provide a path the program will look for the file in the working directory which might be a total different one.

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

If you want to use a specific directory add your path to the filename. A flexible approach would be to determine the path of the current file and use that. Python has a way to do that with os.path.dirname.

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

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

In this case it would lead to the following code:

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")

这篇关于pygame.error“无法打开image.png";仅在命令提示符下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆