Table Of Contents
- Behaviors
- Behavior mixin classes
- Adding behaviors
ButtonBehaviorCodeNavigationBehaviorCompoundSelectionBehaviorCompoundSelectionBehavior.clear_selection()CompoundSelectionBehavior.deselect_node()CompoundSelectionBehavior.get_index_of_node()CompoundSelectionBehavior.get_selectable_nodes()CompoundSelectionBehavior.goto_node()CompoundSelectionBehavior.keyboard_selectCompoundSelectionBehavior.multiselectCompoundSelectionBehavior.nodes_order_reversedCompoundSelectionBehavior.page_countCompoundSelectionBehavior.right_countCompoundSelectionBehavior.scroll_countCompoundSelectionBehavior.select_node()CompoundSelectionBehavior.select_with_key_down()CompoundSelectionBehavior.select_with_key_up()CompoundSelectionBehavior.select_with_touch()CompoundSelectionBehavior.selected_nodesCompoundSelectionBehavior.text_entry_timeoutCompoundSelectionBehavior.touch_deselect_lastCompoundSelectionBehavior.touch_multiselectCompoundSelectionBehavior.up_count
CoverBehaviorDragBehaviorEmacsBehaviorFocusBehaviorFocusBehavior.focusFocusBehavior.focus_nextFocusBehavior.focus_previousFocusBehavior.focusedFocusBehavior.get_focus_next()FocusBehavior.get_focus_previous()FocusBehavior.hide_keyboard()FocusBehavior.ignored_touchFocusBehavior.input_typeFocusBehavior.is_focusableFocusBehavior.keyboardFocusBehavior.keyboard_modeFocusBehavior.keyboard_on_key_down()FocusBehavior.keyboard_on_key_up()FocusBehavior.keyboard_suggestionsFocusBehavior.show_keyboard()FocusBehavior.unfocus_on_touch
HoverBehaviorHoverCollideBehaviorKNSpaceBehaviorToggleButtonBehaviorTouchRippleBehaviorTouchRippleBehavior.ripple_duration_inTouchRippleBehavior.ripple_duration_outTouchRippleBehavior.ripple_fade()TouchRippleBehavior.ripple_fade_from_alphaTouchRippleBehavior.ripple_fade_to_alphaTouchRippleBehavior.ripple_func_inTouchRippleBehavior.ripple_func_outTouchRippleBehavior.ripple_rad_defaultTouchRippleBehavior.ripple_scaleTouchRippleBehavior.ripple_show()
TouchRippleButtonBehavior
Behaviors¶
Added 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:
objectMixin to add button behavior to any Kivy widget.
This mixin enables widgets to respond to press/release interactions with automatic multi-touch support. It provides three specialized events:
on_press(),on_release(), andon_cancel(), along with a reactivepressedproperty.Multi-Touch Behavior¶
The button automatically handles multiple simultaneous touches:
First touch down: Triggers
on_press(), setspressedto TrueAdditional touches: Tracked but don’t trigger
on_press()againTouch release: Only triggers
on_release()after ALL touches releasedTouch cancel: Removes touch from tracking, updates
pressedstate
Release Modes¶
Controlled by
always_releaseproperty:False (default): Standard button behavior.
on_release()only fires if touch ends within button bounds.on_cancel()fires when touch moves outside bounds during drag (touch move).True: Always fires
on_release()regardless of touch position.on_cancel()never fires. Useful for drag-and-drop or gesture-based interfaces.
Events¶
on_press()First touch down on button
on_release()All touches released (respects
always_releasemode)on_cancel()- Touch moved outside bounds during drag (only when
always_release is False)
- Touch moved outside bounds during drag (only when
Changed in version 3.0.0: - Replaced
stateOptionProperty withpressedBooleanProperty - Madepressedread-only via AliasProperty - Addedon_cancel()event - Improved multi-touch handling with explicit touch sets - Added touch argument to on_press, on_release, and on_cancel events- always_release¶
Determines whether the widget fires
on_release()when touch ends outside widget bounds.- When False (default):
on_release()only fires if touch ends within button boundson_cancel()fires when touch moves outside bounds during dragProvides standard button behavior with cancellation feedback
- When True:
on_release()always fires regardless of final touch positionon_cancel()never firesUseful for drag-and-drop or gesture-based interfaces where release position is irrelevant
always_releaseis aBooleanPropertyand defaults to False.Added in version 1.9.0.
Changed in version 1.10.0: The default value changed from True to False.
- on_cancel(touch)[source]¶
Event handler called when touch leaves button bounds during drag.
This event is only fired when always_release is False and a touch moves outside the button’s bounds during a drag operation. It provides an opportunity to give visual feedback that the button action has been cancelled.
Use this to restore the button’s original appearance or cancel any pending actions that would have occurred on release.
- Parameters:
touch – The
MotionEventthat moved outside the button bounds. Access touch.pos to get the position where the touch left the bounds.
Example:
def on_cancel(self, touch): print(f"Action cancelled at position: {touch.pos}") self.background_color = [1, 1, 1, 1] # Reset appearance
Added in version 3.0.0.
- on_press(touch)[source]¶
Event handler called when the button is pressed.
This event is fired when the first touch down occurs on the button. In multi-touch scenarios, only the first touch triggers this event.
- Parameters:
touch – The
MotionEventthat triggered the press. Contains position (touch.x, touch.y), timestamp, and other touch attributes.
Example:
def on_press(self, touch): print(f"Pressed at position: {touch.pos}") print(f"Touch ID: {touch.id}")
- on_release(touch)[source]¶
Event handler called when the button is released.
This event is fired when the last active touch is released, and only if: - The touch is released within button bounds, OR - The always_release property is True
- Parameters:
touch – The
MotionEventof the last touch being released. In multi-touch scenarios, this is the touch that completed the release action.
Example:
def on_release(self, touch): print(f"Released at position: {touch.pos}") duration = touch.time_end - touch.time_start print(f"Touch duration: {duration:.2f}s")
- on_touch_down(touch)[source]¶
Handle touch down events.
Implements core press detection:
Test collision with widget bounds
Grab touch if colliding (marks widget as touch owner)
Add to active touches tracking
Dispatch
on_press()on first touch
- Parameters:
touch –
MotionEventinstance- Returns:
True if event was handled (collided with widget)
- on_touch_move(touch)[source]¶
Handle touch move events.
Detects when touch moves outside button bounds during drag and triggers cancellation if
always_releaseis False.Cancellation flow: 1. Touch owned by this widget moves outside bounds 2. Remove from active touches, add to cancelled touches 3. Dispatch
on_cancel()if this was the last active touch- Parameters:
touch –
MotionEventinstance- Returns:
True if event was handled
- on_touch_up(touch) bool[source]¶
Handle touch up events.
Implements release detection:
Verify we own this touch
Ungrab touch to release ownership
Remove from active/cancelled tracking
Dispatch
on_release()if appropriate: - Touch wasn’t cancelled, AND - (Touch ended within bounds ORalways_releaseis True), AND - This was the last active touch
- Parameters:
touch –
MotionEventinstance- Returns:
True if event was handled
- pressed¶
Read-only boolean indicating if button is currently pressed.
The button is pressed only when currently touched/clicked. This property automatically handles multi-touch scenarios, remaining True as long as at least one active touch is on the button.
Updates automatically as touches are added/removed from
_active_touches.pressedis anAliasPropertyand defaults to False.Changed in version 3.0.0: Changed from editable BooleanProperty to read-only AliasProperty
Bases:
EventDispatcherCode navigation behavior. Modifies the navigation behavior in TextInput to work like an IDE instead of a word processor. Please see the
code navigation behaviors moduledocumentation for more information.Added in version 1.9.1.
- class kivy.uix.behaviors.CompoundSelectionBehavior(**kwargs)[source]¶
Bases:
objectThe 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 moduledocumentation for more information.Added 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_countnodes 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
childrenis 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_selectis aBooleanPropertyand 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_multiselectwhen False.multiselectis aBooleanPropertyand 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_countis aNumericPropertyand 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_countis aNumericPropertyand 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_countis aNumericPropertyand 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_nodesis aListPropertyand 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().Added in version 1.10.0.
- touch_deselect_last¶
Determines whether the last selected node can be deselected when
multiselectortouch_multiselectis False.Added in version 1.10.0.
touch_deselect_lastis aBooleanPropertyand 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
multiselectbecause 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 whenmultiselectis True.Note
multiselect, when False, will disabletouch_multiselect.touch_multiselectis aBooleanPropertyand 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_countis aNumericPropertyand defaults to 1.
- class kivy.uix.behaviors.CoverBehavior(**kwargs)[source]¶
Bases:
objectThe CoverBehavior mixin provides rendering a texture covering full widget size keeping aspect ratio of the original texture.
Added in version 1.10.0.
- cover_pos¶
Position of the aspect ratio aware texture. Gets calculated in
CoverBehavior.calculate_cover.cover_posis aListPropertyand defaults to [0, 0].
- cover_size¶
Size of the aspect ratio aware texture. Gets calculated in
CoverBehavior.calculate_cover.cover_sizeis aListPropertyand defaults to [0, 0].
- reference_size¶
Reference size used for aspect ratio approximation calculation.
reference_sizeis aListPropertyand defaults to [].
- class kivy.uix.behaviors.DragBehavior(**kwargs)[source]¶
Bases:
objectThe DragBehavior mixin provides Drag behavior. When combined with a widget, dragging in the rectangle defined by
drag_rectanglewill drag the widget. Please see thedrag behaviors moduledocumentation for more information.Added in version 1.8.0.
- drag_distance¶
Distance to move before dragging the
DragBehavior, in pixels. As soon as the distance has been traveled, theDragBehaviorwill 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_distanceis aNumericPropertyand 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_heightis aNumericPropertyand defaults to 100.
- drag_rect_width¶
Width of the axis aligned bounding rectangle where dragging is allowed.
drag_rect_widthis aNumericPropertyand defaults to 100.
- drag_rect_x¶
X position of the axis aligned bounding rectangle where dragging is allowed (in window coordinates).
drag_rect_xis aNumericPropertyand defaults to 0.
- drag_rect_y¶
Y position of the axis aligned bounding rectangle where dragging is allowed (in window coordinates).
drag_rect_Yis aNumericPropertyand defaults to 0.
- drag_rectangle¶
Position and size of the axis aligned bounding rectangle where dragging is allowed.
drag_rectangleis aReferenceListPropertyof (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_distancewithin the timeout, dragging will be disabled, and the touch event will be dispatched to the children.drag_timeoutis aNumericPropertyand defaults to the scroll_timeout as defined in the userConfig(55 milliseconds by default).
- class kivy.uix.behaviors.EmacsBehavior(**kwargs)[source]¶
Bases:
objectA mixin that enables Emacs-style keyboard shortcuts for the
TextInputwidget. Please see theEmacs behaviors moduledocumentation for more information.Added 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_bindingsis aStringPropertyand defaults to'emacs'.Added in version 1.10.0.
- class kivy.uix.behaviors.FocusBehavior(**kwargs)[source]¶
Bases:
objectProvides 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 documentationfor more information.Added 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_modeproperty to determine how the keyboard display is handled.focusis aBooleanPropertyand defaults to False.
- focus_next¶
The
FocusBehaviorinstance 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
FocusBehaviorwidgets that are linked throughfocus_nextand are focusable. Iffocus_nextis None, it instead walks the children lists to find the next focusable widget. Finally, iffocus_nextis the StopIteration class, focus won’t move forward, but end here.focus_nextis anObjectPropertyand defaults to None.
- focus_previous¶
The
FocusBehaviorinstance 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
FocusBehaviorwidgets that are linked throughfocus_previousand are focusable. Iffocus_previousis None, it instead walks the children tree to find the previous focusable widget. Finally, iffocus_previousis the StopIteration class, focus won’t move backward, but end here.focus_previousis anObjectPropertyand defaults to None.
- focused¶
An alias of
focus.focusedis aBooleanPropertyand defaults to False.
- get_focus_next()[source]¶
Returns the next focusable widget using either
focus_nextor thechildrensimilar to the order when tabbing forwards with thetabkey.
- get_focus_previous()[source]¶
Returns the previous focusable widget using either
focus_previousor thechildrensimilar to the order when thetab+shiftkeys 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_touchwill 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.
Added 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_typeis anOptionsPropertyand 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_focusableis aBooleanPropertyand 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
configfor 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_nextandfocus_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
focusto False.When using a software keyboard, typical on mobile and touch devices, the keyboard display behavior is determined by the
softinput_modeproperty. You can use this property to ensure the focused widget is not covered or obscured.
keyboardis anAliasPropertyand defaults to None.
- keyboard_mode¶
Determines how the keyboard visibility should be managed. ‘auto’ will result in the standard behavior of showing/hiding on focus. ‘managed’ requires setting the keyboard visibility manually, or calling the helper functions
show_keyboard()andhide_keyboard().keyboard_modeis anOptionsPropertyand 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_typeis set to text, url, mail or address.Warning
On Android, keyboard_suggestions relies on InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS to work, but some keyboards just ignore this flag. If you want to disable suggestions at all on Android, you can set input_type to null, which will request the input method to run in a limited “generate key events” mode.
Added in version 2.1.0.
keyboard_suggestionsis aBooleanPropertyand 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 with only one keyboard), then as the other widgets gain 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 from this widget.
unfocus_on_touchis aBooleanPropertyand defaults to False if the keyboard_mode inConfigis ‘multi’ or ‘systemandmulti’, otherwise it defaults to True.
- class kivy.uix.behaviors.HoverBehavior(**kwargs)[source]¶
Bases:
objectHoverBehavior mixin to handle hover events.
Behavior will register widget to receive hover events (events with type_id set to “hover”) and update attributes
hoveredandhover_idsdepending on the received events.- Events:
- on_hover_event: (etype, me)
Dispatched when this widget receives a hover event.
- on_hover_enter: (me, )
Dispatched when a hover event collides with this widget for the first time.
- on_hover_update: (me, )
Dispatched when a hover event position has changed, but it’s still within this widget.
- on_hover_leave: (me, )
Dispatched when a hover event is no longer within this widget or when an event type “end” is received.
- hover_ids¶
Holds hover event.uid to event.pos values.
hover_idsis aDictProperty.
- hover_mode¶
How this widget will dispatch received hover events.
Options:
'default': Dispatch to children first and if none of the child
widgets accepted the event (by returning True), then dispatch on_hover_event so that this widget can try to handle it.
'all': Same as default, but always dispatch on_hover_event.'self': Don’t dispatch to children, but dispatch on_hover_event.
- hovered¶
Indicates if this widget is hovered by at least one hover event.
hoveredis aAliasProperty.
- on_hover_event(etype, me)[source]¶
Called when a hover event is received.
This method will test if event collides with this widget using
collide_point()and dispatch on_hover_enter, on_hover_update or on_hover_leave events.- Parameters:
- etype: str
Event type, one of “begin”, “update” or “end”
- me:
MotionEvent Hover motion event
- class kivy.uix.behaviors.HoverCollideBehavior[source]¶
Bases:
objectHoverCollideBehavior mixin overrides
on_motion()to filter-out hover events which do not collide with the widget or hover events which are not grabbed events.It’s recommended to use this behavior with
StencilViewor its subclasses (RecycleView,ScrollView, etc.), so that hover events don’t get handled when outside of stencil view.
- class kivy.uix.behaviors.KNSpaceBehavior(knspace=None, **kwargs)[source]¶
Bases:
objectInheriting from this class allows naming of the inherited objects, which are then added to the associated namespace
knspaceand accessible through it.Please see the
knspace behaviors moduledocumentation for more information.- knsname¶
The name given to this instance. If named, the name will be added to the associated
knspacenamespace, which will then point to the proxy_ref of this instance.When named, one can access this object by e.g. self.knspace.name, where name is the given name of this instance. See
knspaceand the module description for more details.
- knspace¶
The namespace instance,
KNSpace, associated with this widget. Theknspacenamespace stores this widget when naming this widget withknsname.If the namespace has been set with a
KNSpaceinstance, e.g. with self.knspace = KNSpace(), then that instance is returned (setting with None doesn’t count). Otherwise, ifknspace_keyis not None, we look for a namespace to use in the object that is stored in the property namedknspace_key, of this instance. I.e. object = getattr(self, self.knspace_key).If that object has a knspace property, then we return its value. Otherwise, we go further up, e.g. with getattr(object, self.knspace_key) and look for its knspace property.
Finally, if we reach a value of None, or
knspace_keywas None, the defaultknspacenamespace is returned.If
knspaceis set to the string ‘fork’, the current namespace inknspacewill be forked withKNSpace.fork()and the resulting namespace will be assigned to this instance’sknspace. See the module examples for a motivating example.Both rebind and allownone are True.
- class kivy.uix.behaviors.ToggleButtonBehavior(**kwargs)[source]¶
Bases:
ButtonBehaviorMixin to add toggle button behavior to any Kivy widget.
This mixin extends
ButtonBehaviorto provide persistent on/off state that survives beyond the press/release interaction. It supports grouping multiple toggles together for radio button behavior.State Management¶
Unlike the transient
pressedproperty from ButtonBehavior (which is True only during active touch), theactivatedproperty maintains persistent state:activated=True: Button is in “on” state (persists after release)
activated=False: Button is in “off” state (default)
The
activatedproperty can be set programmatically or toggled by user interaction. Whenallow_no_selectionis False, attempts to deactivate the last active button in a group are rejected: programmatic attempts log a warning, while touch interactions are silently blocked.Group Behavior¶
When buttons share a
group, they act like radio buttons:Activating one button automatically deactivates others in the group
Only one button per group can be active at a time
allow_no_selectioncontrols whether all buttons can be deactivated
Without group: Buttons toggle independently With group: Buttons behave as mutually exclusive options
Group Scoping¶
Groups can be either global or scoped to a specific widget owner:
Global groups (string):
ToggleButton: group: "mygroup" # Shared across entire application
Scoped groups (tuple):
ToggleButton: group: (root, "mygroup") # Scoped to 'root' widget
Scoped groups allow multiple widget hierarchies to use the same group name without interference. This is useful when creating reusable components with internal toggle groups.
Example:
<MyComponent>: # These groups won't conflict with other MyComponent instances ToggleButton: group: (root, "options") ToggleButton: group: (root, "options")
Events¶
- Inherits all events from ButtonBehavior:
on_press(): First touch downon_release(): All touches releasedon_cancel(): Touch moved outside bounds
Added in version 1.8.0.
Changed in version 3.0.0: - Replaced
stateOptionProperty withactivatedAliasProperty - Improved group management with automatic cleanup - Added scoped group support via tuple syntax - Replacedget_widgets(groupname)static method with unifiedget_group()descriptor that works as both instance and class method- activated¶
Persistent toggle state of the button.
True: Button is in “on” state
False: Button is in “off” state
Unlike
pressed(which is True only during touch),activatedmaintains state after release. Can be set programmatically or toggled by user interaction.When button is in a group, setting activated=True automatically deactivates other buttons in that group.
When
allow_no_selectionis False, attempts to set activated=False on the last active button in a group log a warning and are rejected. Touch interactions are silently blocked without warnings.activatedis anAliasPropertyand defaults to False.Added in version 3.0.0.
- allow_no_selection¶
Specifies whether widgets in a group allow no selection (all deselected).
True (default): Clicking active button deactivates it (all buttons off)
False: At least one button must remain active (radio button behavior)
When False, attempts to deactivate the last active button are rejected: programmatic
activated = Falselogs a warning, while touch interactions are silently blocked.Only applies when
groupis set.Added in version 1.9.0.
allow_no_selectionis aBooleanPropertyand defaults to True.
- get_group()¶
Get widgets in a group.
This descriptor works as both an instance method and a class method, providing a unified API for accessing group widgets.
- As instance method (no arguments):
Returns all widgets in the same group as this instance, including this instance itself.
Example:
# Get all widgets in my_button's group widgets = my_button.get_group() for w in widgets: print(w.text) del widgets # Release immediately
- As class method (pass group identifier):
Returns all widgets in the specified group. Useful when you don’t have a widget instance but know the group identifier.
Example:
# Get widgets by global group name widgets = ToggleButtonBehavior.get_group("options") # Get widgets by scoped group widgets = ToggleButtonBehavior.get_group((panel, "filters")) # Useful after removing a widget my_group = widget.group widget.parent.remove_widget(widget) remaining = ToggleButtonBehavior.get_group(my_group)
Warning
Always release the result immediately! Holding references prevents garbage collection:
widgets = button.get_group() # use widgets del widgets
Note
List may contain recently deleted widgets that haven’t been garbage collected yet.
- Returns:
List of widget instances in the group (empty list if group doesn’t exist or has no members)
Added in version 3.0.0: Replaces the old
get_widgets(groupname)static method with a unified descriptor that works as both instance and class method.
- group¶
Group of the button. If None, no group will be used (button toggles independently).
Accepts two formats:
Hashable value (string, int, etc.): Global group shared across entire application
Tuple (owner, name): Scoped group limited to owner’s context
Global groups (any hashable):
group: "mygroup" group: 42 group: MyEnum.OPTION_A
Scoped groups (tuple of any object + hashable name):
group: (root, "mygroup") group: (self.parent, "options") group: (app.current_screen, "filters")
- Tuple format:
(owner, name) owner: Any object to scope the group to (typically a widget). Uses object identity, not equality. Can be weakly referenced.
name: Hashable identifier for the group (string, int, enum, etc.)
Only one button per group can be active at a time. When a button in a group is activated, all other buttons in that group are automatically deactivated.
Scoped groups allow multiple widget instances to use the same group name without interference, making it easier to create reusable components.
Example of reusable component:
# Multiple instances won't interfere with each other <FilterPanel>: ToggleButton: group: (root, "size") text: "Small" ToggleButton: group: (root, "size") text: "Large" # Each FilterPanel instance has independent "size" groups FilterPanel: id: panel1 FilterPanel: id: panel2
groupis aObjectPropertyand defaults to None.Changed in version 3.0.0: Added support for tuple format to enable scoped groups.
- on_activated(instance, value)[source]¶
Event handler called when activated state changes.
Override this method to respond to state changes.
- Parameters:
instance – This button instance
value – New activated state (True/False)
- toggle_on¶
Specifies which
ButtonBehaviorevent triggers the toggle state change.“release” (default) — The state toggles when the button is released.
“press” — The state toggles immediately when the button is pressed.
This property allows adjusting when the toggle action occurs, depending on the desired interaction style. It can be changed dynamically at runtime, and the new behavior takes effect immediately.
toggle_onis anOptionPropertyand accepts either"press"or"release". Defaults to"release".
- class kivy.uix.behaviors.TouchRippleBehavior(**kwargs)[source]¶
Bases:
objectTouch 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.Example¶
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_inis aNumericPropertyand defaults to 0.5.
- ripple_duration_out¶
Animation duration taken to fade the overlay.
ripple_duration_outis aNumericPropertyand defaults to 0.2.
- ripple_fade_from_alpha¶
Alpha channel for ripple color the animation starts with.
ripple_fade_from_alphais aNumericPropertyand defaults to 0.5.
- ripple_fade_to_alpha¶
Alpha channel for ripple color the animation targets to.
ripple_fade_to_alphais aNumericPropertyand defaults to 0.8.
- ripple_func_in¶
Animation callback for showing the overlay.
ripple_func_inis aStringPropertyand defaults to in_cubic.
- ripple_func_out¶
Animation callback for hiding the overlay.
ripple_func_outis aStringPropertyand defaults to out_quad.
- ripple_rad_default¶
Default radius the animation starts from.
ripple_rad_defaultis aNumericPropertyand defaults to 10.
- ripple_scale¶
Max scale of the animation overlay calculated from max(width/height) of the decorated widget.
ripple_scaleis aNumericPropertyand defaults to 2.0.
- class kivy.uix.behaviors.TouchRippleButtonBehavior(**kwargs)[source]¶
Bases:
TouchRippleBehaviorThis mixin class provides a similar behavior to
ButtonBehaviorbut 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_releaseis aBooleanPropertyand 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_touchis aObjectPropertyand defaults to None.
- Button Behavior
- Code Navigation Behavior
- Compound Selection Behavior
- Compound selection concepts
- Selection mechanics
- Example
CompoundSelectionBehaviorCompoundSelectionBehavior.clear_selection()CompoundSelectionBehavior.deselect_node()CompoundSelectionBehavior.get_index_of_node()CompoundSelectionBehavior.get_selectable_nodes()CompoundSelectionBehavior.goto_node()CompoundSelectionBehavior.keyboard_selectCompoundSelectionBehavior.multiselectCompoundSelectionBehavior.nodes_order_reversedCompoundSelectionBehavior.page_countCompoundSelectionBehavior.right_countCompoundSelectionBehavior.scroll_countCompoundSelectionBehavior.select_node()CompoundSelectionBehavior.select_with_key_down()CompoundSelectionBehavior.select_with_key_up()CompoundSelectionBehavior.select_with_touch()CompoundSelectionBehavior.selected_nodesCompoundSelectionBehavior.text_entry_timeoutCompoundSelectionBehavior.touch_deselect_lastCompoundSelectionBehavior.touch_multiselectCompoundSelectionBehavior.up_count
- Cover Behavior
- Drag Behavior
- Emacs Behavior
- Focus Behavior
- Managing focus
- Initializing focus
FocusBehaviorFocusBehavior.focusFocusBehavior.focus_nextFocusBehavior.focus_previousFocusBehavior.focusedFocusBehavior.get_focus_next()FocusBehavior.get_focus_previous()FocusBehavior.hide_keyboard()FocusBehavior.ignored_touchFocusBehavior.input_typeFocusBehavior.is_focusableFocusBehavior.keyboardFocusBehavior.keyboard_modeFocusBehavior.keyboard_on_key_down()FocusBehavior.keyboard_on_key_up()FocusBehavior.keyboard_suggestionsFocusBehavior.show_keyboard()FocusBehavior.unfocus_on_touch
- HoverBehavior
- Kivy Namespaces
- ToggleButton Behavior
- Touch Ripple
TouchRippleBehaviorTouchRippleBehavior.ripple_duration_inTouchRippleBehavior.ripple_duration_outTouchRippleBehavior.ripple_fade()TouchRippleBehavior.ripple_fade_from_alphaTouchRippleBehavior.ripple_fade_to_alphaTouchRippleBehavior.ripple_func_inTouchRippleBehavior.ripple_func_outTouchRippleBehavior.ripple_rad_defaultTouchRippleBehavior.ripple_scaleTouchRippleBehavior.ripple_show()
TouchRippleButtonBehavior