首页 > 解决方案 > 多次单击按钮时调用函数?

问题描述

我的 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()

标签: pythonfunctionbuttonpygame

解决方案


您需要在这里将每个屏幕/游戏循环隔离到其自己的特殊功能中:

因此,对于我的按钮屏幕,我可以制作这样的功能:

def title():
    button1 = create_button(100, 100, 250, 80, 'game', game) # This will call the game function later in the file
    button2 = create_button(100, 200, 250, 80, 'quit_game', quit_game)
    # A list that contains all buttons.
    button_list = [button1, button2]
    # And so on with the rest of the code...

对于主游戏,您可以执行相同的操作:

def game():
    button1 = create_button(100, 100, 250, 80, 'Exit', title) # This button will return you to the title
    # And whatever else you need     

之后,在文件末尾,您可以添加以下内容:

if __name__ == '__main__':
    pygame.init()
    title() # Call the title first, and then further functions
    pygame.quit()

您必须注意,当您激活按钮回调时,return需要稍后才能卸载该屏幕,否则您只会将游戏循环分层。

因此,在事件循环期间:

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']()
            return # Leave the function now that the new one is called.

推荐阅读