【问题标题】:Kivy, dynimic class on KV languageKivy,KV语言中的动态类
【发布时间】:2016-11-11 23:47:21
【问题描述】:
我正在尝试使用我的 KV 语言上的规则来生成类,但总是出错。
<SimpleInputLayout>:
orientation: 'vertical'
message_label: message
user_input: input
Label:
id: message
text: root.message_to_user
FloatInput: if input_type == 'float' else TextInput:
id: input
focus: True
如果input_type 等于'float',我该怎么做才能使这个工作有效,我希望我的input 类是FloatInput,否则是TextInput。
【问题讨论】:
标签:
python
python-3.x
kivy
kivy-language
【解决方案1】:
单独使用kv lang 是不可能的。至少不是直接的。你有 ~4 个选项:
-
根据小部件的属性设置input_type:
TextInput:
hint_text: 'int'
input_type: 'int' if self.hint_text == 'int' else 'float'
从外部更改input.input_type 属性(如果只是输入类型的区别)
- 动态添加正确的小部件,例如
<parent>.add_widget(Factory.FloatInput()) 在某些事件上,比如说on_release 的Button
- 在构建布局时使用 Python 尤其是
__init__。这比在kv 中尝试实现不存在的东西或寻找用于添加小部件的正确事件要容易得多。它更灵活。
尽管文档中可能提到了 : 之后的所有内容都表现得像一个普通的 Python,但这适用于小部件属性和事件,而不是小部件本身:
不好:
v--rule-- : v------------ not Python -------------v
FloatInput: if input_type == 'float' else TextInput:
好:
TextInput:
text: 'int'
# property: v-------------- Python ---------------v
input_type: 'int' if self.text == 'int' else 'float'