2017-07-25 116 views
0

我相對比較新的Python和全新的基維,所以我正在努力解決可能是一個簡單的任務。我需要一個帶有兩個按鈕的主屏幕:Button1和Button2。當我按下一個按鈕時,第二個屏幕應該出現再次顯示按鈕的數量。第二個屏幕上的按鈕數量是動態的,但我們可以簡單地假設我們知道它。Python Kivy:如何在一個循環中添加多個小部件

Python代碼:

from kivy.app import App 
from kivy.uix.boxlayout import BoxLayout 

buttons = {} 
buttons['Button 1'] = ('A Button 1', 'A Button 2') 
buttons['Button 2'] = ('B Button 1', 'B Button 2', 'B Button 3') 

class SelectButton(BoxLayout): 

    def show_buttons(self, button): 

     self.clear_widgets() # I guess I need this 

     #Here question comes: how to add button widgets buttons[button]? 
     #Shall I do this in the loop in Python code or in .kv file? 
     #for item in buttons[button]: 
     # print (item) 

class TestApp(App): 
    pass 

if __name__ == '__main__': 
    TestApp().run() 

.kv文件:

SelectButton: 

<SelectButton>: 
    orientation: "vertical" 
    Label: 
     size_hint_y: 0.15 
     text: "Select Button" 
    BoxLayout: 
     Button: 
      text: "Button 1" 
      on_press: root.show_buttons(self.text) 
     Button: 
      text: "Button 2" 
      on_press: root.show_buttons(self.text) 
+0

什麼是你的問題被按下的第一按鈕中的一個? –

+0

問題是,如果要添加的按鈕的數量是動態的,我可以如何使用.kv文件來定義所有圖形元素? – Agenobarb

+0

我不是一個kivy專家,當我使用它時,我特意避開了kivy語言......但我認爲你別無選擇,只能在你的Python代碼中定義它們。說實話,你可以在你的.kv中動態創建它們,它在Python中可能會更容易。 –

回答

0

如果其真正的動態那麼你應該做的蟒蛇。

def show_buttons(self, button): 

    self.clear_widgets() # I guess I need this 


    for item in buttons[button]: 
     self.add_widget(Button(text=item)) 

如果它不是是動態,我會建議創造更多屏幕並切換到他們時使用ScreenManager

相關問題