【发布时间】:2018-08-03 20:16:07
【问题描述】:
在将计算数据更新到 ListView 之前,我试图在对输入值进行计算之前验证 Kivy 中的 TextInput。但是当我通过打印出来测试第一个 TextInput 值时,什么都没有,没有错误,也没有结果。我在我的 Kivy 文件中引用了 on_press root.calvariable 方法 AddKalibrasieForm 类,但仍然没有。有人可以告诉我我做错了什么吗?
编辑:我注意到我做错了什么:我在没有声明类的情况下导入了 TextInput(它已被删除)并且没有以正确的方法(修复它)声明 val_lewerha TextInput 对象,因此它打印到控制台。我的问题已更改为您可以在输入上验证用户输入吗?这叫做 on_focus 吗?例如我认为哪种方法应该达到预期的效果:
def validate_input(self):
if isinstance(self.textinput, (int, float)):
accept self.textinput
else:
make self.textinput color red as incorrect data type
第二次编辑:我一定错过了,但另外两个 Stack Overflow Q&A 让我得到了正确答案, Stack_Overflow_Answer1; Stack_Overflow_Answer2。 我还浏览了 Kivy 文档,该文档显示了在插入文本时仅允许浮点数和 TextInput 中的一个点的示例 Kivy1.11.0_TextInput_Documentation。所以我将能够解决它。 @eyllanesc:我只想允许用户在 TextInput 中插入浮点“0-9”,而不是字符串。谢谢。如何将此标记为已回答?
这是我的 Python3 代码:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class AddKalibrasieForm(BoxLayout):
calculated_results = ObjectProperty()
def convert_calvariables(self):
val_lewerha = ObjectProperty()
not_filled_in = ""
flowha = float(self.val_lewerha.text)
if flowha != not_filled_in and isinstance(flowha, (int, float)):
print(format(self.val_lewerha.text))
else:
print("Error")
class CalibrationApp(App):
pass
if __name__ == '__main__':
CalibrationApp().run()
这是我的 Kivy 文件的一部分:calibration.kv
AddKalibrasieForm:
<AddKalibrasieForm>:
orientation: "vertical"
val_lewerha: volha_box
calculated_results: calculated_results_table
BoxLayout:
height: "40dp"
size_hint_y: None
Label:
text: "Lewering per ha"
size_hint_x: 25
TextInput:
id: volha_box #TextInput object name
size_hint_x: 50
Label:
text: "liter"
size_hint_x: 25
text_size: self.size
halign: "left"
BoxLayout:
height: "60dp"
size_hint_y: None
Label:
size_hint_x: 35
Button:
text: "Bereken"
size_hint_x: 30
on_press: root.convert_calvariables() #method called on_press
Label:
size_hint_x: 35
ListView:
id: calculated_results_table
table_items: []
【问题讨论】:
-
你可以解释什么是验证行为,例如让我们说在 TextInput 中这是值“12”,现在用户按下“s”然后应该显示在 TextInput
-
请改进您在 .kv 中的缩进
-
请在这里回答,不在您的帖子中,您找到解决方案了吗?
-
是的,我在文档中给出的 kivy 文件“input_filter = 'float'”中添加了一行,它解决了它。谢谢。
标签: python python-3.x kivy