2016-11-11 57 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'