danatron
danatron

Reputation: 717

dynamically adding kivy widgets

I can add a new widget, but it something isn't connecting correctly. The canvas seems like its in the wrong coordinate system.

My .py

class Ship(Widget):
   def __init__(self, **kwargs):
       super(Ship, self).__init__(**kwargs)
       self.vel = 10

class Game(Widget):

    def __init__(self, **kwargs):
       super(Game, self).__init__(**kwargs)
       self.ship = Ship()
       self.add_widget(self.ship)
       self.ship.center = self.center

My .kv

<Ship>
   size: 50, 50
   canvas:
       Color:
           rgb: 0, 0, 1
       Rectangle:
           size: self.size
           pos: self.pos
<Game>
   canvas.before:
       Color:
           rgb: 0, 0, 0
       Rectangle:
           size: self.size
           pos: self.pos

This creates the image: enter image description here

I would expect the blue box to be dead center.

Upvotes: 0

Views: 1052

Answers (1)

kitti
kitti

Reputation: 14794

At the time you assign the center position, layout has not yet been calculated. Every widget starts off at size 100, 100 by default, and your Ship is being positioned correctly in the center of that 100, 100 area. If you want the Ship to remain centered, you need to bind the properties:

class Game(Widget):
    def __init__(self, **kwargs):
       super(Game, self).__init__(**kwargs)
       self.ship = Ship()
       self.add_widget(self.ship)
       self.bind(center=self.ship.setter('center'))

Upvotes: 1

Related Questions