Kivy,动态 class 关于 KV 语言

Kivy, dynimic class on KV language

我试图在我的 KV 语言上使用规则来生成 classes,但我总是遇到错误。

<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 class 是 FloatInput,我该怎么做才能使它起作用,否则TextInput.

单独使用 kv 语言是不可能的。至少不是直接的。您有 ~4 个选项:

  1. 根据某个widget的属性设置input_type:

    TextInput:
        hint_text: 'int'
        input_type: 'int' if self.hint_text == 'int' else 'float'
    
  2. 从外部改变input.input_type属性(如果区别只是输入类型)

  3. 动态添加正确的小部件,例如<parent>.add_widget(Factory.FloatInput()) 在某些事件中,假设是 Button
  4. on_release
  5. 在 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'