Pygame 中的顺序图像呈现 [英] Sequential image presentation in Pygame
问题描述
一个简单的问题,但我是 Python/Pygame 的新手.我想 blit 图像(old.png),然后在按键(空格键)上将该图像替换为另一个图像(new.png):顺序演示.目前,old.png 仍保留在表面上,而 new.png 最终位于其顶部.
A simple problem, but i am new to Python/Pygame. I want to blit an image (old.png) and then have that image be replaced by another image (new.png) upon a keypress (spacebar): sequential presentation. Currently, the old.png remains on the surface, with new.png ending up on top of it.
这是我的代码:
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)
推荐答案
您可以将图像保留在列表中并使用索引 current_image
选择要显示的图像.这样你就可以拥有 2 张以上的图片.
You can keep images on list and use index current_image
to select image to display. This way you can have more than 2 images.
# 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)
--
顺便说一句:你可以使用
screen_rect = screen.get_rect()
然后你可以使用
screen_rect.center
代替
(display_width/2, display_height/2)
在
screen.blit(images[current_image], screen_rect.center)
但如果你想正确居中图像,你需要图像矩形
but if you want to center image correctly you need image rect
# 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)
这篇关于Pygame 中的顺序图像呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!