Search code examples
pythonpropertieskivykivy-language

Setting property value at kv file doesn't affect the value of same variable at py simple code


By instantiating a custom GridLayout in the kv file, I set a value for the mes property, an integer. The value is not passed to the python class variable. I have declared the same property as NumericProperty, but when I run the code, the print statement shows up the default value set at py file rather than the value set at kv file. I can't figure why this happens.

The main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import NumericProperty

class FichaSemApp(App):
    pass

class ShowCal(GridLayout):
    mes = NumericProperty()
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        print('VALUE OF mes: ',self.mes)

FichaSemApp().run()

I'm using the init method because I need some computation for populating the grid.

The fichasem.kv

ShowCal:
    mes: 2
    cols: 7
    rows: 7

Solution

  • You might want to do the following:

    Program

    import kivy
    kivy.require('1.10.0')
    
    from kivy.app import App
    from kivy.uix.gridlayout import GridLayout
    from kivy.properties import NumericProperty
    
    
    class ShowCal(GridLayout):
        mes = NumericProperty()
    
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            print('VALUE OF mes: ', self.mes)
    
    
    class FichaSemApp(App):
        def build(self):
            return ShowCal()
    
    
    if __name__ == '__main__':
        FichaSemApp().run()
    

    Kivy File

    #:kivy 1.10.0
    
    <ShowCal>:
        mes: 2
        cols: 7
        rows: 7
    

    Output

    enter image description here