Drew
Drew

Reputation: 1261

kivy python 3.x loop add widgets .kv

I have a python script like such:

class GuiApp(App):
    def build(self):
        #for i in range(24):
            #Grid.add_widget(Button(text='Test'))
        return Gui()

class Gui(BoxLayout):
    pass

And I have a .kv file like such:

<Gui>:
  BoxLayout:
    orientation: 'vertical'
    Button:
      text: 'Top'
    GridLayout:
      id: Grid
      cols: 5
      rows: 5

How do I apply a loop to add the 24 buttons to the GridLayout?

I thought that I could call the id Grid like shown in the python comments, but that fails.

How do I go about applying a loop to add buttons to the GridLayout in the kv file with the id Grid?

Upvotes: 4

Views: 4771

Answers (2)

Drew
Drew

Reputation: 1261

I seemed to have figured out how to do the loop propery:

py

class GuiApp(App):

    def build(self)
        g = Gui()
        for i in range(24):
            g.grid.add_widget(Button(text='test'))
        return g

class Gui(BoxLayout):
    grid = ObjectProperty(None)

kv

<Gui>:
  grid: Grid
  BoxLayout:
    orientation: 'vertical'
    Button:
      text: 'Top'
    GridLayout:
      id: Grid
      cols: 5
  rows: 5

In order for it to work I needed to reference it _grid: Grid in the .kv file to be found by the ObjectProperty, the grid, when used in python needed to be lowercase

Upvotes: 5

Joran Beasley
Joran Beasley

Reputation: 113950

def build(self):
    layout = GridLayout()
    for i in range(24): layout.add_widget(...)
    return layout

I think at least

class GuiApp(App):
    def build(self):
        g = Gui()
        for i in range(24):
            g.Grid.add_widget(Button(text='Test'))
        return g

class Gui(BoxLayout):
    Grid = ObjectProperty(None)

Upvotes: 2

Related Questions