Pygame Add Image to Surface

So, you know how to make a simply pygame window, and now you want to do something a bit more interesting, aye?

download-bttn
Download Code

How do you  add an image to your pygame surface ?

In this quick tutorial, we’ll show you exactly that. So that your finished product will look like is the following picture :

 

pygame-image-on-surface

 

Here’s the full Python code:

import pygame

pygame.init()
width=350;
height=200
screen = pygame.display.set_mode((width, height ))
pygame.display.set_caption('Display an image')
penguinImage = pygame.image.load("peng-east.png").convert()

x = 20; # x coordnate of image
y = 30; # y coordinate of image
screen.blit(penguinImage, ( x,y)) # paint to screen
pygame.display.flip() # paint screen one time

running = True
while (running): # loop listening for end of game
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
#loop over, quite pygame
pygame.quit()



So, remember that the top left corner is where the coordinates will place the image so x = 20,y = 30  in lines 13/14 means that that’s where the top left corner of the image is.

pygame display image

Now, this only works if the image is in the *same folder* as your script.peng-east

 

Here’s what the folder  structure should look like (It’s important that the image “peng-east.png” is in the same folder as the “display-pygame-image.py” file.

folder-structure