Kivy:TextInputs是否有"BoundedString"属性?

Noo*_*bot 3 python kivy

有没有办法让TextInputs接收有界字符串值(即最大长度为x的字符串)?我试图调查如何mixin AliasProperty以模仿BoundedNumericProperty,但找不到任何Property类方法.

qua*_*non 7

到时候on_text被称为文本已经在textinput中被更改.您希望覆盖insert_text以在将文本插入TextInput之前捕获文本,从而在更新text属性之前捕获文本以限制对TextInput的输入.

请不要绑定/请求键盘,因为textinput为你做了这一点,你的处理程序将在Textinput聚焦后停止工作(TextInput会请求键盘,在单个键盘环境中你的处理程序将停止工作).

下面是一个覆盖insert_text的示例代码,用于将文本文本输入限制为仅数字输入.

class NumericInput(TextInput):

    def insert_text(self, substring, from_undo=False):
        if not from_undo:
            try:
                int(substring)
            except ValueError:
                return
        super(NumericInput, self).insert_text(substring, from_undo)
Run Code Online (Sandbox Code Playgroud)

因此,为了将文本限制在一定长度,您可以执行以下操作::

class CustomInput(TextInput):

    max_chars = NumericProperty(10)

    def insert_text(self, substring, from_undo=False):
        if not from_undo and (len(self.text)+len(substring) > self.max_chars):
            return
        super(CustomInput, self).insert_text(substring, from_undo)
Run Code Online (Sandbox Code Playgroud)