亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號