Kivy如果按钮被按下一段特定时间,请执行此操作

2024-06-17 12:16:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查一下按钮(YearLabel)是如何触摸/按下的。如果在特定时间按下按钮,我不想执行“to_2020”功能中的逻辑

我怎样才能做到这一点? 谢谢

Python:

  def on_touch_down(self, touch):
        # if button is pressed for this time don't execute "to_2020"-logic

    def to_2020(self):
        layout = self.ids.years_layout
        anim_to_2020 = Animation(pos=(0,-2900),duration=0.25)
        label_2020 = self.ids.label_2020
        anim_white_2020 = Animation(color=(1,1,1,1),duration=0.25)
        anim_to_2020.start(layout)
        anim_white_2020.start(label_2020)

千伏:

        YearLabel:
            id: label_2020
            text: "2020"
            font_size: "150sp"
            color: 1,1,1,1
            on_touch_down:
                self.collide_point(*args[1].pos) and root.on_touch_down()
            on_touch_up:
                self.collide_point(*args[1].pos) and root.to_2020()



1条回答
网友
1楼 · 发布于 2024-06-17 12:16:43

我相信,通过记录on_touch_down事件的时间,并在on_touch_up()方法中使用该时间来确定是否调用to_2020()方法,您可以完成您想要的任务。如果无法修改YearLabel类,或许可以像这样扩展它:

class MyYearLabel(YearLabel):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.time = time()
        return super(MyYearLabel, self).on_touch_down(touch)

    def on_touch_up(self, touch):
        if self.collide_point(*touch.pos):
            length_of_press = time() - self.time
            if length_of_press > 2:
                self.to_2020()
        return super(MyYearLabel, self).on_touch_up(touch)

    def to_2020(self):
        layout = self.ids.years_layout
        anim_to_2020 = Animation(pos=(0, -2900), duration=0.25)
        label_2020 = self.ids.label_2020
        anim_white_2020 = Animation(color=(1, 1, 1, 1), duration=0.25)
        anim_to_2020.start(layout)
        anim_white_2020.start(label_2020)

在“kv”中:

MyYearLabel:
    id: label_2020
    text: "2020"
    font_size: "150sp"
    color: 1,1,1,1

kivy为您调用了on_touch_down()on_touch_up()方法,因此您不必在kv中提及它们

相关问题 更多 >