Prak
Prak

Reputation: 3

Adding custom Buttons Dynamically Kivy

I want to create custom buttons based on some list, dynamically in floatlayaout. How can I forward from here?

from kivy.uix.button import ButtonBehavior
from kivy.uix.image import Image

class Home(ScreenManager):
    pass

class FirstSc(Screen):
    pass

class ImBut(ButtonBehavior, Image):
    pass

class SecSc(Screen):
    pass

class Category(Screen):
    pass

customButton is what I created in the root widget of the kivy, and want it to be populated dynamically based on the list I would provide, in "SecSc" screen floatlayout. how can I access the custombutton and add it to the 'SecSc' class?

root_widget = Builder.load_string('''
Home:
    FirstSc:
    SecSc:
    Category:
`THIS IS THE CUSTOM BUTTON`
<customButton@Button>
    id: custbut
    font_size: 0.65 * self.height
    size_hint: (.15,.1)
    border_radius: [18]
    canvas.before:
        Color:
            rgba: self.back_color
        RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: self.border_radius

<FirstSc>:
    name: '1st'
    FloatLayout:
        canvas.before:
            Rectangle:
                source: 'bg.png'

<SecSc>:
    name: '2nd'
    FloatLayout:
        canvas.before:
            Rectangle:
                source: 'bg.png'
        FloatLayout:
            id: grid
            `HERE I WOULD LIKE TO ADD BUTTONS`
<Category>:
    name: 'category'

''')

class MyiApp(App):
    def build(self):
        return root_widget

MyiApp().run()

Upvotes: 0

Views: 1029

Answers (2)

Prak
Prak

Reputation: 3

Thank you. got it working. Here is how it looks -

    def on_enter(self, *args):
        count = 0
       ab = ["A", "D", "D"]
        self.buttons = []
        for i,j in enumerate(ab):
            self.buttons.append(Factory.ImButb(text=j, on_press=self.o_p))
            self.ids.grid.add_widget(self.buttons[i])
            count += 1
        print(self.buttons)
    def o_p(self, instance):
        print(str(instance.text))

Upvotes: 0

John Anderson
John Anderson

Reputation: 38947

Perhaps this can get you started. Modify your SecSc class:

class SecSc(Screen):
    def on_enter(self, *args):
        count = 0
        for txt in ["Abba", "Dabba", "Doo"]:
            butt = Factory.CustomButton(text=txt, pos=(50, count*75))
            self.ids.grid.add_widget(butt)
            count += 1

The use of the on_enter() is just an example. The key is using the Factory to create a Widget that is defined only in kv.

Upvotes: 2

Related Questions