Python,Kivy。使用TextInput过滤器将输入值限制在两个数字之间

时间:2020-06-02 15:23:50

标签: python kivy

我需要一个import 'package:flutter/material.dart'; ​ final Color darkBlue = Color.fromARGB(255, 18, 32, 47); ​ void main() { runApp(MyApp()); } ​ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue), debugShowCheckedModeBanner: false, home: Scaffold( body: Center( child: MyWidget(), ), ), ); } } ​ class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return FutureBuilder( future: Future.delayed(Duration(seconds: 2)), builder: (context, snapshot) { if (snapshot.connectionState != ConnectionState.done) { return Center(child: CircularProgressIndicator()); } ​ return ListView( children: [ Container(height: 150, color: Colors.red), Container(height: 150, color: Colors.yellow), Container(height: 150, color: Colors.blue), Container(height: 150, color: Colors.orange), Container(height: 150, color: Colors.red), ], ); }, ); } } 和一个TextInput filter值的minimum (1)。过滤器应允许maximum (100) +我要integer only:无法将字符串转换为float或int:'。

所以我的目标是: TextInput只让数字介于1到100之间。

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

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

)。

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

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

我的文件avoid: 'ValueError

.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

1 个答案:

答案 0 :(得分:0)

尝试一下:

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)
相关问题