Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kivy python 3.x loop add widgets .kv

Tags:

python

kivy

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?

like image 996
Drew Avatar asked Oct 12 '25 10:10

Drew


2 Answers

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

like image 64
Drew Avatar answered Oct 14 '25 11:10

Drew


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)
like image 26
Joran Beasley Avatar answered Oct 14 '25 11:10

Joran Beasley