按钮多次点击通话功能?

时间:2019-05-16 17:58:20

标签: python function button pygame

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

1 个答案:

答案 0 :(得分:2)

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

因此,对于我的按钮屏幕,我可以执行以下功能:

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.