Quick search

Behaviors

New in version 1.8.0.

Behavior mixin classes

This module implements behaviors that can be mixed in with existing base widgets. The idea behind these classes is to encapsulate properties and events associated with certain types of widgets.

Isolating these properties and events in a mixin class allows you to define your own implementation for standard kivy widgets that can act as drop-in replacements. This means you can re-style and re-define widgets as desired without breaking compatibility: as long as they implement the behaviors correctly, they can simply replace the standard widgets.

Adding behaviors

Say you want to add Button capabilities to an Image, you could do:

class IconButton(ButtonBehavior, Image):
    pass

This would give you an Image with the events and properties inherited from ButtonBehavior. For example, the on_press and on_release events would be fired when appropriate:

class IconButton(ButtonBehavior, Image):
    def on_press(self):
        print("on_press")

Or in kv:

IconButton:
    on_press: print('on_press')

Naturally, you could also bind to any property changes the behavior class offers:

def state_changed(*args):
    print('state changed')

button = IconButton()
button.bind(state=state_changed)

Note

The behavior class must always be _before_ the widget class. If you don’t specify the inheritance in this order, the behavior will not work because the behavior methods are overwritten by the class method listed first.

Similarly, if you combine a behavior class with a class which requires the use of the methods also defined by the behavior class, the resulting class may not function properly. For example, when combining the ButtonBehavior with a Slider, both of which use the on_touch_up() method, the resulting class may not work properly.

Changed in version 1.9.1: The individual behavior classes, previously in one big behaviors.py file, has been split into a single file for each class under the behaviors module. All the behaviors are still imported in the behaviors module so they are accessible as before (e.g. both from kivy.uix.behaviors import ButtonBehavior and from kivy.uix.behaviors.button import ButtonBehavior work).

class kivy.uix.behaviors.ButtonBehavior(**kwargs)[source]

Bases: object

This mixin class provides Button behavior.

Events:
on_press

Fired when the button is pressed.

on_release

Fired when the button is released (i.e. the touch/click that pressed the button goes away).

trigger_action(duration=0.1)[source]

Trigger whatever action(s) have been bound to the button by calling both the on_press and on_release callbacks.

This simulates a quick button press without using any touch events.

Duration is the length of the press in seconds. Pass 0 if you want the action to happen instantly.

New in version 1.8.0.

class kivy.uix.behaviors.ToggleButtonBehavior(**kwargs)[source]

Bases: kivy.uix.behaviors.button.ButtonBehavior

This mixin class provides ToggleButton behavior. Please see the togglebutton module documentation for more information.

New in version 1.8.0.

static get_widgets(groupname)[source]

Return a list of the widgets contained in a specific group. If the group doesn’t exist, an empty list will be returned.

Note

Always release the result of this method! Holding a reference to any of these widgets can prevent them from being garbage collected. If in doubt, do:

l = ToggleButtonBehavior.get_widgets('mygroup')
# do your job
del l

Warning

It’s possible that some widgets that you have previously deleted are still in the list. The garbage collector might need to release other objects before flushing them.

class kivy.uix.behaviors.DragBehavior(**kwargs)[source]

Bases: object

This mixin class provides Drag behavior. When combined with a widget, dragging in the rectangle defined by drag_rectangle will drag the widget.

For example, to make a popup which is draggable by its title do:

from kivy.uix.behaviors import DragBehavior
from kivy.uix.popup import Popup

class DragPopup(DragBehavior, Popup):
    pass

And in .kv do:

<DragPopup>:
    drag_rectangle: self.x, self.y+self._container.height, self.width,            self.height - self._container.height
    drag_timeout: 10000000
    drag_distance: 0

New in version 1.8.0.

class kivy.uix.behaviors.FocusBehavior(**kwargs)[source]

Bases: object

This mixin class provides keyboard focus behavior. When combined with other FocusBehavior widgets it allows one to cycle focus among them by pressing tab. In addition, upon gaining focus, the instance will automatically receive keyboard input.

Focus, very different from selection, is intimately tied with the keyboard; each keyboard can focus on zero or one widgets, and each widget can only have the focus of one keyboard. However, multiple keyboards can focus simultaneously on different widgets. When escape is hit, the widget having the focus of that keyboard will de-focus.

