Search code examples
pythonpython-3.xkivykivy-language

How to create Variables / properties in the kv file?


I want to create a "property" in my rouded button to be able to do something like:

RoundedButton:
    radius: 30

My python code:I have this class in Python:

class RoundedButton(Button):
    radius = NumericProperty(30)
        

And in my kv file:

<RoundedButton@Button>:
    background_color: 0,0,0,0  # the last zero is the critical on, make invisible
    canvas.before:
        Color:
            rgba: (.4,.4,.4,1) if self.state=='normal' else (0,.7,.7,1)  # visual feedback of press
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [10,]



<MenuScreen>
    GridLayout:
        size: root.width, root.height
        GridLayout:
            RoundedButton:
                size: 300, 300

And I would like to write something like that:

<RoundedButton@Button>:
    radius: radius
    background_color: 0,0,0,0  # the last zero is the critical on, make invisible
    canvas.before:
        Color:
            rgba: (.4,.4,.4,1) if self.state=='normal' else (0,.7,.7,1)  # visual feedback of press
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [radius,]


<MenuScreen>
    GridLayout:
        size: root.width, root.height
        GridLayout:
            RoundedButton:
                size: 300, 300
                radius: 10

Solution

  • RoundedButton:
        radius: 30
    

    You can and...have. This is the way to do it.

    However, it comes with some gotchas and race conditions relating to when exactly the property is created and may be accessed. You may or may not hit these. I generally consider that it's better practice to define the class and its properties in Python.

    radius: radius
    

    This one line doesn't make sense, you variable radius is not defined, set it to some actual value.