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 demonstrates 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()

When binding a function to an event, a kivy.weakmethod.WeakMethod of the callback is saved, and when dispatching the callback is removed if the callback reference becomes invalid. For properties, the actual callback is saved.

Another difference between binding to an event vs a property; when binding to a property, if this callback has already been bound to this property, it won’t be added again. For events, we don’t do this check.

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.9.0: 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/fast_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: basestring

the event name to dispatch.

Changed in version 1.9.0: 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.

fast_bind()

A method for faster binding. This method is somewhat different than bind() and is meant for more advanced users and internal usage. It can be used as long as the following points are heeded.

  • As opposed to bind(), it does not check that this function and largs/kwargs has not been bound before to this name. So binding the same callback multiple times will just keep adding it.
  • Although bind() creates a WeakMethod when binding to an event, this method stores the callback directly.
  • This method returns True if name was found and bound, and False, otherwise. It does not raise an exception, like bind(), would if the property name is not found.

When binding a callback with largs and/or kwargs, fast_unbind() must be used for unbinding. If no largs and kwargs are provided, unbind() may be used as well.

This method passes on any caught positional and/or keyword arguments to the callback, removing the need to call partial. When calling the callback the expended largs are passed on followed by instance/value (just instance for kwargs) followed by expended kwargs.

Following is an example of usage similar to the example in bind():

class DemoBox(BoxLayout):

    def __init__(self, **kwargs):
        super(DemoBox, self).__init__(**kwargs)
        self.orientation = "vertical"

        btn = Button(text="Normal binding to event")
        btn.fast_bind('on_press', self.on_event)

        btn2 = Button(text="Normal binding to a property change")
        btn2.fast_bind('state', self.on_property)

        btn3 = Button(text="A: Using function with args.")
        btn3.fast_bind('on_press', self.on_event_with_args, 'right',
                       tree='birch', food='apple')

        btn4 = Button(text="Unbind A.")
        btn4.fast_bind('on_press', self.unbind_a, btn3)

        btn5 = Button(text="Use a flexible function")
        btn5.fast_bind('on_press', self.on_anything)

        btn6 = Button(text="B: Using flexible functions with args. For hardcores.")
        btn6.fast_bind('on_press', self.on_anything, "1", "2", monthy="python")

        btn7 = Button(text="Force dispatch B with different params")
        btn7.fast_bind('on_press', btn6.dispatch, 'on_press', 6, 7, monthy="other python")

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

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

    def on_event_with_args(self, side, obj, tree=None, food=None):
        print("Event with args", obj, side, tree, food)

    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))
        return True

    def unbind_a(self, btn, event):
        btn.fast_unbind('on_press', self.on_event_with_args, 'right',
                        tree='birch', food='apple')

Note

Since the kv lang uses this method to bind, one has to implement this method, instead of bind() when creating a non EventDispatcher based class used with the kv lang. See Observable for an example.

New in version 1.9.0.

fast_unbind()

Similar to fast_bind().

When unbinding from a property unbind() will unbind all callbacks that match the callback, while this method will only unbind the first (as it is assumed that the combination of func and largs/kwargs are uniquely bound).

To unbind, the same positional and keyword arguments passed to fast_bind() must be passed on to fast_unbind.

New in version 1.9.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.

Changed in version 1.9.0: To keep compatibility, callbacks bound with fast_bind() will also only return the callback function and not their provided args.

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 property name. If quiet is True, None is returned instead of raising an exception when name is not a property. Defaults to False.

New in version 1.0.9.

Returns:A Property derived instance corresponding to the name.

Changed in version 1.9.0: quiet was added.

proxy_ref

Default implementation of proxy_ref, returns self. ..versionadded:: 1.9.0

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 with similar usage as bind().

One difference between unbinding from an event vs. property, is that when unbinding from an event, we stop after the first callback match. For properties, we remove all matching callbacks.

Note, a callback bound with fast_bind() without any largs or kwargs is equivalent to one bound with bind() so either unbind() or fast_unbind() will unbind it.

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.

class kivy.event.Observable

Bases: kivy.event.ObjectWithUid

Observable is a stub class defining the methods required for binding. EventDispatcher is (the) one example of a class that implements the binding interface. See EventDispatcher for details.

New in version 1.9.0.

fast_bind()

See EventDispatcher.fast_bind().

Note

To keep backward compatibility with derived classes which may have inherited from Observable before, the fast_bind() method was added. The default implementation of fast_bind() and fast_unbind() is to create a partial function that it passes to bind. However, fast_unbind() is fairly inefficient since we have to lookup this partial function before we can call unbind(). It is recommended to overwrite these methods in derived classes to bind directly for better performance.

fast_unbind()

See fast_bind().