I'm writing an app using Kivy framework and I stumbled upon a minor but annoying problem: I don't know how to handle Tab/Enter/Arrow keys in text fields so that pressing either of them would dispatch an event, eg. switch the focus (jump) to another TextInput or launch something like send_form()
Could anyone please shed some light on this issue?
The TextInput widget provides a box for editable plain text. Unicode, multiline, cursor navigation, selection and clipboard features are supported. The TextInput uses two different coordinate systems: (x, y) - coordinates in pixels, mostly used for rendering on screen.
Bookmark this question. Show activity on this post. Neither on_touch_down: or on_focus erases JUST the text input that is currently focused.
in addition to the answer size_hint_x and size_hint_y must be set to None respectively before the height and width attribute can be used i.e size_hint: (None, None) for less typing. If you want to set the width attribute, size_hint_x is set to None and vice-versa.
Kivy 1.9 provides the ability to set write_tab: False
on text inputs (see docs), causing the tab key to focus on the next focusable widget.
Kivy allows the Enter key to dispatch events by setting multiline: False
and on_text_validate: root.foo()
.
So, to create a text input widget that has the desired Enter and Tab functionality, do as follows:
TextInput:
write_tab: False
multiline: False
on_text_validate: root.foo()
Just found this old question and figured I would contribute. I also needed tab / enter to go to the next field. I did what @tshirtman suggested. This is my custom TextInput
class:
from kivy.uix.textinput import TextInput
class TabTextInput(TextInput):
def __init__(self, *args, **kwargs):
self.next = kwargs.pop('next', None)
super(TabTextInput, self).__init__(*args, **kwargs)
def set_next(self, next):
self.next = next
def _keyboard_on_key_down(self, window, keycode, text, modifiers):
key, key_str = keycode
if key in (9, 13) and self.next is not None:
self.next.focus = True
self.next.select_all()
else:
super(TabTextInput, self)._keyboard_on_key_down(window, keycode, text, modifiers)
This allows you to pass next
when you instantiate the input, or alternatively call set_next
on an existing input.
9 and 13 are the key codes for tab and enter.
Works well for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With