Pygame window crashes when I use pygame.image.load()

Viewed 84

I started playing around with Pygame today, and while following a guide that instructed me to change the game icon I ran into an issue with the line:

img = pygame.image.load("icon.bmp")

My code works fine without this line, but with it the program instantly crashes. I also noticed that before the crash the icon starts as "icon.bmp", but then changes into the default one. I have a block of code afterwards that stops the program from exiting automatically after running the code, and the window remains on screen when I comment the problematic line.

My guess is maybe a problem with the file path. The image is in the same folder as the script. I am not sure how to make a relative file path, but earlier when I used an absolute path and the issue persisted.

I can't find anyone else with the same problem, and I am getting frustrated at getting stuck on such a simple issue, so in my desperation, I've come here for help. I am sorry for the newbie question, I've never written on stackoverflow.com before.

1 Answers

The file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory.

The name and path of the file can be get by __file__. The current working directory can be retrieved with os.getcwd() and can be changed with os.chdir(path):

import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))
Related