pygame-How to replace an image with an other one

2019-09-15 09:58发布

I have this sort of code:

width = 100
height = 50
gameDisplay.blit(button, (width, height))
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            # replace the button's image with another

Is there any function or something that would let me replace the image with another?

2条回答
霸刀☆藐视天下
2楼-- · 2019-09-15 10:18

To show changes on screen use pygame.display.update().

Your code should look like this

width = 100
height = 50
gameDisplay.blit(button, (width, height))
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            gameDisplay.blit(new_button, (width, height))
            pygame.display.update()
查看更多
时光不老,我们不散
3楼-- · 2019-09-15 10:24

You cannot 'replace' anything you've drawn. What you do is that you draw new images over the existing ones. Usually, you clear the screen and redraw your images every loop. Here's pseudo-code illustrating what a typical game loop looks like. I'll use screen as variable name instead of gameDisplay, because gameDisplay goes against PEP-8 naming convention.

while True:
    handle_time()  # Make sure your programs run at constant FPS.
    handle_events()  # Handle user interactions.
    handle_game_logic()  # Use the time and interactions to update game objects and such.

    screen.fill(background_color)  # Clear the screen / Fill the screen with a background color.
    screen.blit(image, rect)  # Blit an image on some destination.  Usually you blit more than one image using pygame.sprite.Group.
    pygame.display.update()  # Or 'pygame.display.flip()'.

For your code you probably should do something like this:

rect = pygame.Rect((x_position, y_position), (button_width, button_height))
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            button = new_button  # Both should be a pygame.Surface.

    gameDisplay.fill(background_color, rect)  # Clear the screen.
    gameDisplay.blit(button, rect)
    pygame.display.update()

If you only want to update the area where your image is you could pass rect inside the update method, pygame.display.update(rect).

查看更多
登录 后发表回答