我正在尝试在pygame中创建一个按钮。它应该在每次点击时显示三个新图像。一切正常,除了这些3个图像仅在单击按钮时出现。显示图像的代码如下,它是一个较大的while循环的一部分,它现在无限延续。如何才能使图像保持不变,直到再次按下按钮并出现新图像?感谢任何帮助,提前谢谢。
mouse = pygame.mouse.get_pos ()
click = pygame.mouse.get_pressed ()
element = -1
if 1120 > mouse [0] > 865 and 330 > mouse [1] > 250:
screen.blit (dice_button_light, (870, 250))
if click [0] == 1:
dice_choices = Dice.dice_choice()
print(dice_choices)
element = -1
for i in dice_choices:
element += 1
x = 750
if element == 1:
x += 100
if element == 2:
x += 200
if i == 1:
screen.blit (dice1,(x,100))
elif i == 2:
screen.blit (dice2,(x,100))
elif i == 3:
screen.blit (dice3,(x,100))
elif i == 4:
screen.blit (dice4,(x,100))
elif i == 5:
screen.blit (dice5,(x,100))
elif i == 6:
screen.blit (dice6,(x,100))
else:
screen.blit (dice_button, (870, 250))
答案 0 :(得分:0)
要循环浏览不同的图像,可以将它们放入列表中,只要单击按钮rect,就会递增表示当前图像的index
变量。在while循环中,只需使用索引从列表中获取正确的图像。
import sys
import pygame as pg
# Three images.
IMG1 = pg.Surface((100, 100))
IMG1.fill((240, 240, 240))
pg.draw.circle(IMG1, (0, 0, 0), (50, 50), 10)
IMG2 = pg.Surface((100, 100))
IMG2.fill((240, 240, 240))
pg.draw.circle(IMG2, (0, 0, 0), (25, 25), 10)
pg.draw.circle(IMG2, (0, 0, 0), (75, 75), 10)
IMG3 = pg.Surface((100, 100))
IMG3.fill((240, 240, 240))
pg.draw.circle(IMG3, (0, 0, 0), (20, 20), 10)
pg.draw.circle(IMG3, (0, 0, 0), (50, 50), 10)
pg.draw.circle(IMG3, (0, 0, 0), (80, 80), 10)
# Put the images into a list or tuple.
IMAGES = [IMG1, IMG2, IMG3]
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
bg_color = pg.Color(30, 40, 60)
# Use this rect for the collision detection and blitting.
img_rect = IMG1.get_rect(topleft=(200, 200))
img_index = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
if img_rect.collidepoint(event.pos):
img_index += 1
# Modulo to cycle between 0, 1, 2.
img_index %= len(IMAGES)
screen.fill(bg_color)
# Use the index to get the current image and blit
# it at the img_rect (topleft) position.
screen.blit(IMAGES[img_index], img_rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()