Search code examples
pythonkivykivy-language

Getting a property from a different widget in Kivy


How can I use a property in a different widget? I have this code:

Python file

class Control(ToggleButton):
    width_multiplier = NumericProperty(1)


class MainScreen(StackLayout):
    pass


class HomeControl(App):

    def build(self):
        return MainScreen()


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

KV file

<Control>:
    size_hint: None,None
    height: '100dp'
    width: self.width_multiplier * self.height + (self.width_multiplier - 1) * spacing
    halign: 'center'

<MainScreen>:
    orientation: 'lr-tb'
    spacing: '10dp'
    padding: '15dp'

    Control:
        text: 'Button'

    Control:
        text: 'Long Button'
        width_multiplier: 2

The width of the Control widgets should be width_multiplier times the height of the widget plus the spacing between MainScreen’s children. How can I use the spacing property of MainScreen in the Control role? I'm new to Kivy so it’s probably a silly question but I hope someone can help me.


Solution

  • In your case you can use the parent property

    <Control>:
        size_hint: None,None
        height: '100dp'
        width: self.width_multiplier * self.height + (self.width_multiplier - 1) * self.parent.spacing[0]  <--- 
        halign: 'center'