In essence, focus is implemented as a doubly linked list, where each node holds a (weak) reference to the instance before it and after it, as visualized when cycling through the nodes using tab (forward) or shift+tab (backward). If a previous or next widget is not specified, focus_next and focus_previous defaults to None. This means that the children list and parents are walked to find the next focusable widget, unless focus_next or focus_previous is set to the StopIteration class, in which case focus stops there.

For example, to cycle focus between Button elements of a GridLayout:

class FocusButton(FocusBehavior, Button):
    pass

grid = GridLayout(cols=4)
for i in range(40):
    grid.add_widget(FocusButton(text=str(i)))
# clicking on a widget will activate focus, and tab can now be used
# to cycle through

When using a software keyboard, typical on mobile and touch devices, the keyboard display behavior is determined by the softinput_mode property. You can use this property to ensure the focused widget is not covered or obscured by the keyboard.

New in version 1.9.0.

Warning

This code is still experimental, and its API is subject to change in a future version.

hide_keyboard()[source]

Convenience function to hide the keyboard in managed mode.

keyboard_on_key_down(window, keycode, text, modifiers)[source]

The method bound to the keyboard when the instance has focus.

When the instance becomes focused, this method is bound to the keyboard and will be called for every input press. The parameters are the same as kivy.core.window.WindowBase.on_key_down().

When overwriting the method in the derived widget, super should be called to enable tab cycling. If the derived widget wishes to use tab for its own purposes, it can call super after it has processed the character (if it does not wish to consume the tab).

Similar to other keyboard functions, it should return True if the key was consumed.

keyboard_on_key_up(window, keycode)[source]

The method bound to the keyboard when the instance has focus.

When the instance becomes focused, this method is bound to the keyboard and will be called for every input release. The parameters are the same as kivy.core.window.WindowBase.on_key_up().

When overwriting the method in the derived widget, super should be called to enable de-focusing on escape. If the derived widget wishes to use escape for its own purposes, it can call super after it has processed the character (if it does not wish to consume the escape).

See keyboard_on_key_down()

show_keyboard()[source]

Convenience function to show the keyboard in managed mode.

class kivy.uix.behaviors.CompoundSelectionBehavior(**kwargs)[source]

Bases: object

The Selection behavior mixin implements the logic behind keyboard and touch selection of selectable widgets managed by the derived widget. For example, it could be combined with a GridLayout to add selection to the layout.

At its core, it keeps a dynamic list of widgets that can be selected. Then, as the touches and keyboard input are passed in, it selects one or more of the widgets based on these inputs. For example, it uses the mouse scroll and keyboard up/down buttons to scroll through the list of widgets. Multiselection can also be achieved using the keyboard shift and ctrl keys. Finally, in addition to the up/down type keyboard inputs, it can also accepts letters from the kayboard to be used to select nodes with associated strings that start with those letters, similar to how files are selected by a file browser.

When the controller needs to select a node it calls select_node() and deselect_node(). Therefore, they must be overwritten in order affect the selected nodes. By default, the class doesn’t listen to keyboard and touch events, therefore, the derived widget must call select_with_touch(), select_with_key_down(), and select_with_key_up() on events that it wants to pass on for selection purposes.

For example, to add selection to a grid layout which will contain Button widgets:

class SelectableGrid(CompoundSelectionBehavior, GridLayout):

    def __init__(self, **kwargs):
        super(CompoundSelectionBehavior, self).__init__(**kwargs)
        keyboard = Window.request_keyboard(None, self)
        keyboard.bind(on_key_down=self.select_with_key_down,
        on_key_up=self.select_with_key_up)

    def select_node(self, node):
        node.background_color = (1, 0, 0, 1)
        return super(CompoundSelectionBehavior, self).select_node(node)

    def deselect_node(self, node):
        node.background_color = (1, 1, 1, 1)
        super(CompoundSelectionBehavior, self).deselect_node(node)

Then, for each button added to the layout, bind on_touch_down of the button to select_with_touch() to pass on the touch events.

New in version 1.9.0.

Warning

This code is still experimental, and its API is subject to change in a future version.

clear_selection()[source]

Deselects all the currently selected nodes.

deselect_node(node)[source]

Deselects a possibly selected node.

It is called by the controller when it deselects a node and can also be called from the outside to deselect a node directly. The derived widget should overwrite this method and change the node to its unselected state when this is called

Parameters:
node

The node to be deselected.

Warning

This method must be called by the derived widget using super if it is overwritten.

