Python Kivy:如何在循环中添加多个小部件

Python Kivy: How to add multiple widgets in a loop

我是 Python 的新手,也是 Kivy 的新手,所以我可能很难解决一个简单的任务。我需要一个带有两个按钮的主屏幕:Button1 和 Button2。当我按下一个按钮时,应该会出现第二个屏幕,再次显示按钮的数量。第二个屏幕上的按钮数量是动态的,但为简单起见,我们可以假设我们知道它。

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)

如果它 真正动态 那么你应该在 python 中进行。

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

按下