1
votes

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

1
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

1 Answers

3
votes

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