【问题标题】:How to change the text of a button when it is being continuosly pressed for 3 seconds如何在连续按下按钮 3 秒时更改按钮的文本
【发布时间】:2023-03-22 04:36:01
【问题描述】:

让我们考虑以下代码:

#.py file

class Screen:
    def change_text():
        self.ids.btn.text="some text"
#.kv file

<Screen>:
    GridLayout:
        cols:1
        Button:
            id:btn
            on_press: root.change_text()

一旦按下按钮,它的文本就会改变。但是如何更改代码,以便仅在连续按下按钮 3 秒时更改文本?

【问题讨论】:

    标签: android python-3.x button kivy widget


    【解决方案1】:

    如果您只想在按住按钮 3 秒钟后更改文本,您可以执行以下操作:

    kv:

    <Screen>:
        GridLayout:
            cols:1
            Button:
                id:btn
                on_press: root.start_timer()
                on_release: root.cancel_timer()
    

    py:

    class Screen(FloatLayout):
        def __init__(self, **kwargs):
            super(Screen, self).__init__(**kwargs)
            self.timer = None
    
        def start_timer(self):
            if self.timer:
                self.timer.cancel()
            self.timer = Clock.schedule_once(self.change_text, 3.0)
    
        def cancel_timer(self):
            if self.timer:
                self.timer.cancel()
    
        def change_text(self, dt):
            self.ids.btn.text="some text"
    

    这使用Clock.schedule_once() 将文本更改安排在 3 秒后。 on_presson_release 都取消任何当前计时器(尽管 on_press 可能没有必要。

    【讨论】:

      【解决方案2】:

      您可以在 Screen 类中构建一些逻辑:

      class Screen(FloatLayout):
          def __init__(self, **kwargs):
              super(Screen, self).__init__(**kwargs)
              self.start_time = 0
              self.count = 0
      
          def change_text(self):
              time_now = time.time()
              if time_now - self.start_time > 3.0:
                  # longer than 3 seconds since first click, start over
                  self.start_time = time_now
                  self.count = 1
              else:
                  # this click within 3 seconds
                  self.count += 1
      
              if self.count == 3:
                  # 3 clicks within 3 seconds, so make the text change
                  self.ids.btn.text="some text"
                  self.count = 0
                  self.start_time = 0
      

      【讨论】:

      • 我想我在问这个问题时并不清楚。我的意思是只有在按下按钮 3 秒时才能更改文本。只是按下,而不是释放。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      相关资源
      最近更新 更多