Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

python - pygame.error "couldn't open image.png" only in command prompt

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

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:UsersjulixDocumentsestpygame_tutorial.py
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:UsersjulixDocumentsestpygame_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")

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

Here is an alternative implementation using the wonderful pathlib:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...