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

查看:120
本文介绍了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:\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

这是我的代码中所指的行:

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天全站免登陆