In this tutorial, we will be walking through how to draw images with PyGame. Let’s dive right in.
In your game file, you should see the set_mode method being called. This method call returns a Surface, which is pretty much just the canvas that we’re drawing to. Make sure that the return value of this method call is being assigned to a variable. I named my variable, display like to so:
display = pygame.display.set_mode((800, 600))
Next, we need to load an image. To do so, write this line before our game loop:
myimage = pygame.image.load("myimage.png")
At the bottom of our game loop, before the display.update call (if you added one), add the following two lines:
display.fill((0, 0, 0)) display.blit(myimage, myimage.get_rect())
The first line fills the screen in black. It’s good practice to call this before our drawing code. Normally we only need to call this once. The blit method is what actually copies our image to our surface, display, to be drawn. In this method, we are passing two arguments. The first argument we pass in is the image we want to draw. The second argument we’re passing is the source rectangle of the image. The source rectangle x and y positions are 0, 0 (top-left corner of image), the width and height is the width and height of the image. When we run our project, we should see the image we loaded display in the top-left corner of our game canvas.
Alternatively, we can pass in x and y positions instead of a destination rectangle. To do so, adjust our blit call to:
display.blit(myimage, (480, 128))
When we run our game now we should see:
Now you know how to draw images with PyGame! It’s not too bad once you practice adding more. Have questions? Please leave your questions and comments down below, and I will do my best to get back to you. If you found this guide useful, you may want to consider taking a look at the rest of our Python Basics tutorial series. To receive updates and news regarding our future tutorials and courses, you can subscribe to our newsletter. Sharing this guide on your favorite social media platform is also much appreciated, of course, only if you found this tutorial valuable.Tags: cross-platform, free, gamedesign, PyGame, Python
Categorised in: PyGame Basics
This post was written by Jared York