JULIUS
JULIUS

Reputation: 121

Kivy If button is pressed for a specific time do this

I want to check how log the button(YearLabel) is touched/pressed. If the button is pressed over a specific time, I don't want to execute the logic in the "to_2020" function.

How can I achieve this? Thanks

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)

Kv:

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


Upvotes: 1

Views: 225

Answers (1)

John Anderson
John Anderson

Reputation: 38857

You can accomplish what, I believe you want, by recording the time of the on_touch_down event, and using that in the on_touch_up() method to determine whether to call the to_2020() method. If you cannot modify the YearLabel class, perhaps you can extend it Like this:

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)

and in the 'kv':

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

The on_touch_down() and on_touch_up() methods are called for you by kivy, so you don't have to mention them in the kv.

Upvotes: 1

Related Questions