Image not loading from file within same directory, Pygame, python

Viewed 119

I'm currently trying to show an image onto my pygame screen but it I keep on being told that my image is not in the directory. Maybe I can be proven wrong but I'm quite confident that the image location is in the same directory, and that something must be wrong with my code and so it's not able to fetch it. The traceback error is:

FileNotFoundError: No file 'Assets\gold_star.png' found in working directory 
'C:\Users\PycharmProjects\eyegame'

I've pasted the code below:

WIDTH,HEIGHT  = 750,600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Eye Reaction App !")

WHITE = (250, 250, 250)

FPS = 60

GOLD_STAR_IMAGE = pygame.image.load(
    os.path.join('Assets', 'gold_star.png'))
GREEN_TRIANGLE_IMAGE= pygame.image.load(
    os.path.join('Assets','green_triangle.png'))
LIGHT_BLUE_RECTANGLE_IMAGE = pygame.image.load(
    os.path.join('Assets','light_blue_rectanhle.png'))
ORANGE_SQUARE_IMAGE = pygame.image.load(
    os.path.join('Assets','orange_square.png'))
PURPLE_HEXAGON_IMAGE = pygame.image.load(
    os.path.join('Assets','purple_hexagon.png'))
RED_CIRCLE_IMAGE = pygame.image.load(
   os.path.join('Assets','red_circle.png'))


def draw_window():
    WIN.fill(WHITE)
    WIN.blit(GOLD_STAR_IMAGE, (300,100))
    pygame.display.update()

def main():
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        draw_window()

    pygame.quit()

if __name__ == "__main__":
    main()
1 Answers

It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python script.
Put the following at the beginning of your code to set the working directory to the same as the script's directory:

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

See __file__ and os.chdir()

Related