【发布时间】:2019-10-04 01:32:21
【问题描述】:
我的 python/Pygame 程序从一个调用函数的按钮和一个退出游戏的按钮开始。我想按下第一个按钮,然后调用一次函数,然后,它应该返回到开始按钮屏幕,让我通过单击按钮再次调用该函数。我怎样才能做到这一点?目前我只能点击按钮,调用函数,然后游戏结束。在下面的代码中,您可以看到代码中最重要的部分。
def function():
....
def main():
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False
def quit_game(): # A callback function for the button.
nonlocal done
done = True
button1 = create_button(100, 100, 250, 80, 'function', function)
button2 = create_button(100, 200, 250, 80, 'quit', quit_game)
# A list that contains all buttons.
button_list = [button1, button2]
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
for button in button_list:
# `event.pos` is the mouse position.
if button['rect'].collidepoint(event.pos):
# Increment the number by calling the callback
# function in the button list.
button['callback']()
screen.fill(WHITE)
for button in button_list:
draw_button(button, screen)
pygame.display.update()
clock.tick(30)
main()
【问题讨论】:
-
这里我说不清楚你想要什么,你想在点击一个按钮时多次调用一个函数吗?你想要一个按钮,当点击多次退出游戏?你想用按钮开始游戏吗?我不能完全理解你在说什么。
-
很抱歉,我的英语不是最好的。多次我的意思是:我想点击按钮,它会调用一次函数,然后它返回到按钮屏幕,让我有机会再次点击。
-
从最里面的for循环,你实际上调用了两个按钮回调,所以在执行button1函数之后它会调用
quit_game,也就是button2回调。不过,不确定这是否是您要问的。 -
好的,那么当你点击按钮时,你想进入游戏然后能够返回主屏幕吗? @ddd
-
@Pygasm,是的,这就是我要找的。span>
标签: python function button pygame