Displaying images with PyGame

In this tutorial, we will learn how to display an image in Python using the PyGame library, with the help of an easy example.

PyGame in Python

In this tutorial, we are going to make use of a popular Python library called PyGame. PyGame is essentially a wrapper for the SDL library. The SDL library is a useful one as it provides access to your device’s multimedia hardware components such as a mouse, keyboard, sound, video, etc. This allows you to develop games and write programs for any platform that supports one of these libraries. Let us start by installing the pygame library.

pip install pygame

Now, import it into our IDE or text editor.

import pygame

Also read: Drawing Different Shapes in pygame Using Python

We are ready to use the library now. Here’s the code for displaying an image in Python in it’s entirety.

import pygame


pygame.init()


display_width = 600
display_height = 500

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Race')

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load(r'C:\Users\anish\Downloads\car.jfif')

def car(x,y):
    gameDisplay.blit(carImg, (x,y))

x =  (display_width * 0.27)
y = (display_height * 0.25)

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

    gameDisplay.fill(white)
    car(x,y)

        
    pygame.display.update()
    clock.tick(60)

pygame.quit()

After initializing pygame, we need the size of the window in which we want to display our image. So, we use pygame.display.set_mode() method and give some display height and width. We can also give the window some caption.

display_width = 600 
display_height = 500 
gameDisplay = pygame.display.set_mode((display_width,display_height)) 
pygame.display.set_caption('Race')

Moving on, we need a while loop which functions until to user quits the program. So, we give the starting condition as crashed = True, which means the program runs. When the user quits the program, the condition changes to crashed = False.

Inside the while loop, we define a function car pass in it the method gameDisplay.blit() which displays the image in the window. For the arguments, we pass the image we want to display and the starting and ending points of the image (x, y).

carImg = pygame.image.load(r'C:\Users\anish\Downloads\car.jfif')

def car(x,y):
    gameDisplay.blit(carImg, (x,y))

x =  (display_width * 0.27)
y = (display_height * 0.25)

For the background color, we pass the RGB format of the colors we want to use. In this case, I’ve taken Black and White.

black = (0,0,0)
white = (255,255,255)

We use the function pygame.Display.fill() and then pass the function car(x,y) on top of it.

gameDisplay.fill(white)
car(x,y)

As a result, a window should be created having the image you want to be displayed.

Leave a Reply