close

How to add a background image into pygame?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to add a background image into pygame in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to add a background image into pygame?

  1. How to add a background image into pygame?

    For background I always make an image the size of my game window or smaller then before all of the images are displayed, I blit that image to 0,0.

  2. add a background image into pygame

    For background I always make an image the size of my game window or smaller then before all of the images are displayed, I blit that image to 0,0.

Method 1

For background I always make an image the size of my game window or smaller then before all of the images are displayed, I blit that image to 0,0.

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

#INSIDE OF THE GAME LOOP
gameDisplay.blit(bg, (0, 0))

#REST OF ITEMS ARE BLIT'D TO SCREEN.

Hope this helps.

Method 2

This problem can be easily solved. You will need an image the size of your screen for your background. Please remember to add pygame.init() at the beginning of your game to be able to start it and its abilities. A function for this picture can be used like this:

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location

This will allow the program to load your image through this function when you call it like this:

BackGround = Background('background_image.png', [0,0])

And you will also need these two lines in your while loop:

screen.fill([255, 255, 255])
screen.blit(BackGround.image, BackGround.rect)

This will fill your screen white and put the background image over it but under your other sprites and objects.
Suggestions: You should make another class for your other sprite (maybe the reason why the image is not appearing). An example could be like:

class Ship(pygame.sprite.Sprite):
    def __init__(self, image_file, speed, location):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location

You could then “activate” it like this:

ship = Ship("images\ship.png", [a, b])

Select the coordinates for a and b. You can then blit the image on to the screen like this but after your background blit statement:

screen.blit(ship.image, ship.rect)

I hope this helps you!

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read