from
kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty, BooleanProperty, StringProperty
from kivy.factory import Factory
class ButtonBehavior(object):
'''Button behavior.
:Events:
`on_press`:
Fired when a touch is pressing the widget
`on_release`:
Fired when the first touch is up
'''
is_hover = BooleanProperty(False)
button_grab = BooleanProperty(False)
button_touch = ObjectProperty(None, allownone=True)
state = StringProperty('normal')
def __init__(self, **kwargs):
super(ButtonBehavior, self).__init__(**kwargs)
self.register_event_type('on_press')
self.register_event_type('on_release')
self.bind(
on_touch_down=self._button_on_touch_down,
on_touch_up=self._button_on_touch_up)
self.state = 'normal'
def on_press(self, touch):
pass
def on_release(self, touch):
pass
def _button_on_touch_down(self, instance, touch):
if not self.collide_point(*touch.pos):
return
touch.ungrab(self)
touch.grab(self)
self.is_hover = True
self.button_touch = touch
self.state = 'down'
self.dispatch('on_press', touch)
return self.button_grab
def _button_on_touch_up(self, instance, touch):
if touch.grab_current is not self:
return
touch.ungrab(self)
self.is_hover = False
self.dispatch('on_release', touch)
self.state = 'normal'
self.button_touch = None
return self.button_grab
Factory.register('ButtonBehavior', cls=ButtonBehavior)
Builder.load_string('''
[UrlBut@ButtonBehavior+AsyncImage]:
source: ctx.source
button_grab: True
on_press: self.parent.pressed(*args)
on_release: self.parent.released(*args)
color: (1, 1, 1, 1) if self.state == 'normal' else (1, 0, 1 , 1)
<MyApp>:
UrlBut:
source: '
http://icons.iconseeker.com/png/fullsize/summer-collection/button.png'
UrlBut:
source: '
http://icons.iconseeker.com/png/fullsize/summer-collection/button.png'
''')
class MyApp(BoxLayout):
def pressed(self, button, touch):
print 'button [' + str(button)+'] pressed'
def released(self, button, *touch):
print 'button [' + str(button)+'] released'
class MyTestApp(App):
def build(self):
return MyApp()
if __name__ == '__main__':
MyTestApp().run()