如何仅接受Texinputfield中的两个数字?

2024-04-25 11:56:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想接受文本输入中的两个数字。我知道如何只接受数字,我知道如何只接受两个字母,但不知道如何同时接受两个字母

此代码仅接受以下字母:

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

Tags: lambda代码textfromselffalseinputlen
1条回答
网友
1楼 · 发布于 2024-04-25 11:56:48

据我所知,你不能用这种方式做你想做的事。但是您可以使用数值输入,该类将使用文本输入,并将处理您的限制。我希望这能帮助你,这与你最初的想法有点不同,但解决了问题

所以试着去追随:

main.py文件

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()

gui.kv文件

#: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)

相关问题 更多 >