gpt4 book ai didi

python - Kivy - InputText 的限制值

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:08 25 4
gpt4 key购买 nike

我正在尝试制作一个只接受浮点值的输入文本。此外,输入的值必须介于两个值之间。

我创建了一个包含“验证”方法的类。如果该值不在两个值之间,则会显示一个弹出窗口。

但是我有一个问题。该方法仅在用户点击“Enter”时调用。我尝试在文本更改时调用该方法,但这对用户来说很烦人,因为在用户输入数据时弹出窗口一直出现。

还有另一种方法可以做这样的事情吗?

Python 文件:

class BoundedInput(BoxLayout):
value = NumericProperty()

def validate(self, min_value, max_value):
status = min_value <= self.value <= max_value
if not status:
message = f'Value must be between {min_value} and {max_value}'
popup = Popup(title='Warning', content=Label(text=message),
size_hint=(None, None), size=(300, 200))
popup.open()

Kv文件:

<NumericInput@TextInput>:
input_filter: 'float'
multiline: False

<BoundedInput>:
orientation: 'horizontal'
Label:
text: 'Value'
NumericInput:
text: str(root.value)
on_text_validate:
root.value = float(self.text)
root.validate(5, 100)

最佳答案

一个合适的方法除了 float 之外还可以在范围内进行过滤,为此我们创建一个继承 TextInput 的类并覆盖 insert_text 方法:

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


Builder.load_string("""
<BoundedLayout>:
orientation: 'horizontal'
Label:
text: 'Value'
NumericInput:
min_value : 5
max_value : 100
hint_text : 'Enter values between {} and {}'.format(self.min_value, self.max_value)
""")

class NumericInput(TextInput):
min_value = NumericProperty()
max_value = NumericProperty()
def __init__(self, *args, **kwargs):
TextInput.__init__(self, *args, **kwargs)
self.input_filter = 'float'
self.multiline = False

def insert_text(self, string, from_undo=False):
new_text = self.text + string
if new_text != "":
if self.min_value <= float(new_text) <= self.max_value:
TextInput.insert_text(self, string, from_undo=from_undo)

class BoundedLayout(BoxLayout):
pass

class MyApp(App):
def build(self):
return BoundedLayout()

if __name__ == '__main__':
MyApp().run()

关于python - Kivy - InputText 的限制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48347569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com