python - 如果用户多次按下函数,如何只调用一次函数
问题描述
我目前正在开发一个具有简单 GUI 和 3 个按钮的程序。其中之一是start
,它运行我的代码。我正在尝试使其尽可能用户友好,因此如果他们点击垃圾邮件,它只会运行一次。目前,如果用户多次按下按钮,则图像每秒更新多次。任何帮助,将不胜感激。
解决方案
最常见的 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)
有了这个,我们可以看到实际组件之外的组件状态。
推荐阅读
- c - C程序修改文件中的现有记录
- reactjs - React 组件将无法加载并抱怨子元素问题
- windows - Docker 可以在 Windows 10 IoT Enterprise 上运行吗?
- wordpress - 如何将 wordpress 后端编辑器时间从 24 小时格式转换为 12 小时格式
- django - 本地主机上的 Django + https
- camunda - Camunda:如何在我的工作流程中找到引发 OptimisticLockingException 的步骤
- query-optimization - 为什么即使在刚刚重新编译后,使用“WITH RECOMPILE”的存储过程运行得更快?
- javascript - 如何从函数返回错误?
- python - 在 Python 中抓取 onclick 表
- java - 是否可以创建必要/必需的接口?