I can't get images to load.. I always get an error

here's my code so far:

#pong

import os, sys
import pygame
from pygame.locals import *

if not pygame.font: print "Warning, fonts disabled"


#--------------------------------------------------------

def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

class Paddle(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('paddle.bmp')


class ball(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('ball.bmp')
        screen = pygame.display.get_surface()
        self. area = screen.get_rect()
        self.rect.topleft = 10, 10
        self.y, self.x = 10, 8


    def move(self):
        newpos = self.rect.move((self.y, self.x))
        if self.rect.left < self.area.left:
            #point to player 1
            #new ball
            pass
        if self.rect.right > self.area.right:
            #point ot player 2
            #new ball
            pass
        if self.rect.top < self.area.top or \
           self.rect.bottom > self.area.bottom:
           self.y = -self.y
           newpos = self.rect.move((self.x, self.y))
        self.rect = newpos


def main():

    pygame.init()
    screen = pygame.display.set_mode((640,480))
    pygame.display.set_caption("Pong")
    pygame.mouse.set_visible(0)

    background = pygame.Surface((640,480))
    background = background.convert()
    background.fill((250,250,250))

    if pygame.font:
        font = pygame.font.Font(None, 36)
        text = font.render("0:0", 1, (10,10,10))
        textpos = text.get_rect(centerx=background.get_width()/2)
        background.blit(text, textpos)

    screen.blit(background, (0,0))
    pygame.display.flip()

    clock = pygame.time.Clock()
    paddle = Paddle()
    ball = Ball()
    allsprites = pygame.sprite.RenderPlain((paddle, ball))

#main loop
    while 1:
        clock.tick(40)

        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == KEYDOWN and event.key == K_UP:
                #move paddle up
                pass
            elif event.type == KEYDOWN and event.key == K_DOWN:
               # move paddle down
               pass

        allsprites.update()

        screen.blit(background, (0,0))
        allsprites.draw(screen)
        pygame.display.flip()

if __name__ == '__main__': main()

Dani AI

Generated

Most "can't load image" errors in threads like this come from where the program is looking for the file, not from Pygame itself. The original loader builds a relative path (for example a data subfolder); if the process is started with a different current working directory, the file won't be found even when it sits next to the .py. A reliable approach is to build an absolute path from the script location and verify existence before attempting pygame.image.load().

import os, pygame
pygame.init()
script_dir = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(script_dir, 'data', 'paddle.bmp')  # change if images are in the same folder
print("CWD:", os.getcwd())
print("Looking for:", image_path, "Exists:", os.path.exists(image_path))
try:
    img = pygame.image.load(image_path)
except pygame.error as e:
    print("Load failed:", e)

Quick checklist (run these before assuming a Pygame bug): confirm os.path.exists(image_path), check filename spelling and case (macOS/Linux are case-sensitive), verify the extension (.bmp vs .png), try loading the absolute path from a Python prompt, and use convert_alpha() for images with transparency (or convert() for opaque bitmaps). Running the script by double-clicking an editor or from some IDEs can set the current working directory differently than running from the command line — that often explains why files that "look" next to the script are not found.

This directly addresses 's placement question and the cross-platform symptom described: if the absolute-path test shows the file exists but pygame.image.load() still fails, inspect the image file itself and the installed SDL/Pygame build; if os.path.exists is False, the problem is the path/working-directory and the snippet above fixes it in the vast majority of cases.

Recommended Answers

All 5 Replies

What error?

oops, forget to paste it at the bottom

Traceback (most recent call last):
File "C:\Python26\New folder\", line 106, in <module>
if __name__ == '__main__': main()
File "C:\Python26\New folder\", line 80, in main
paddle = Paddle()
File "C:\Python26\New folder\", line 29, in __init__
self.image, self.rect = load_image('paddle.bmp')
File "C:\Python26\New folder\", line 18, in load_image
raise SystemExit, message
SystemExit: Couldn't open data\paddle.bmp

Where are you placing your paddle.bmp file?

the img files and py file are all in the same folder

python26/pong

Im having the same problem. after three months with no reply, has anyone come up with a solution to this?

More specifically, the problem is that pygame wont load any images. none at all. please dont tell me to put the images in the same folder or to write out the entire path to the image. none of that works.

Ive tried this on mac and windows, using different versions of python and pygame. still nothing.

I have read the entire internet. yes, the entire internet. nothing.

To be honest, this is quite frustrating and i would appreciate any help

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.