如何在Kivy的TextInput中设置光标位置

How to set cursor position in TextInput in Kivy

我正在尝试弄清楚如何在调用 on_validate() 方法后将焦点保持在我的 TextInput 小部件上。这样一来,在点击 RETURN 之后,我可以继续打字,而无需使用鼠标 select 小部件。

当我阅读 TextInput 文档时,所有光标选项似乎都假设光标已经在小部件中。

在文档中显示,要将焦点设置在 TextInput 上,您可以这样做:

textinput = TextInput(focus=True)

也许您可以在 on_validate 方法的末尾再次将焦点设置为 True。 具体如何执行将取决于您是从 kv 文件还是 main.py

调用它

例如,在 kv 文件中它看起来像这样:

on_validate: mytextinput.focus = True

而在 main.py 中,它需要这样的东西:

class MyTextInput(TextInput):
    def __init__(self, **kwargs):
        super(MyTextInput, self).__init__(kwargs)

    def on_validate(self):
        #do other stuff perhaps
        self.focus = True

下面的代码片段展示了如何使用 Kivy Clock.schedule_once 在用户按下 Enter 提交他在一行 Textinput 中输入的文本后,将焦点重置在 TextInput 小部件上。

    commandTextInput = ObjectProperty()

...

def refocusOnCommandTextInput(self):
    #defining a delay of 0.1 sec ensure the
    #refocus works in all situations. Leaving
    #it empty (== next frame) does not work
    #when pressing a button !
    Clock.schedule_once(self._refocusTextInput, 0.1)       


def _refocusTextInput(self, *args):
    self.commandTextInput.focus = True


#example of calling refocus function after
#having handled new command entry
def submitCommand(self):

    # Get the student name from the TextInputs
    commandStr = self.commandTextInput.text
    #... some processing
    self.refocusOnCommandTextInput()

来自 .kv 文件

    TextInput:
        id: command
        background_color: 0,0,0,0
        foreground_color: 1,1,1,1
        focus: True
        #ENTER triggers root.submitCommand()
        multiline: False
        on_text_validate: root.submitCommand()