我只想在Textinput中接受两个数字。我知道如何只接受数字,我知道如何只接受两个字母,但不怎么都接受。
此代码仅接受字母:
TextInput:
multiline: False
input_filter: lambda text, from_undo: text[:2 - len(self.text)]
此代码仅接受数字:
TextInput:
multiline: False
input_filter: "int"
但是当我尝试类似的操作时:
TextInput:
multiline: False
input_filter: "int", lambda text, from_undo: text[:2 -
len(self.text)]
我收到此错误:
TypeError: 'tuple' object is not callable
答案 0 :(得分:0)
据我所知,您无法以这种方式做自己想做的事。但是您可以使用 NumericInput ,此类将使用 TextInput 并处理您的限制。希望对您有所帮助,与您的最初想法有些不同,但是可以解决问题。
所以请尝试遵循:
from kivy.app import App
from kivy.base import Builder
from kivy.properties import NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager
class NumericInput(TextInput):
min_value = NumericProperty(None)
max_value = NumericProperty(None)
def __init__(self, *args, **kwargs):
TextInput.__init__(self, *args, **kwargs)
self.input_filter = 'int' # The type of your filter
self.multiline = False
def insert_text(self, string, from_undo=False):
new_text = self.text + string
if new_text != "" and len(new_text) < 3:
try:
# Will try convert the text to a int and compare, if it's not a number
# It will throw a exception and will not append the text into the input
# If the value is between the values and is a int
if self.min_value <= int(new_text) <= self.max_value:
TextInput.insert_text(self, string, from_undo=from_undo)
except ValueError as e: # Just cannot convert to a `int`
pass
class BoundedLayout(BoxLayout):
pass
presentation = Builder.load_file("gui.kv")
class App(App):
def build(self):
return BoundedLayout()
if __name__ == '__main__':
App().run()
#:kivy 1.0
<BoundedLayout>:
orientation: 'horizontal'
Label:
text: 'Value'
NumericInput:
min_value : 0 # your smaller value, can be negative too
max_value : 99 # Here goes the max value
hint_text : 'Enter values between {} and {}'.format(self.min_value, self.max_value)