为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕码人2483693 2022-12-20 16:31:00
我需要一个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 过滤器。我知道官方网站上有示例,我尝试创建一个过滤器,但似乎我的知识还不够(还)。你能帮我解决这个问题吗?我创建了一个简单的例子:我的档案.pyfrom kivy.app import Appfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.uix.textinput import TextInputfrom kivy.properties import ObjectPropertyclass 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):        passif __name__ == '__main__':    MyApp().run()我的档案.kvBoxLayout:    orientation: 'horizontal'    Label:        text: "Sample"    NewTextInput:
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

试试这个:


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)


查看完整回答
反对 回复 2022-12-20
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信