So after some scrambling around trying to find a good beginner programming language, i have found python, and with my ultimate goal being game development, also pygame.

I have just started learning some basics, and I was going through a tutorial when i ran into an error that im not sure how to get around.

Here is my code:

import pygame, sys,os
from pygame.locals import * 
 
pygame.init() 
 
window = pygame.display.set_mode((640, 320)) 
pygame.display.set_caption('Test') 
screen = pygame.display.get_surface() 

background = os.path.join("C:\\python26\\stuff\\bg.jpeg")

background_surface = pygame.image.load(background)

screen.blit(background_surface, (0,0)) 
pygame.display.flip() 
 
def input(events): 
   for event in events: 
      if event.type == QUIT: 
         sys.exit(0) 
      else: 
         print event 
 
while True: 
   input(pygame.event.get())

I want to load the background image (which is 100% in the directory i specified). Unfortunately when i run the program i recieve the following error:

Traceback (most recent call last):
  File "C:/Python26/Tutorial", line 12, in <module>
    background_surface = pygame.image.load(background)
error: Couldn't open C:\python26\stuff\bg.jpeg

I have searched some, and found that inputting the os.path.join command was supposed to get rid of the error because of the cross-platform compatibility or somthing.
Currently on vista 64bit, dont know if that helps or not.

All replies appreciated, thank you for taking the time to read and (hopefully) respond.

Dani AI

Generated

Nice catch by and on the extension. Two extra pitfalls to watch for when loading images in Pygame: your working directory and display format. The error often means Python is looking in a different folder than you think. Also, for fast blits you want the image converted to the display format after the window is created.

Building on and , keep assets in a project folder and load them via a path relative to the script. This avoids hardcoded absolute paths and works on Windows, macOS, and Linux.

from pathlib import Path
import pygame, sys

pygame.init()
screen = pygame.display.set_mode((640, 320))
pygame.display.set_caption("Test")

ASSETS = Path(__file__).resolve().parent / "assets"

def load_image(name):
    path = ASSETS / name
    if not path.is_file():
        raise FileNotFoundError(f"Missing: {path}")
    surf = pygame.image.load(str(path))  # str() keeps pygame happy on all versions
    return surf.convert_alpha() if surf.get_alpha() else surf.convert()

bg = load_image("bg.jpg")

clock = pygame.time.Clock()
running = True
while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
    screen.blit(bg, (0, 0))            # redraw every frame so uncovered windows repaint
    pygame.display.flip()
    clock.tick(60)

pygame.quit(); sys.exit()

Quick troubleshooting if you ever see "Couldn’t open ...":

  • Verify the exact filename and case. On Linux/macOS, BG.JPG and bg.jpg are different.
  • Print both os.getcwd() and the absolute path you are trying to load to confirm location.
  • Prefer forward slashes in plain strings (e.g., C:/stuff/bg.jpg) or just use pathlib as above.
  • If JPEG/PNG fail on older setups, check pygame.image.get_extended(); if it returns False, install SDL_image or use BMP for a quick test.

Recommended Answers

All 7 Replies

Yeah, i dont know if you may have checked this. But i know i stuffed this up one time, but are you sure its .jpeg not .jpg or .JPG or something like that?

:P

Yeah I'm with the guy above, are you sure that it's ".jpeg" and not ".jpg"?

You could use / both Windows and Unix allow that.

oh yep.. now i feel stupid :O
it turned out to be .jpg, and when i changed the code, all went well
thanks guys :D

Might as well go with:

...
background = "C:\\python26\\stuff\\bg.jpg"
background_surface = pygame.image.load(background)
...

Since that kind of directory name is meant for Windows only.

I personally think (as a side note), that he should:

a) Use a relative path so that he can keep the project in one folder and use a hierarchy of folders within that. This allows him to move the project's folder but keep all the paths in the script valid because they're relative.
b) Use single, forward slashes in his path as that's accepted on Windows and Linux. So "C:/python26/stuff/bg.jpg" works even better.

Just my two cents :P

Thanks shadwickman for your thoughts.
Using C:/python26/stuff/bg.jpg with the Windows OS would be recommendation too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.