3

有没有办法让TextInputs 接收有界字符串值(即最大长度的字符串 x)?我尝试研究如何混合AliasProperty以模仿BoundedNumericProperty,但找不到任何 Property 类方法。

4

3 回答 3

7

到时间on_text被调用时,文本输入中的文本已经更改。您希望覆盖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)

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

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)
于 2013-07-25T09:57:05.310 回答
3

我认为on_text每次修改文本时都会触发该事件。因此,您可以覆盖该方法:

def on_text(self, instance, value):
    print('The widget', instance, 'have:', value)

    # validate here!!!

    # you might also want to call the parent.
    #super(ClassName, self).on_text(instance, value)

或者绑定它:

def my_callback(instance, value):
    print('The widget', instance, 'have:', value)
    #validate here

textinput = TextInput()
textinput.bind(text=my_callback)

小心不定式递归。如果您修改内部的文本变量,on_text或者my_callback您可能之前触发了该事件。老实说,我不记得了,但我认为确实如此,因此您需要一个标志,例如在修改变量之前进行验证

您还可以使用仍然使用on_focus,以便检查何时TextInput失去焦点:

def on_focus(instance, value):
    if value:
        print('User focused', instance)
    else:
        print('User defocused', instance)

textinput = TextInput()
textinput.bind(focus=on_focus)

最后,您还可以绑定键盘,这样您就可以保证在TextInput. 老实说,我不知道执行顺序,但如果你使用on_text,你可能会在屏幕上出现的字母之后删除,这可能是不受欢迎的。

我认为实现你自己的BoundedStringProperty将是一项相当大的工作来实现你想要的。这是代码BoundedNumericProperty

此外,您不应该尝试使用 an ,AliasProperty因为您已经得到StringProperty了触发on_text前面提到的事件的方法。

于 2013-07-25T05:58:06.340 回答
1

上面给出的代码有一个简单的问题。您必须使用 NumericProperty.defaultvalue 才能使用代码(在长度比较中)。下面是简单的子类,可用于为您认为合适的任何大小创建类。

class CustomInput(TextInput):

def  __init__(self , **kwargs):
    if "max_chars" in kwargs:
        self.max_chars = NumericProperty(int(kwargs["max_chars"]))
    super(CustomInput , self ).__init__(**kwargs)

def insert_text( self , substring , from_undo = False ):
    if not from_undo and ( len( self.text ) + len( substring ) > self.max_chars.defaultvalue ):
        return
    super( CustomInput , self).insert_text( substring , from_undo)

我将 max_chars 作为关键字参数传递给 init。如果我只将 int 用于 max_chars 而不是 NumericProperty,则此方法有效

于 2016-03-10T14:03:11.940 回答