1

Im trying to load an image into a window on pygame but when i run the code. It pops up with an error of

pygame.error: Couldn't open backround.png

I have the image in the same folder with the code itself. I have done this for another script and it works perfectly fine. I am not sure what the problem is.

I've tried closing my program. Renaming the file but that's about it. Not sure how to tackle the problem. Any help is much appreciated

import pygame
import os
from Introduction import *

# Making the window
pygame.init()
windowSize = (800, 600)
screen = pygame.display.set_mode(windowSize)

# Images in the Introduction
GameBackround = pygame.image.load('backround.png')

while True:

    screen.blit(GameBackround, (0,0))

    for event in pygame.event.get():

        screen.blit(GameBackround, (0,0))

    pygame.display.update()
    pygame.display.flip()

Like I said: I have used similar layout to load images with another file and it works perfectly fine but for some reason it doesn't load the image in case.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

0

The image filepath has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.

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

If the image is in the same folder as the python file, then you cnb get the directory of the file and change the working directory by os.chdir(path):

import os

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir )

or concatenate the image filename and the file path by os.path.join. e.g.:

import pygame
import os
from Introduction import *

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

GameBackround = pygame.image.load(os.path.join(sourceFileDir, 'backround.png'))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174