Pygame中的连续图像显示

时间:2016-01-05 15:56:08

标签: python pygame

一个简单的问题,但我是Python / Pygame的新手。我想blit一个图像(old.png),然后在按键(空格键)上将该图像替换为另一个图像(new.png):顺序显示。目前,old.png仍然在表面上,new.png最终在它上面。

这是我的代码:

for event in pygame.event.get():   
    if event.type == pygame.QUIT:
        pygame.quit()
        quit()

    screen.blit(old, (display_width/2, display_height/2))
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
           screen.blit(new, (display_width/2, display_height/2))

pygame.display.flip()
clock.tick(30)

2 个答案:

答案 0 :(得分:0)

例如,您可以创建一个变量:picture = "old",当按下空格键时,您可以执行以下操作:

if picture == "old":
    picture = "new"
    screen.blit(new, (display_width/2, display_height/2))
else:
    picture = "old"
    screen.blit(old, (display_width/2, display_height/2))

因此,每按一次空格键,图片都会切换

答案 1 :(得分:0)

您可以将图像保留在列表中,并使用索引current_image选择要显示的图像。这样您就可以拥有2张以上的图像。

# all images on list

images = []

images.append(old)
images.append(new)
images.append(another_image)
#images.append(another_image_2)
#images.append(another_image_3)

# how many images we have ?
images_number = len(image)

# index of current displayed image
current_image = 0


# in mainloop

while True:

    for event in pygame.event.get():   
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:

                # get next index (if it is bigger than `images_number` then get `0`) 
                current_image = (current_image + 1) % images_number

    # clear screen
    screen.fill((0,,0)) # black

    # blit current image
    screen.blit(images[current_image], (display_width/2, display_height/2))


    pygame.display.flip()
    clock.tick(30)

-

BTW:您可以使用

screen_rect = screen.get_rect() 

然后你可以使用

screen_rect.center

而不是

(display_width/2, display_height/2)

screen.blit(images[current_image], screen_rect.center)

但如果你想正确居中图像,你需要图像矩阵

# get image rect
image_rect = images[current_image].get_rect()

# center image rect on the screen
image_rect.center = screen_rect.center

# draw image using `image_rect`
screen.blit(images[current_image], image_rect)