Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65859573/how-to-fill-the-background-with-a-small-image-in-pygame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...