How to fill the background with a small image in pygame?

Viewed 122

How can I tell pygame to repeat a small image to fill the screen ? I tried using blit but it only puts one image on the screen and doesn't fill it.

1 Answers

You need to use nested loops to blit the image multiple times like tiles. Get the width and height of the screen and the image with get_size(). Use range to generate the top left positions of the tiles:

screen_w, screen_h = screen.get_size()
image_w, image_h = image.get_size()

for x in range(0, screen_w, image_w):
    for y in range(0, screen_h, image_h):
        screen.blit(image, (x, y))

Minimal example:

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 200))
image = pygame.image.load('Apple.png')

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    screen.fill((255, 255, 255))

    screen_w, screen_h = screen.get_size()
    image_w, image_h = image.get_size()

    for x in range(0, screen_w, image_w):
        for y in range(0, screen_h, image_h):
            screen.blit(image, (x, y))
   
    pygame.display.flip()

pygame.quit()
exit()
Related