Python 3.Kivy。有什么方法可以限制在 TextInput 小部件中输入的文本吗?

问题描述 投票:0回答:3

我正在编写 kivy 应用程序,最近我遇到了在 TextInput 小部件中无限输入文本的问题。这个问题有办法解决吗?

python kivy
3个回答
8
投票

一个可能的解决方案是创建一个新属性并覆盖 insert_text 方法:

from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.properties import NumericProperty


class MyTextInput(TextInput):
    max_characters = NumericProperty(0)
    def insert_text(self, substring, from_undo=False):
        if len(self.text) > self.max_characters and self.max_characters > 0:
            substring = ""
        TextInput.insert_text(self, substring, from_undo)

class MyApp(App):
    def build(self):
        return MyTextInput(max_characters=4)


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

0
投票

我也需要做这样的事情,并且还需要将文本输入大写以保持一致性。这是我想出的..

首先,我创建了一个新类:

class CapitalInput(TextInput):
    max_length = 15 # sets max length of TextInput to 15 chars

在类中,我创建了一个方法:

def insert_text(self, substring, from_undo = False):
        s = substring.upper().strip()
        if len(self.text) <= self.max_length:
            return super(CapitalInput, self).insert_text(s, from_undo = from_undo)

注意:如果不需要,则无需将“.upper()”保留在方法内。如果您删除该部分,它就会正常工作。

最后,在你的程序中,当你需要使用这个修改过的TextInput时,只需使用这个:

self.whatever_your_user_input_is_called = CapitalInput(multiline = False, padding_y = (8, 4))
self.window.add_widget(self.whatever_your_user_input_is_called)

就是这样!希望这个解决方案对您有所帮助,就像对我一样。


0
投票

(我无法评论所以在这里回复)

Mova 的答案是允许一个字符超出限制。这是因为在方法结束之前附加插入的字符不是 self.text 的一部分。

class CapitalInput(TextInput):
    max_length = 15 # sets max length of TextInput to 15 chars

以及更正的方法:

def insert_text(self, substring, from_undo = False):
        s = substring.upper().strip()
        if len(self.text)+1 <= self.max_length:
            return super(CapitalInput, self).insert_text(s, from_undo = from_undo)
© www.soinside.com 2019 - 2024. All rights reserved.