Load an Image
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 1 of 36.
Games draw pictures, not only shapes. A picture comes from an image file, and pygame turns the file into a Surface, the same kind of thing as the window: a grid of pixels you can draw.
ship = pygame.image.load("assets/images/ship.png").convert_alpha()The path is relative to main.py: the game has an assets folder next to it, and the Assets tab beside the game lists every file in it.
convert_alpha() copies the picture into the window's own pixel format, so drawing it every frame is fast, and keeps its see-through pixels. It needs the window, so load images after set_mode. Load each image once, before the loop: reading a file 60 times a second slows the game down.
To draw the picture, blit it onto the window. The position is where its top left corner goes:
screen.blit(ship, (288, 208))Blit it after screen.fill(...), or the fill paints over it.
Challenge
Easy- After
set_mode, loadassets/images/ship.pngwith.convert_alpha()into a variable namedship. - In the loop, after the fill, blit
shipwith its top left corner at(288, 208). The ship is 64 by 64 pixels, so it sits in the middle of the 640 by 480 window.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Space Images")
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 22, 40))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sprites and Images
3Classes for Game Objects
Your First ClassMethodsSelf Is the ObjectA List of ObjectsObjects with ImagesA SubclassPractice on your own: Pygame playground