Last active
October 5, 2021 09:25
-
-
Save tshirtman/3e879c89266e639513d2f34674f65e6f to your computer and use it in GitHub Desktop.
Simple implementation of a hold behavior for buttons.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
''' | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this snippet, very useful 👍
I made
HoldBehavior
inherit fromButtonBehavior
in order for this to work on widgets that don't implement theon_press()
andon_release()
methods: