The Python Game Book

code games. learn Python.

User Tools

Site Tools




This is an old revision of the document!

step 008 - loading images


loading images

Using pre-fabricated images instead of painting all images yourself with the pygame.draw - functions comes very handy. This example shows you how to load images into pygame. Note that in this example, the images must be in the same folder as the python program ! In this example, if pygame can not find the images, it will print an error message and use the image-drawing methods from the previous code example.

catching file not found error

This is done using the try: except: method.

   #do something risky that may not work like loading files
   #do that if an error occurs inside the try block
# continue here if no error

Also see the official documentation:


additional resources

Put those 2 graphic files in the same folder as to make the program run correctly. If one or both of those files are not found you will see a brown and a blue circle instead:

filename preview1) / note folder 2) source / license
babytux.png Babytux graphic file (.png) with transparent border <key>.</key> wikimedia commons
background640x480_a.jpg background.jpg file
<key>.</key> Horst JENS / public domain all files except the source code
in a zipped package

source code

# -*- coding: utf-8 -*-

loading images from harddisk and using convert_alpha()
This program try to load 2 image files from the harddisk. Both files must be in the
same folder as the program itself. If the image files are not found, images are
created by code instead and an error message is printed.
Note that convert_alpha() is only necessary when the loaded image had
a transparent color. Some .png and .gif files have this, but never .jpg files.
import pygame
screen=pygame.display.set_mode((640,480)) # try out larger values and see what happens !
    background = pygame.image.load("background640x480_a.jpg")
    print("Error: the image background640x480_a.jpg is not in this folder")
    background = pygame.Surface(screen.get_size()) # create a pygame Surface
    background.fill((255,255,255))                 # fill the background white, (50,50,0), (300,250), 200)   # draw circle
    ball = pygame.image.load("babytux.png")
    print("Error: the image babytux.png is not in this folder")
    ball = pygame.Surface((50,50))     #create a new black surface 
    ball.set_colorkey((0,0,0))    , (0,0,255), (25,25),25) # paint blue circle
background = background.convert()  # jpg can not have transparency
ball = ball.convert_alpha()        # png image has transparent color 
ballx, bally = 550, 240            # start position of ball surface
dx, dy  = 60, 60                   # ball speed in pixel per second !
screen.blit(background, (0,0))     # blit background on screen (overwriting all)
screen.blit(ball, (ballx, bally))  # blit the ball shape 
clock = pygame.time.Clock()        # create pygame clock object 
mainloop = True
FPS = 60                           # desired max. framerate in frames per second. 
while mainloop:
    milliseconds = clock.tick(FPS)  # milliseconds passed since last frame
    seconds = milliseconds / 1000.0 # seconds passed since last frame
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mainloop = False # pygame window closed by user
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                mainloop = False # user pressed ESC
    pygame.display.set_caption("[FPS]: %.2f X:%.1f Y:%.1f Speed"
    " [pixel/sec] dx:%.2f dy:%.2f" % (clock.get_fps(), ballx, bally, dx, dy))
    # only blit the part of the background where the ball was (cleanrect)
    dirtyrect = background.subsurface((round(ballx,0), 
                round(bally,0), ball.get_width(), ball.get_height()))
    # comment out the next line for a funny effect !
    screen.blit(dirtyrect, (round(ballx,0), round(bally,0))) 
    #calculate new center of ball 
    ballx += dx * seconds # time based movement
    bally += dy * seconds
    # bounce ball if out of screen
    if ballx < 0:
        ballx = 0
        dx *= -1 
    elif ballx + ball.get_width() > screen.get_width():
        ballx = screen.get_width() - ball.get_width()
        dx *= -1
    if bally < 0:
        bally = 0
        dy *= -1
    elif bally + ball.get_height() > screen.get_height():
        bally = screen.get_height() - ball.get_height()
        dy *= -1
    # paint the ball    
    screen.blit(ball, (round(ballx,0), round(bally,0)))    
    pygame.display.flip()          # flip the screen 30 times a second                # flip the screen 30 (or FPS) times a second

left-click to zoom to original size
<key>.</key> means the same folder as the program
en/part2/pygame/step008.1264342240.txt.gz · Last modified: 2014/01/09 11:07 (external edit)