Python / Kivy:使用回车键表单提交

时间:2018-04-09 07:52:42

标签: python-2.7 kivy kivy-language

我使用TextInput键从一个TextInput移动到另一个enter 我想使用TextInput键从上次Button移至enter。当我再次按下输入键时,应调用root.abc()功能。
有人能告诉我怎么做吗?

test.py

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.core.window import Window

Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (300, 100)

class User(Screen):

    def abc(self):
        print('Test')

class Test(App):

    def build(self):
        return self.root

if __name__ == '__main__':
    Test().run()

test.kv

User:
    BoxLayout:
        orientation: "vertical"

        TextInput:
            id:test1
            focus : True
            text: ' '
            width: 100
            multiline: False
            on_text_validate: test2.focus = True

        TextInput:
            id:test2
            text: ' '
            width: 100
            multiline: False
            on_text_validate: test3.focus = True

        Button:
            id:test3
            text: 'Ok'
            on_press : root.abc()

1 个答案:

答案 0 :(得分:2)

这里我们使用按键向下绑定,检查按钮的焦点和按下Enter键。

实施例

main.py

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.core.window import Window
from kivy.properties import ObjectProperty

Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (300, 100)


class User(Screen):
    test3 = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        Window.bind(on_key_down=self._on_keyboard_down)

    def _on_keyboard_down(self, instance, keyboard, keycode, text, modifiers):
        if self.test3.focus and keycode == 40:  # 40 - Enter key pressed
            self.abc()

    def abc(self):
        print('Test')


class Test(App):

    def build(self):
        return self.root


if __name__ == '__main__':
    Test().run()

test.kv

#:kivy 1.10.0

User:
    test3: test3
    BoxLayout:
        orientation: "vertical"

        TextInput:
            id:test1
            focus : True
            text: ' '
            width: 100
            multiline: False
            on_text_validate: test2.focus = True

        TextInput:
            id:test2
            text: ' '
            width: 100
            multiline: False
            on_text_validate:
                test3.background_normal = ''
                test3.background_color = [0, 0, 1, 0.5]    # 50% translucent blue
                test3.focus = True

        Button:
            id:test3
            text: 'Ok'
            focus: False
            on_press : root.abc()

输出

Img01 - App Startup Img02 - test1-TextInput Img03 - test2-TextInput Img04 - Pressed Enter-OK Button