Python kivy如何在multiline=True时使用按钮或回车键验证TextInput



的想法是使用Enter键或通过";按钮";

问题:是否有任何方法可以在TextInput中运行on_text_validate:使用按钮Enter键(也触发按钮(,然后使用shift-Enter或者ctrl-Enter?因为我需要将TextInput中的文本更新到我的标签,因为我不能按Enter键,因为我的多行=True。还有任何方法可以知道TextInput中是否存在文本;"验证按钮";将在您在TextInput中键入内容时启用并高亮显示。

我试着在互联网上搜索,但只能找到2个选项,1个是绑定键盘,2个是设置multiline=False。我选择了选项1,花了一整天的时间,但仍然无法解决问题,因为例子不多。

编辑:我添加了一个例子,使我的例子更清楚。

.kv文件

TextInput:
multiline: True     # Down the line by hitting shift-enter/ctrl-enter instead of enter
on_text_validate:   # I want to run this line by hitting enter or via a Button:
root.on_text_validate(self)

默认情况下,当触摸在TextInput小部件之外时,TextInput会失去焦点。因此,如果您从按钮(TextInput之外(触发一些操作,那么处理focus之外的其他事情就足够了。

但我不清楚你到底想发生什么

如果您想在按下回车键或任何其他键时从键盘上散焦TextInput,您可以将键盘绑定到某个回调,并从该回调执行所需的操作。

基于这个假设,你有这个(完整的(代码和一些额外的调整:

from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder

class TestApp(App):
def build(self):
Window.bind(on_keyboard = self.validate_input)
return Builder.load_string(
"""
BoxLayout:
orientation: "vertical"
spacing: "5dp"
Label:
id: lbl
TextInput:
id: textfield
hint_text: "Enter text here"
""")
def validate_input(self, window, key, *args, **kwargs):
textfield = self.root.ids.textfield
if key == 13 and textfield.focus: # The exact code-key and only the desired `TextInput` instance.
#           textfield.do_undo() # Uncomment if you want to strip out the new line.
textfield.focus = False
self.root.ids.lbl.text = textfield.text
#           textfield.text = "" # Uncomment if you want to make the field empty.
return True
TestApp().run()

最新更新