Quick search

Table Of Contents

Event dispatcher

All objects that produce events in Kivy implement the EventDispatcher which provides a consistent interface for registering and manipulating event handlers.

Changed in version 1.0.9: Property discovery and methods have been moved from the Widget to the EventDispatcher.

class kivy.event.EventDispatcher

Bases: kivy.event.ObjectWithUid

Generic event dispatcher interface.

See the module docstring for usage.

bind()

Bind an event type or a property to a callback.

Usage:

# With properties
def my_x_callback(obj, value):
    print('on object', obj, 'x changed to', value)
def my_width_callback(obj, value):
    print('on object', obj, 'width changed to', value)
self.bind(x=my_x_callback, width=my_width_callback)

# With event
def my_press_callback(obj):
    print('event on object', obj)
self.bind(on_press=my_press_callback)

In general, property callbacks are called with 2 arguments (the object and the property’s new value) and event callbacks with one argument (the object). The example above illustrates this.

The following example demonstates various ways of using the bind function in a complete application:

from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.uix.button import Button
from functools import partial


class DemoBox(BoxLayout):
    """
    This class demonstrates various techniques that can be used for binding to
    events. Although parts could me made more optimal, advanced Python concepts
    are avoided for the sake of readability and clarity.
    """
    def __init__(self, **kwargs):
        super(DemoBox, self).__init__(**kwargs)
        self.orientation = "vertical"

        # We start with binding to a normal event. The only argument
        # passed to the callback is the object which we have bound to.
        btn = Button(text="Normal binding to event")
        btn.bind(on_press=self.on_event)

        # Next, we bind to a standard property change event. This typically
        # passes 2 arguments: the object and the value
        btn2 = Button(text="Normal binding to a property change")
        btn2.bind(state=self.on_property)

        # Here we use anonymous functions (a.k.a lambdas) to perform binding.
        # Their advantage is that you can avoid declaring new functions i.e.
        # they offer a concise way to "redirect" callbacks.
        btn3 = Button(text="Using anonymous functions.")
        btn3.bind(on_press=lambda x: self.on_event(None))

        # You can also declare a function that accepts a variable number of
        # positional and keyword arguments and use introspection to determine
        # what is being passed in. This is very handy for debugging as well
        # as function re-use. Here, we use standard event binding to a function
        # that accepts optional positional and keyword arguments.
        btn4 = Button(text="Use a flexible function")
        btn4.bind(on_press=self.on_anything)

        # Lastly, we show how to use partial functions. They are sometimes
        # difficult to grasp, but provide a very flexible and powerful way to
        # reuse functions.
        btn5 = Button(text="Using partial functions. For hardcores.")
        btn5.bind(on_press=partial(self.on_anything, "1", "2", monthy="python"))

        for but in [btn, btn2, btn3, btn4, btn5]:
            self.add_widget(but)

    def on_event(self, obj):
        print("Typical event from", obj)

    def on_property(self, obj, value):
        print("Typical property change from", obj, "to", value)

    def on_anything(self, *args, **kwargs):
        print('The flexible function has *args of', str(args),
            "and **kwargs of", str(kwargs))


class DemoApp(App):
    def build(self):
        return DemoBox()

if __name__ == "__main__":
    DemoApp().run()
create_property()

Create a new property at runtime.

New in version 1.0.9.

Changed in version 1.8.0: value parameter added, can be used to set the default value of the property. Also, the type of the value is used to specialize the created property.

Changed in version 1.8.1: In the past, if value was of type bool, a NumericProperty would be created, now a BooleanProperty is created.

Warning

This function is designed for the Kivy language, don’t use it in your code. You should declare the property in your class instead of using this method.

Parameters :
name: string

Name of the property

value: object, optional

Default value of the property. Type is also used for creating more appropriate property types. Defaults to None.

>>> mywidget = Widget()
>>> mywidget.create_property('custom')
>>> mywidget.custom = True
>>> print(mywidget.custom)
True
dispatch()

Dispatch an event across all the handlers added in bind(). As soon as a handler returns True, the dispatching stops.

The function collects all the positional and keyword arguments and passes them on to the handlers.

Note

The handlers are called in reverse order than they were registered with bind().

Parameters :
event_type: str

the event name to dispatch.

Changed in version 1.8.1: Keyword arguments collection and forwarding was added. Before, only positional arguments would be collected and forwarded.

events()

Return all the events in the class. Can be used for introspection.

New in version 1.8.0.

get_property_observers()

Returns a list of methods that are bound to the property/event passed as the name argument:

widget_instance.get_property_observers('on_release')

New in version 1.8.0.

getter()

Return the getter of a property.

New in version 1.0.9.

is_event_type()

Return True if the event_type is already registered.

New in version 1.0.4.

properties()

Return all the properties in the class in a dictionary of key/property class. Can be used for introspection.

New in version 1.0.9.

property()

Get a property instance from the name.

New in version 1.0.9.

Returns:A Property derived instance corresponding to the name.
register_event_type()

Register an event type with the dispatcher.

Registering event types allows the dispatcher to validate event handler names as they are attached and to search attached objects for suitable handlers. Each event type declaration must:

  1. start with the prefix on_.
  2. have a default handler in the class.

Example of creating a custom event:

class MyWidget(Widget):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.register_event_type('on_swipe')

    def on_swipe(self):
        pass

def on_swipe_callback(*largs):
    print('my swipe is called', largs)
w = MyWidget()
w.dispatch('on_swipe')
setter()

Return the setter of a property. Use: instance.setter(‘name’). The setter is a convenient callback function useful if you want to directly bind one property to another. It returns a partial function that will accept (obj, value) args and results in the property ‘name’ of instance being set to value.

New in version 1.0.9.

For example, to bind number2 to number1 in python you would do:

class ExampleWidget(Widget):
    number1 = NumericProperty(None)
    number2 = NumericProperty(None)

    def __init__(self, **kwargs):
        super(ExampleWidget, self).__init__(**kwargs)
        self.bind(number1=self.setter('number2'))

This is equivalent to kv binding:

<ExampleWidget>:
    number2: self.number1
unbind()

Unbind properties from callback functions.

Same usage as bind().

unregister_event_types()

Unregister an event type in the dispatcher.

class kivy.event.ObjectWithUid

Bases: object

(internal) This class assists in providing unique identifiers for class instances. It it not intended for direct usage.