我正在编写kivy应用程序,并且心里感到我遇到了在TextInput小部件中无限制地输入文本的问题。有没有解决这个问题的方法?
答案 0 :(得分:2)
一种可能的解决方案是创建一个新属性并覆盖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()