get_index_of_node(node, selectable_nodes)[source]

(internal) Returns the index of the node within the selectable_nodes returned by get_selectable_nodes().

get_selectable_nodes()[source]

(internal) Returns a list of the nodes that can be selected. It can be overwritten by the derived widget to return the correct list.

This list is used to determine which nodes to select with group selection. E.g. the last element in the list will be selected when home is pressed, pagedown will move (or add to, if shift is held) the selection from the current position by negative page_count nodes starting from the position of the currently selected node in this list and so on. Still, nodes can be selected even if they are not in this list.

Note

It is safe to dynamically change this list including removing, adding, or re-arranging its elements. Nodes can be selected even if they are not on this list. And selected nodes removed from the list will remain selected until deselect_node() is called.

Warning

Layouts display their children in the reverse order. That is, the contents of children is displayed form right to left, bottom to top. Therefore, internally, the indices of the elements returned by this function are reversed to make it work by default for most layouts so that the final result is consistent e.g. home, although it will select the last element in this list visually, will select the first element when counting from top to bottom and left to right. If this behavior is not desired, a reversed list should be returned instead.

Defaults to returning children.

goto_node(key, last_node, last_node_idx)[source]

(internal) Used by the controller to get the node at the position indicated by key. The key can be keyboard inputs, e.g. pageup, or scroll inputs from the mouse scroll wheel, e.g. scrollup. ‘last_node’ is the last node selected and is used to find the resulting node. For example, if the key is up, the returned node is one node up from the last node.

It can be overwritten by the derived widget.

Parameters:
key

str, the string used to find the desired node. It can be any of the keyboard keys, as well as the mouse scrollup, scrolldown, scrollright, and scrollleft strings. If letters are typed in quick succession, the letters will be combined before it’s passed in as key and can be used to find nodes that have an associated string that starts with those letters.

last_node

The last node that was selected.

last_node_idx

The cached index of the last node selected in the get_selectable_nodes() list. If the list hasn’t changed it saves having to look up the index of last_node in that list.

Returns:

tuple, the node targeted by key and its index in the get_selectable_nodes() list. Returning (last_node, last_node_idx) indicates a node wasn’t found.

select_node(node)[source]

Selects a node.

It is called by the controller when it selects a node and can be called from the outside to select a node directly. The derived widget should overwrite this method and change the node state to selected when called.

Parameters:
node

The node to be selected.

Returns:

bool, True if the node was selected, False otherwise.

Warning

This method must be called by the derived widget using super if it is overwritten.

select_with_key_down(keyboard, scancode, codepoint, modifiers, **kwargs)[source]

Processes a key press. This is called when a key press is to be used for selection. Depending on the keyboard keys pressed and the configuration, it could select or deselect nodes or node ranges from the selectable nodes list, get_selectable_nodes().

The parameters are such that it could be bound directly to the on_key_down event of a keyboard. Therefore, it is safe to be called repeatedly when the key is held down as is done by the keyboard.

Returns:bool, True if the keypress was used, False otherwise.
select_with_key_up(keyboard, scancode, **kwargs)[source]

(internal) Processes a key release. This must be called by the derived widget when a key that select_with_key_down() returned True is released.

The parameters are such that it could be bound directly to the on_key_up event of a keyboard.

Returns:bool, True if the key release was used, False otherwise.
select_with_touch(node, touch=None)[source]

(internal) Processes a touch on the node. This should be called by the derived widget when a node is touched and is to be used for selection. Depending on the keyboard keys pressed and the configuration, it could select or deslect this and other nodes in the selectable nodes list, get_selectable_nodes().

Parameters:
node

The node that recieved the touch. Can be None for a scroll type touch.

touch

Optionally, the touch. Defaults to None.

Returns:

bool, True if the touch was used, False otherwise.

class kivy.uix.behaviors.CodeNavigationBehavior[source]

Bases: kivy.event.EventDispatcher

Code navigation behavior. Modifies navigation behavior in TextInput work like an IDE instead of a word processor.

New in version 1.9.1.

class kivy.uix.behaviors.EmacsBehavior(**kwargs)[source]

Bases: object

A mixin that enables Emacs-style keyboard shortcuts for the TextInput widget.

delete_word_left()[source]

Delete text left of the cursor to the beginning of word

delete_word_right()[source]

Delete text right of the cursor to the end of the word