Skip to content

Instantly share code, notes, and snippets.

@tshirtman
Last active October 5, 2021 09:25
Show Gist options
  • Save tshirtman/3e879c89266e639513d2f34674f65e6f to your computer and use it in GitHub Desktop.
Save tshirtman/3e879c89266e639513d2f34674f65e6f to your computer and use it in GitHub Desktop.
Simple implementation of a hold behavior for buttons.
'''
'''
from kivy.app import App
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.clock import Clock
from kivy.properties import NumericProperty
KV = '''
<HoldButton@HoldBehavior+Button>:
FloatLayout:
HoldButton:
text: 'test'
on_press: print("press")
on_hold: print("hold")
on_release: print("release")
'''
class Application(App):
def build(self):
return Builder.load_string(KV)
class HoldBehavior:
__events__ = ['on_hold']
timeout = NumericProperty(1)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._event = None
def _cancel(self):
if self._event:
self._event.cancel()
def on_press(self):
self._cancel()
self._event = Clock.schedule_once(lambda *x: self.dispatch('on_hold'), self.timeout)
return super().on_press()
def on_hold(self, *args):
pass
def on_release(self):
self._cancel()
Factory.register('HoldBehavior', cls=HoldBehavior)
if __name__ == "__main__":
Application().run()
@outdooracorn
Copy link

Thanks for this snippet, very useful 👍

I made HoldBehavior inherit from ButtonBehavior in order for this to work on widgets that don't implement the on_press() and on_release() methods:

from kivy.uix.behaviors import ButtonBehavior


class HoldBehavior(ButtonBehavior):
    __events__ = ['on_hold']
    timeout = NumericProperty(1)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._event = None

    def _cancel(self):
        if self._event:
            self._event.cancel()

    def on_press(self):
        self._cancel()
        self._event = Clock.schedule_once(lambda *x: self.dispatch('on_hold'), self.timeout)
        return super().on_press()

    def on_hold(self, *args):
        pass

    def on_release(self):
        self._cancel()


Factory.register('HoldBehavior', cls=HoldBehavior)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment