首页 > 解决方案 > 如果用户多次按下函数,如何只调用一次函数

问题描述

我目前正在开发一个具有简单 GUI 和 3 个按钮的程序。其中之一是start,它运行我的代码。我正在尝试使其尽可能用户友好,因此如果他们点击垃圾邮件,它只会运行一次。目前,如果用户多次按下按钮,则图像每秒更新多次。任何帮助,将不胜感激。

标签: pythonfunctionuser-interface

解决方案


最常见的 OOP 实践之一是将 GUI 中的所有内容视为一个组件、一个处理自己的变量的类、一个组件状态,当您第一次渲染组件时对其进行初始化。

例如,如果我们想监控按钮何时被点击,我们可以在之后通过更新组件状态来禁用该按钮。

class Button:
    """
        Button that self monitors how many clicks have been performed
    """
    def __init__(self,):
        #Initialize state
        self.disabled = False
        self.button_clicked = 0
    
    def click(self,):
        if not self.disabled: #Only perform action if self.disabled == False
            self.disabled = True
            self.button_clicked += 1
            #Do stuff on click

class ButtonContainer:
    """
        Container for a group of associated Buttons
    """

    def __init__(self,):
        self.button1 = Button()
        self.button2 = Button()
        self.button3 = Button()


class App:
    def __init__(self,):
        #Add components to your app
        self.button_container = ButtonContainer()

我们可能想要使用容器的原因是因为我们可以将按钮组合在一起,然后从我们的主 App 类中进行监控。
例如,在 App 类中,我们可以调用

print(self.button_container.button1.disabled)

有了这个,我们可以看到实际组件之外的组件状态。


推荐阅读