Table Of Contents
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:
builtins.object
This mixin class provides
Button
behavior. Please see thebutton behaviors module
documentation for more information.- 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).
- always_release¶
This determines whether or not the widget fires an on_release event if the touch_up is outside the widget.
New in version 1.9.0.
Changed in version 1.10.0: The default value is now False.
always_release
is aBooleanProperty
and defaults to False.
- last_touch¶
Contains the last relevant touch received by the Button. This can be used in on_press or on_release in order to know which touch dispatched the event.
New in version 1.8.0.
last_touch
is aObjectProperty
and defaults to None.
- min_state_time¶
The minimum period of time which the widget must remain in the ‘down’ state.
New in version 1.9.1.
min_state_time
is a float and defaults to 0.035. This value is taken fromConfig
.
- state¶
The state of the button, must be one of ‘normal’ or ‘down’. The state is ‘down’ only when the button is currently touched/clicked, otherwise its ‘normal’.
state
is anOptionProperty
and defaults to ‘normal’.
- 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 is similar to a quick button press without using any touch events, but note that like most kivy code, this is not guaranteed to be safe to call from external threads. If needed use
Clock
to safely schedule this function and the resulting callbacks to be called from the main thread.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.
Bases:
kivy.event.EventDispatcher
Code navigation behavior. Modifies the navigation behavior in TextInput to work like an IDE instead of a word processor. Please see the
code navigation behaviors module
documentation for more information.New in version 1.9.1.
- class kivy.uix.behaviors.CompoundSelectionBehavior(**kwargs)[source]¶
Bases:
builtins.object
The Selection behavior mixin implements the logic behind keyboard and touch selection of selectable widgets managed by the derived widget. Please see the
compound selection behaviors module
documentation for more information.New in version 1.9.0.
- 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.
- keyboard_select¶
Determines whether the keyboard can be used for selection. If False, keyboard inputs will be ignored.
keyboard_select
is aBooleanProperty
and defaults to True.
- multiselect¶
Determines whether multiple nodes can be selected. If enabled, keyboard shift and ctrl selection, optionally combined with touch, for example, will be able to select multiple widgets in the normally expected manner. This dominates
touch_multiselect
when False.multiselect
is aBooleanProperty
and defaults to False.
- nodes_order_reversed¶
(Internal) Indicates whether the order of the nodes as displayed top- down is reversed compared to their order in
get_selectable_nodes()
(e.g. how the children property is reversed compared to how it’s displayed).
- page_count¶
Determines by how much the selected node is moved up or down, relative to the position of the last selected node, when pageup (or pagedown) is pressed.
page_count
is aNumericProperty
and defaults to 10.
- right_count¶
Determines by how much the selected node is moved up or down, relative to the position of the last selected node, when the right (or left) arrow on the keyboard is pressed.
right_count
is aNumericProperty
and defaults to 1.
- scroll_count¶
Determines by how much the selected node is moved up or down, relative to the position of the last selected node, when the mouse scroll wheel is scrolled.
right_count
is aNumericProperty
and defaults to 0.
- 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 received 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.
- selected_nodes¶
The list of selected nodes.
Note
Multiple nodes can be selected right after one another e.g. using the keyboard. When listening to
selected_nodes
, one should be aware of this.selected_nodes
is aListProperty
and defaults to the empty list, []. It is read-only and should not be modified.
- text_entry_timeout¶
When typing characters in rapid succession (i.e. the time difference since the last character is less than
text_entry_timeout
), the keys get concatenated and the combined text is passed as the key argument ofgoto_node()
.New in version 1.10.0.
- touch_deselect_last¶
Determines whether the last selected node can be deselected when
multiselect
ortouch_multiselect
is False.New in version 1.10.0.
touch_deselect_last
is aBooleanProperty
and defaults to True on mobile, False on desktop platforms.
- touch_multiselect¶
A special touch mode which determines whether touch events, as processed by
select_with_touch()
, will add the currently touched node to the selection, or if it will clear the selection before adding the node. This allows the selection of multiple nodes by simply touching them.This is different from
multiselect
because when it is True, simply touching an unselected node will select it, even if ctrl is not pressed. If it is False, however, ctrl must be pressed in order to add to the selection whenmultiselect
is True.Note
multiselect
, when False, will disabletouch_multiselect
.touch_multiselect
is aBooleanProperty
and defaults to False.
- up_count¶
Determines by how much the selected node is moved up or down, relative to the position of the last selected node, when the up (or down) arrow on the keyboard is pressed.
up_count
is aNumericProperty
and defaults to 1.
- class kivy.uix.behaviors.CoverBehavior(**kwargs)[source]¶
Bases:
builtins.object
The CoverBehavior mixin provides rendering a texture covering full widget size keeping aspect ratio of the original texture.
New in version 1.10.0.
- cover_pos¶
Position of the aspect ratio aware texture. Gets calculated in
CoverBehavior.calculate_cover
.cover_pos
is aListProperty
and defaults to [0, 0].
- cover_size¶
Size of the aspect ratio aware texture. Gets calculated in
CoverBehavior.calculate_cover
.cover_size
is aListProperty
and defaults to [0, 0].
- reference_size¶
Reference size used for aspect ratio approximation calculation.
reference_size
is aListProperty
and defaults to [].
- class kivy.uix.behaviors.DragBehavior(**kwargs)[source]¶
Bases:
builtins.object
The DragBehavior mixin provides Drag behavior. When combined with a widget, dragging in the rectangle defined by
drag_rectangle
will drag the widget. Please see thedrag behaviors module
documentation for more information.New in version 1.8.0.
- drag_distance¶
Distance to move before dragging the
DragBehavior
, in pixels. As soon as the distance has been traveled, theDragBehavior
will start to drag, and no touch event will be dispatched to the children. It is advisable that you base this value on the dpi of your target device’s screen.drag_distance
is aNumericProperty
and defaults to the scroll_distance as defined in the userConfig
(20 pixels by default).
- drag_rect_height¶
Height of the axis aligned bounding rectangle where dragging is allowed.
drag_rect_height
is aNumericProperty
and defaults to 100.
- drag_rect_width¶
Width of the axis aligned bounding rectangle where dragging is allowed.
drag_rect_width
is aNumericProperty
and defaults to 100.
- drag_rect_x¶
X position of the axis aligned bounding rectangle where dragging is allowed (in window coordinates).
drag_rect_x
is aNumericProperty
and defaults to 0.
- drag_rect_y¶
Y position of the axis aligned bounding rectangle where dragging is allowed (in window coordinates).
drag_rect_Y
is aNumericProperty
and defaults to 0.
- drag_rectangle¶
Position and size of the axis aligned bounding rectangle where dragging is allowed.
drag_rectangle
is aReferenceListProperty
of (drag_rect_x
,drag_rect_y
,drag_rect_width
,drag_rect_height
) properties.
- drag_timeout¶
Timeout allowed to trigger the
drag_distance
, in milliseconds. If the user has not moveddrag_distance
within the timeout, dragging will be disabled, and the touch event will be dispatched to the children.drag_timeout
is aNumericProperty
and defaults to the scroll_timeout as defined in the userConfig
(55 milliseconds by default).
- class kivy.uix.behaviors.EmacsBehavior(**kwargs)[source]¶
Bases:
builtins.object
A mixin that enables Emacs-style keyboard shortcuts for the
TextInput
widget. Please see theEmacs behaviors module
documentation for more information.New in version 1.9.1.
- key_bindings¶
String name which determines the type of key bindings to use with the
TextInput
. This allows Emacs key bindings to be enabled/disabled programmatically for widgets that inherit fromEmacsBehavior
. If the value is not'emacs'
, Emacs bindings will be disabled. Use'default'
for switching to the default key bindings of TextInput.key_bindings
is aStringProperty
and defaults to'emacs'
.New in version 1.10.0.
- class kivy.uix.behaviors.FocusBehavior(**kwargs)[source]¶
Bases:
builtins.object
Provides keyboard focus behavior. When combined with other FocusBehavior widgets it allows one to cycle focus among them by pressing tab. Please see the
focus behavior module documentation
for more information.New in version 1.9.0.
- focus¶
Whether the instance currently has focus.
Setting it to True will bind to and/or request the keyboard, and input will be forwarded to the instance. Setting it to False will unbind and/or release the keyboard. For a given keyboard, only one widget can have its focus, so focusing one will automatically unfocus the other instance holding its focus.
When using a software keyboard, please refer to the
softinput_mode
property to determine how the keyboard display is handled.focus
is aBooleanProperty
and defaults to False.
- focus_next¶
The
FocusBehavior
instance to acquire focus when tab is pressed and this instance has focus, if not None or StopIteration.When tab is pressed, focus cycles through all the
FocusBehavior
widgets that are linked throughfocus_next
and are focusable. Iffocus_next
is None, it instead walks the children lists to find the next focusable widget. Finally, iffocus_next
is the StopIteration class, focus won’t move forward, but end here.focus_next
is anObjectProperty
and defaults to None.
- focus_previous¶
The
FocusBehavior
instance to acquire focus when shift+tab is pressed on this instance, if not None or StopIteration.When shift+tab is pressed, focus cycles through all the
FocusBehavior
widgets that are linked throughfocus_previous
and are focusable. Iffocus_previous
is None, it instead walks the children tree to find the previous focusable widget. Finally, iffocus_previous
is the StopIteration class, focus won’t move backward, but end here.focus_previous
is anObjectProperty
and defaults to None.
- focused¶
An alias of
focus
.focused
is aBooleanProperty
and defaults to False.
- get_focus_next()[source]¶
Returns the next focusable widget using either
focus_next
or thechildren
similar to the order when tabbing forwards with thetab
key.
- get_focus_previous()[source]¶
Returns the previous focusable widget using either
focus_previous
or thechildren
similar to the order whentab
+shift
key are triggered together.
- ignored_touch = []¶
A list of touches that should not be used to defocus. After on_touch_up, every touch that is not in
ignored_touch
will defocus all the focused widgets if the config keyboard mode is not multi. Touches on focusable widgets that were used to focus are automatically added here.Example usage:
class Unfocusable(Widget): def on_touch_down(self, touch): if self.collide_point(*touch.pos): FocusBehavior.ignored_touch.append(touch)
Notice that you need to access this as a class, not an instance variable.
- input_type¶
The kind of input keyboard to request.
New in version 1.8.0.
Changed in version 2.1.0: Changed default value from text to null. Added null to options.
Warning
As the default value has been changed, you may need to adjust input_type in your code.
input_type
is anOptionsProperty
and defaults to ‘null’. Can be one of ‘null’, ‘text’, ‘number’, ‘url’, ‘mail’, ‘datetime’, ‘tel’ or ‘address’.
- is_focusable¶
Whether the instance can become focused. If focused, it’ll lose focus when set to False.
is_focusable
is aBooleanProperty
and defaults to True on a desktop (i.e. desktop is True inconfig
), False otherwise.
- keyboard¶
The keyboard to bind to (or bound to the widget) when focused.
When None, a keyboard is requested and released whenever the widget comes into and out of focus. If not None, it must be a keyboard, which gets bound and unbound from the widget whenever it’s in or out of focus. It is useful only when more than one keyboard is available, so it is recommended to be set to None when only one keyboard is available.
If more than one keyboard is available, whenever an instance gets focused a new keyboard will be requested if None. Unless the other instances lose focus (e.g. if tab was used), a new keyboard will appear. When this is undesired, the keyboard property can be used. For example, if there are two users with two keyboards, then each keyboard can be assigned to different groups of instances of FocusBehavior, ensuring that within each group, only one FocusBehavior will have focus, and will receive input from the correct keyboard. See keyboard_mode in
config
for more information on the keyboard modes.Keyboard and focus behavior
When using the keyboard, there are some important default behaviors you should keep in mind.
When Config’s keyboard_mode is multi, each new touch is considered a touch by a different user and will set the focus (if clicked on a focusable) with a new keyboard. Already focused elements will not lose their focus (even if an unfocusable widget is touched).
If the keyboard property is set, that keyboard will be used when the instance gets focused. If widgets with different keyboards are linked through
focus_next
andfocus_previous
, then as they are tabbed through, different keyboards will become active. Therefore, typically it’s undesirable to link instances which are assigned different keyboards.When a widget has focus, setting its keyboard to None will remove its keyboard, but the widget will then immediately try to get another keyboard. In order to remove its keyboard, rather set its
focus
to False.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.
keyboard
is anAliasProperty
and defaults to None.
- keyboard_mode¶
Determines how the keyboard visibility should be managed. ‘auto’ will result in the standard behaviour of showing/hiding on focus. ‘managed’ requires setting the keyboard visibility manually, or calling the helper functions
show_keyboard()
andhide_keyboard()
.keyboard_mode
is anOptionsProperty
and defaults to ‘auto’. Can be one of ‘auto’ or ‘managed’.
- 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).
- keyboard_suggestions¶
If True provides auto suggestions on top of keyboard. This will only work if
input_type
is set to text, url, mail or address.New in version 2.1.0.
keyboard_suggestions
is aBooleanProperty
and defaults to True
- unfocus_on_touch¶
Whether a instance should lose focus when clicked outside the instance.
When a user clicks on a widget that is focus aware and shares the same keyboard as this widget (which in the case of only one keyboard, are all focus aware widgets), then as the other widgets gains focus, this widget loses focus. In addition to that, if this property is True, clicking on any widget other than this widget, will remove focus form this widget.
unfocus_on_touch
is aBooleanProperty
and defaults to False if the keyboard_mode inConfig
is ‘multi’ or ‘systemandmulti’, otherwise it defaults to True.
- class kivy.uix.behaviors.ToggleButtonBehavior(**kwargs)[source]¶
Bases:
kivy.uix.behaviors.button.ButtonBehavior
This mixin class provides
togglebutton
behavior. Please see thetogglebutton behaviors module
documentation for more information.New in version 1.8.0.
- allow_no_selection¶
This specifies whether the widgets in a group allow no selection i.e. everything to be deselected.
New in version 1.9.0.
allow_no_selection
is aBooleanProperty
and defaults to True
- 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.
- group¶
Group of the button. If None, no group will be used (the button will be independent). If specified,
group
must be a hashable object, like a string. Only one button in a group can be in a ‘down’ state.group
is aObjectProperty
and defaults to None.
- class kivy.uix.behaviors.TouchRippleBehavior(**kwargs)[source]¶
Bases:
builtins.object
Touch ripple behavior.
Supposed to be used as mixin on widget classes.
Ripple behavior does not trigger automatically, concrete implementation needs to call
ripple_show()
respectiveripple_fade()
manually.Here we create a Label which renders the touch ripple animation on interaction:
class RippleLabel(TouchRippleBehavior, Label): def __init__(self, **kwargs): super(RippleLabel, self).__init__(**kwargs) def on_touch_down(self, touch): collide_point = self.collide_point(touch.x, touch.y) if collide_point: touch.grab(self) self.ripple_show(touch) return True return False def on_touch_up(self, touch): if touch.grab_current is self: touch.ungrab(self) self.ripple_fade() return True return False
- ripple_duration_in¶
Animation duration taken to show the overlay.
ripple_duration_in
is aNumericProperty
and defaults to 0.5.
- ripple_duration_out¶
Animation duration taken to fade the overlay.
ripple_duration_out
is aNumericProperty
and defaults to 0.2.
- ripple_fade_from_alpha¶
Alpha channel for ripple color the animation starts with.
ripple_fade_from_alpha
is aNumericProperty
and defaults to 0.5.
- ripple_fade_to_alpha¶
Alpha channel for ripple color the animation targets to.
ripple_fade_to_alpha
is aNumericProperty
and defaults to 0.8.
- ripple_func_in¶
Animation callback for showing the overlay.
ripple_func_in
is aStringProperty
and defaults to in_cubic.
- ripple_func_out¶
Animation callback for hiding the overlay.
ripple_func_out
is aStringProperty
and defaults to out_quad.
- ripple_rad_default¶
Default radius the animation starts from.
ripple_rad_default
is aNumericProperty
and defaults to 10.
- ripple_scale¶
Max scale of the animation overlay calculated from max(width/height) of the decorated widget.
ripple_scale
is aNumericProperty
and defaults to 2.0.
- class kivy.uix.behaviors.TouchRippleButtonBehavior(**kwargs)[source]¶
Bases:
kivy.uix.behaviors.touchripple.TouchRippleBehavior
This mixin class provides a similar behavior to
ButtonBehavior
but provides touch ripple animation instead of button pressed/released as visual effect.- 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).
- always_release¶
This determines whether or not the widget fires an on_release event if the touch_up is outside the widget.
always_release
is aBooleanProperty
and defaults to False.
- last_touch¶
Contains the last relevant touch received by the Button. This can be used in on_press or on_release in order to know which touch dispatched the event.
last_touch
is aObjectProperty
and defaults to None.