Search code examples
pythonkivykivy-language

Python Kivy: How to add multiple widgets in a loop


I am relativly new to Python and totaly new to Kivy so I am strugling to solve probably a simple task. I need a main screen with two buttons: Button1 and Button2. When I press a button, the second screen should appear showing again the number of buttons. The numbers of buttons on the second screen is dynamic but we can assume for simplicity we know it.

python code:

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 file:

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)

Solution

  • If its truly dynamic then you should do it in 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))
    

    If its not that dynamic, I would recommend to create to more screens and switch to them when one of the first buttons are pressed using a ScreenManager