In this Pygame Tutorial we want to learn How to Display Image in Pygame, so Pygame is popular Python library and it is used for building games and graphical applications. some times in building games and applications you need to add images in the screen, in this tutorial we are going to talk about this concept.
First of all we need to install this library and we can use pip for that.
1 |
pip install pygame |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import pygame pygame.init() # Load image image = pygame.image.load('python.png') # Scale image scaled_image = pygame.transform.scale(image, (200, 200)) # Create display screen = pygame.display.set_mode((800, 600)) # Blit image to the display screen.blit(scaled_image, (300, 250)) # Update the display pygame.display.update() # Main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() |
So in the above code first of all we need to import and initialize pygame.
1 2 |
import pygame pygame.init() |
After that we have initialized Pygame, we can load an image file that we want to display in our game or application. Pygame provides an image module that allows us to load images from files on our computer. this is is an example of how to load an image.
1 |
image = pygame.image.load('python.png') |
Images can be scaled up or down to fit the display surface. Pygame provides transform function in the surface module that allows us to scale an image.
1 |
scaled_image = pygame.transform.scale(image, (200, 200)) |
And lastly, we can blit our rendered text to the display. Pygame provides blit function that allows us to draw our Surface object onto the display. this is an example of how to blit our text to the display.
1 2 3 |
screen = pygame.display.set_mode((800, 600)) screen.blit(scaled_image, (300, 250)) pygame.display.update() |
Run the complete code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email