Skip to content

Instantly share code, notes, and snippets.

@borrascador
Created January 22, 2016 06:19
Show Gist options
  • Select an option

  • Save borrascador/58eba95b5e5d02cee1ec to your computer and use it in GitHub Desktop.

Select an option

Save borrascador/58eba95b5e5d02cee1ec to your computer and use it in GitHub Desktop.

Revisions

  1. borrascador created this gist Jan 22, 2016.
    67 changes: 67 additions & 0 deletions sparsegridlayout.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    from kivy.app import App
    from kivy.uix.floatlayout import FloatLayout
    from kivy.properties import NumericProperty, ReferenceListProperty
    from kivy.event import EventDispatcher
    from kivy.animation import Animation

    from kivy.uix.button import Button

    class SparseGridLayout(FloatLayout):

    rows = NumericProperty(1)
    columns = NumericProperty(1)
    shape = ReferenceListProperty(rows, columns)

    def __init__(self, **kwargs):
    super(SparseGridLayout, self).__init__(**kwargs)

    self.make_grid()

    def do_layout(self, *args):
    shape_hint = (1. / self.columns, 1. / self.rows)
    for child in self.children:
    child.size_hint = shape_hint
    if not hasattr(child, 'row'):
    child.row = 0
    if not hasattr(child, 'column'):
    child.column = 0

    child.pos_hint = {'x': shape_hint[0] * 1. * child.row,
    'y': shape_hint[1] * 1. * child.column}
    super(SparseGridLayout, self).do_layout(*args)

    def make_grid(self):
    buttons = []
    for i in range(3):
    for j in range(3):
    buttons.append(GridButton(row=i, column=j,
    text='button ({}, {})'.format(i, j)))
    for button in buttons:
    self.add_widget(button)
    button.bind(on_release=self.animate)

    def animate(self, button):
    # Animation only works if ONE of the coordinates is 'x' or 'y'.
    # Does not work if BOTH are 'row' and 'column'
    anim = Animate(x=1, column=1)
    anim.start(button)

    class GridEntry(EventDispatcher):
    row = NumericProperty(0)
    column = NumericProperty(0)

    class GridButton(Button, GridEntry):
    pass

    # Animate class should now take row, column as arguments
    class Animate(Animation, GridEntry):
    pass

    class ExampleApp(App):
    def build(self):
    return SparseGridLayout(rows=3, columns=3)



    if __name__ == "__main__":
    ExampleApp().run()