Part 4 Loading and displaying images

In the last example we did load some images, but let’s look closer at these functions, and some other image-related functions that PyGame provides for us.

Working with images

To load an image into the program, you will use the pygame.image.load function.

Load an image — pygame.image.load

  • Inputs: filename (string)
  • Outputs: image-surface object (store it in a variable)

When you’re calling this function, you will want to make sure to store the loaded image into a variable like this:

imgGrass = pygame.image.load( "content/graphics/grass.png" )

Notes:

  • The file path is relative – this means that it’s in relation to the current path of the source code file you’re working in. For me, content is a folder at the same level as my .py file. Use forward-slashes, /, to differentiate between folders; the graphics folder is inside the content folder, and the grass.png image is within the graphics folder.
  • Store the result of the function in a variable – otherwise, it will load the image but you won’t be able to access it! Here, we are storing it in the variable imgGrass using the assignment operator, =.

 

Draw an image — Surface.blit

  • Inputs: source-surface, destination-rectangle )
  • Outputs: image-surface object (store it in a variable)

Remember that the window variable I declared last time was created like this:

window = pygame.display.set_mode( ( screenWidth, screenHeight ) )

The window variable is technically a pygame.Surface object.

To draw our image to the screen, we use window.blit:

window.blit( imgGrass, imgGrass.get_rect() )

Notes:

  • asdfasdf

 


 

Function documentation


<< Previous: Importing PyGame and Creating the window | Next: Loading and playing audio >>

Back to main page


Download this lesson’s source code at https://github.com/Rachels-Courses/Intro-to-PyGame

Print Friendly