Search code examples
pythonpython-3.xkivykivy-language

Kivy: Update CheckBox State without call 'on_active' method


I have this simple code here: a CheckBox and a Widget where I want to add the CheckBox.
When the App starts I want to update the CheckBox.state from a dictionary or from a .json file. Here I directly typed 'down'. The main problem is that when I update the state from 'normal' to 'down' it calls the method on_action: and here I have some function that I want to call just when I press the CheckBox.
How can I initialize CheckBox.state (from a dict or .json file -> I know how to do that) without call that on_action that executes my function there.

class AddCheckBox(Widget):
    def __init__(self, **kwargs):
        super(AddCheckBox, self).__init__(**kwargs)
        check_box = ChBox()
        check_box.update_state = 'down'
        self.add_widget(check_box)

class ChBox(CheckBox):
    update_state = StringProperty('normal')
    def some_function(self):
        print("Function is called")
AddCheckBox:
<AddCheckBox>:
<ChBox>:
    state: root.update_state
    on_active: root.some_function()

Solution

  • You can accomplish this, in a sort of clunky approach, by defining a Property ignore_state_change, like this:

    class ChBox(CheckBox):
        update_state = StringProperty('normal')
        ignore_state_change = BooleanProperty(True)
    
        def some_function(self):
            if self.ignore_state_change:
                return
            print("Function is called")
    
        def on_parent(self, *args):
            self.ignore_state_change = False
    

    The on_parent() method changes the ignore_state_change to not ignore any state changes after that.