Skip to content Skip to sidebar Skip to footer

Position Of Widgets In GridLayout

I'm trying to create a grid of widgets with each 'cell' widget having a rectangle I can change the color of later. When I run the code below with the line grid.add_widget(Button(t

Solution 1:

I will show an example on how you can achieve this. I will create a grid class, and add the cell widgets to it. But I will only use one canvas (the gridlayouts canvas). So the cell class will contain an InstructionGroup, rather than make multiple canvases.
To be able to set size, position and color of each cell later, those attributes must be attributes of the cell class.
The attributes will be set in MyGrid's set_attributes method.
First when the app is running, you can get the positions of the cells, hence I use the Clock.schedule_once method. That will execute the next frame.
And to demonstrate how to change the colors, I create a Clock.schedule_interval, to animate the colors of the cells with random colors.

So here is the example:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Rectangle, Color, InstructionGroup
from kivy.clock import Clock

from random import uniform

XSIZE=2
YSIZE=2

class Cell(Widget):
    def __init__(self, i, **kwargs):
        super(Cell, self).__init__(**kwargs)
        self.ig = InstructionGroup()
        self.rect = Rectangle()
        self.color = Color(0.2, 0.2, 0.2*i)
        self.ig.add(self.color)
        self.ig.add(self.rect)



class MyGrid(GridLayout):
    def __init__(self,**kwargs):
        super(MyGrid,self).__init__(**kwargs)
        self.rows=YSIZE
        self.cols=XSIZE
        for i in xrange(4):
            self.add_widget(Cell(i))
            self.canvas.add(self.children[0].ig)

        Clock.schedule_once(self.set_attributes)
        Clock.schedule_interval(self.change_color,1)

    def set_attributes(self,dt):
        for i in self.children:
            i.rect.pos = i.pos
            i.rect.size = i.size

    def change_color(self,dt):
        for i in self.children:
            i.color.rgb = (uniform(0.0,1.0),uniform(0.0,1.0),uniform(0.0,1.0))


class GameApp(App):
    def build(self):
        return MyGrid()


if __name__ == '__main__':
    GameApp().run()

Post a Comment for "Position Of Widgets In GridLayout"