使用 TextInput 过滤器限制两个数字之间的输入值

我需要一个TextInput filter和minimum (1)一个maximum (100)值。过滤器应该允许integer only+ I want to avoid: 'ValueError: could not convert string to float or int:'。


所以我的目标是: TextInput 只让数字在 1-100 之间。


我尝试了一些解决方案,比如简单的 if-else 代码,但它不够优雅、不够简单,而且我的代码也变得有点混乱。


这就是为什么我认为我需要一个 TextInput 过滤器。我知道官方网站上有示例,我尝试创建一个过滤器,但似乎我的知识还不够(还)。


你能帮我解决这个问题吗?


我创建了一个简单的例子:


我的档案.py


from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.textinput import TextInput

from kivy.properties import ObjectProperty



class NewTextInput(TextInput):

    input_filter = ObjectProperty('int', allownone=True)


    max_characters = 2

    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)


    #This is where I need the filter.

    #min_value = 1

    #max_value = 100

    #def insert_text(self, substring, from_undo=False):

       #...


class MyApp(App):

    def build(self):

        pass


if __name__ == '__main__':

    MyApp().run()

我的档案.kv


BoxLayout:

    orientation: 'horizontal'

    Label:

        text: "Sample"

    NewTextInput:


慕码人2483693
浏览 91回答 1
1回答

偶然的你

试试这个:class MyTextInput(TextInput):    def __init__(self, **kwargs):        super(MyTextInput, self).__init__(**kwargs)        self.input_filter = 'int'    def insert_text(self, substring, from_undo=False):        if substring in string.digits:            cc, cr = self.cursor            text = self._lines[cr]            new_text = text[:cc] + substring + text[cc:]            if int(new_text) > 100:                return        super(MyTextInput, self).insert_text(substring, from_undo=from_undo)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python