Pygame tutorial 2 – loading images

After talking about surfaces in the last post (Pygame tutorial n. 1), we talk now about using images instead of simple colored area. These object we are going to create are surfaces too, the difference is that we can have any images on them and then we can show them on the screen (the main) surface with blit.

How to load an image

image = pygame.image.load("name.png")

How to show the image

Once you created the screen = pygame.display.set_mode((400, 400)) main surface, for example, you can blit on it the image with

screen.blit(image, (0, 0))

(0, 0) is a tuple that is where the image top left corner will be. At 0,0 means that it will be at the top left of the window.

Using a color as background

In case you want a color as background of the window

screen.fill((0, 0, 255))

You will have a blue color. This is good also to clean the window when you run games or animations. This will clear all the window, if you put this in the while loop. We will see this in another post.

The code with the example

This code will let you show an image. If you just call show() the image will be displayed at its original size. If you call it with 1 as parameter (show(1)), the image will ne stretched to fit the size of the screen.

import pygame

# SCALE AN IMAGE TO FIT THE SCREEN
 
pygame.init()
 
def show(fit=0):
    ''' use show(1) to fit the screen '''
    screen = pygame.display.set_mode((600, 500))
    bg = pygame.image.load("image.png").convert_alpha()
    sw, sh = screen.get_size()
    if fit:
        screen.blit(pygame.transform.scale(bg, (sw, sh)),(0, 0))
    else:
        screen.blit(bg,(0, 0))
    while True:
        if pygame.event.get(pygame.QUIT):
            break
        pygame.display.update()
    pygame.quit()

show(1)

In this example we show the background, a blue surface and an image on the screen

The live video coding explanation


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.