# First, schedule once.
event = Clock.schedule_once(my_callback, 0)
# Then, in another place you will have to unschedule first
# to avoid duplicate call. Then you can schedule again.
Clock.unschedule(event)
event = Clock.schedule_once(my_callback, 0)
trigger = Clock.create_trigger(my_callback)
# later
trigger()
每次调用 trigger() 时,它都会安排一次回调调用。如果已经安排,则不会重新安排。
小部件有两种默认类型的事件:
属性事件:如果您的小部件更改其位置或大小,则会触发一个事件。
小部件定义的事件:例如,当按钮被按下或释放时,将触发一个事件。
要创建带有自定义事件的事件派发器,您需要在类中注册事件的名称,然后创建一个同名的方法。
请参阅以下示例:
class MyEventDispatcher(EventDispatcher):
def __init__(self, **kwargs):
self.register_event_type('on_test')
super(MyEventDispatcher, self).__init__(**kwargs)
def do_something(self, value):
# when do_something is called, the 'on_test' event will be
# dispatched with the value
self.dispatch('on_test', value)
def on_test(self, *args):
print("I am dispatched", args)
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
class RootWidget(BoxLayout):
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
self.add_widget(Button(text='btn 1'))
cb = CustomBtn()
cb.bind(pressed=self.btn_pressed)
self.add_widget(cb)
self.add_widget(Button(text='btn 2'))
def btn_pressed(self, instance, pos):
print('pos: printed from root widget: {pos}'.format(pos=pos))
class CustomBtn(Widget):
pressed = ListProperty([0, 0])
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
self.pressed = touch.pos
# we consumed the touch. return False here to propagate
# the touch further to the children.
return True
return super(CustomBtn, self).on_touch_down(touch)
def on_pressed(self, instance, pos):
print('pressed at {pos}'.format(pos=pos))
class TestApp(App):
def build(self):
return RootWidget()
if __name__ == '__main__':
TestApp().run()
cursor_pos = AliasProperty(_get_cursor_pos, None,
bind=('cursor', 'padding', 'pos', 'size',
'focus', 'scroll_x', 'scroll_y',
'line_height', 'line_spacing'),
cache=True)
'''Current position of the cursor, in (x, y).
:attr:`cursor_pos` is an :class:`~kivy.properties.AliasProperty`,
read-only.
'''