Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab/Enter (and other keystrokes) handling in Kivy's TextInput widgets

Tags:

python

kivy

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?

like image 489
minder Avatar asked Aug 20 '12 12:08

minder


People also ask

What is KIVY TextInput?

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.

How do I remove TextInput from KIVY?

Bookmark this question. Show activity on this post. Neither on_touch_down: or on_focus erases JUST the text input that is currently focused.

How do I change the size of TextInput in KIVY?

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.


2 Answers

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()
like image 114
mcastle Avatar answered Sep 20 '22 18:09

mcastle


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.

like image 33
dgel Avatar answered Sep 22 '22 18:09

dgel