2016-11-11 74 views
1

我试图在我的KV语言上使用规则来生成类,但是我总是得到一个错误。Kivy,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

回答

0

这样的事情不可能与kv lang单独。至少不是直接的。你有〜4个选项:

  1. 设置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())在某些事件上,我们假设on_release的一个Button
  4. 在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'