问题
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:\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")
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
回答1:
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"))
回答2:
I would suggest an easy solution, I got stuck at the same stage. I was coding in VS Code and later realized that the terminal is currently executing code from parent directory. So to import image I just need to get the terminal into my current working directory and then run the program again. Images were load fine without any error.
Just make sure in the terminal you are executing code from the same working directory as the project folder.
来源:https://stackoverflow.com/questions/53553272/pygame-error-couldnt-open-image-png-only-in-command-prompt