I am trying to use Kivy for the first time. I have imported a function from an external file using
#:import centerAlign helperFunctions.centerAlign
My function (centerAlign) looks like this:
def centerAlign(elem, parent):
pos = [parent.width/2-elem.width/2, parent.height/2-elem.height/2]
return pos
It's implementation looks like this:
GridLayout:
cols: 2
spacing: 10
size_hint: 0.5, 0.25
pos: centerAlign(self, root)
This fails because it's calculating a height and width of 100 for both elements (root and GridLayout). However, I know this should be working because when I say:
GridLayout:
cols: 2
spacing: 10
size_hint: 0.5, 0.25
pos: [root.width/2-self.width/2, root.height/2-self.height/2]
It works great! So I really don't understand what's happening here. I'm a bit new to Python so hopefully it's something simple that a seasoned veteran can shed some light on. Thanks in advance!
pos: [root.width/2-self.width/2, root.height/2-self.height/2]
When kv parses this line, it is able to see that it needs to update pos
when root.width, root.height, self.width or self.height change, because they are all referenced here. Bindings are automatically created to achieve this.
pos: centerAlign(self, root)
In this row there aren't any properties to bind to, so there is no update when anything changes. You therefore only get a result based on the initial value of the width/height, which is 100.
To solve this, either reference the properties you want to bind to in the kv line or write some other code to create the bindings you want.