How can I make many buttons in a dynamic language?

I want to make many buttons in a dynamic language in kv language. But now I can’t ... Now I will show the source.


BoxLayout:
    orientation: 'vertical'
    pos: root.pos
    size: root.size

    GridLayout:
        rows: 2
        spacing: 5
        padding: 5

        Button:
            text: "X0"
            on_press: root.X(0)
        Button:
            text: "X1"
            on_press: root.X(1)

I want to do as in code

BoxLayout:
    orientation: 'vertical'
    pos: root.pos
    size: root.size

    GridLayout:
        rows: 2
        spacing:5
        padding:5

        for i
            Button:
                text: "X#{i}"
                on_press: root.X(i)

How can i do this?

+4
source share
2 answers

Such loops are not possible in kv, except to do some dirty hacks.

To create a set of buttons dynamically, use a ListView or add them to the loop inside the py file.

Example:

from functools import partial

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.add_buttons()

    def add_buttons(self):
        for i in xrange(5):
            button = Button(
                text='X' + str(i),
                on_press=partial(self.X, number=i)
            )
            self.add_widget(button)

    def X(self, caller, number):
        print  caller, number
+1
source

I do not think that this can be done in a file kv. However, if you can write the kv line in a python file, you can do something like this:

from kivy.app import App
from kivy.lang import Builder

kv_string = """
BoxLayout:
    orientation: 'vertical'
    pos: root.pos
    size: root.size

    GridLayout:
        rows: 2
        spacing: 5
        padding: 5
""" + ''.join(["""
        Button:
            text: "X{0}"
            on_press: root.X({0})
""".format(i) for i in range(6)])

class MyApp(App):
    def build(self):
        w = Builder.load_string(kv_string)
        return w

if __name__ == '__main__':
    MyApp().run()
-1

All Articles