1

I am trying to load a .png image using the pygame.image.load() function. The image I am trying to load is in the same relative directory as the program file I'm running. I have followed the same syntax I've used before and found in tutorials, yet it still doesn't work.

Code:

import pygame
image = pygame.image.load("ImageFolder/TestImage.png")

File directory(cannot yet embed image, so here's a link):

https://gyazo.com/5b8c20ca6058db7629caae602adbcb35

Error Message:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "c:/Users/dougl/OneDrive/Skolgrejer/Programmering/Program/TestFolder/TestFile.py", line 3, in <module>
    image = pygame.image.load("ImageFolder/TestImage.png")
pygame.error: Couldn't open ImageFolder/TestImage.png
PS C:\Users\dougl\OneDrive\Skolgrejer\Programmering\Program> 

Using: Python 3.7.4 32-bit, pygame 1.9.6

TehDogge
  • 15
  • 5
  • Try `TestFolder/ImageFolder/TestImage.png` instead. If you're using an IDE, then your program might start from another path. It seems like your project is starting at *'C:\Users\dougl\OneDrive\Skolgrejer\Programmering\Program'* – Ted Klein Bergman Mar 31 '20 at 19:43

1 Answers1

3

It's likley that your program isn't executing in the same directory that your ImageFolder exists in.

This can be checked quite easily:

import os.path

dir_path = os.path.dirname( os.path.realpath( __file__ ) )
print( "Current dir is [%s]" % dir_path )

You could also use os.chdir() to ensure your code is running in the correct place before the loading starts:

import os

INSTALL_DIR = "c:/Users/dougl/OneDrive/Skolgrejer/Programmering/Program/TestFolder/"

os.chdir( INSTALL_DIR )

... and perhaps check if your directory is where you think it is, and handle it gracefully:

import os.path

IMAGE_DIR = 'ImageFolder'

if ( not os.path.isdir( IMAGE_DIR ) ):
    # TODO: handle error
    pass
Kingsley
  • 14,398
  • 5
  • 31
  • 53
  • Using the whole directory in that way turned out to work, but I'm still looking for a solution that uses the relative directory in order to launch the file, so I can export it to other users. – TehDogge Apr 01 '20 at 20:22
  • @TehDogge - Yes, but right now you're using some kind of IDE like PyCharm, VSC, etc. etc. Once it's packaged the executable will be started in the correct location. So you should first check that the `ImageFolder` is not available before doing an `os.chdir()`, because this is probably only a problem running from the IDE. – Kingsley Apr 01 '20 at 21:25