Search code examples
pythonkivyanimated-gifkivy-language

How do I bind two different gifs to a toggle button in kivy?


I got this code from a helpful user on here and it is almost perfect.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<ExampleApp>:
    id: main
    orientation: "vertical"
    Button:
        size_hint_x: None
        size_hint_y: None
        height: 300
        width: self.height
        center: self.parent.center
        text: ""
        on_press: gif.anim_delay = 0.09
        on_press: gif._coreimage.anim_reset(True)

        Image:
            id: gif
            source: 'power_on.gif'
            center: self.parent.center
            height: 300
            width: self.height
            allow_stretch: True
            anim_delay: -1
            anim_loop: 1


""")

class ExampleApp(App, BoxLayout):
    def build(self):
        return self


if __name__ == "__main__":
    ExampleApp().run()

I need it to use two different gifs the power_on gif when it's toggled on and the power_off gif when it's toggled off. so I tried to change it to a toggle button and added

on_press: gif.source="power_off.gif"

But that didn't work at all. It never even played the power_on gif because it immediately changed the source of the gif to power_off

What would be the correct way to go about this?


Solution

  • The following admits the first gif is power_off.gif:

    -consider adding the StringProperty import, that property will keep the current gif image source

    from kivy.properties import StringProperty
    

    -Add a method to handle the different change:

    class ExampleApp(App, BoxLayout):
        power = StringProperty('power_off.gif')
    
        def build(self):
            return self
    
        def change_state(self):
            if self.power == 'power_on.gif':
                self.power = 'power_off.gif'
            else:
                self.power = 'power_on.gif'
    

    -then add those changes in your kv:

    Builder.load_string("""
    <ExampleApp>:
        id: main
        orientation: "vertical"
        Button:
            size_hint_x: None
            size_hint_y: None
            height: 300
            width: self.height
            center: self.parent.center
            text: ""
            on_press: gif.anim_delay = 0.09
            on_press: gif._coreimage.anim_reset(True); root.change_state()
    
            Image:
                id: gif
                source: root.power
                center: self.parent.center
                height: 300
                width: self.height
                allow_stretch: True
                anim_delay: -1
                anim_loop: 1
    
    
    """)