Search code examples
pythonkivywidgetkivy-language

How can I modify my .kv file to update the shown image/widget instead of adding another image/widget onto my kivy app?


I currently have the problem that I want to add an image to my kivy app once I click a certain button that receives inputs from sliders (so basically the button adds a different image for a given slider value). The issue that I have now is that, my current solution uses the add_widget command which obviously results in the button adding a new widget every time it is clicked. What I would like instead is that, the existing widget is updated instead of a new one being added.

test.kv:

#: import Factory kivy.factory.Factory


<TestImage1@Image>:
    source: 'test_1.jpg'
    #allow_stretch: True
    #keep_ratio: True
    pos_hint: {'centre_X':0.7}


<TestImage2@Image>:
    source: 'test_2.jpg'
    #allow_stretch: True
    #keep_ratio: True
    pos_hint: {'centre_X':0.7}


<TestBoxLayout>:
    orientation:'vertical'
    size: root.width,root.height
    font_size: 20
    padding: 100
    spacing: 10

    Slider:
        id: slider
        min: 1
        max: 2
        step: 1

    Button:
        text: 'press me'
        on_press: 
            if slider.value == 1: root.add_widget(Factory.TestImage1())
            elif slider.value == 2: root.add_widget(Factory.TestImage2())
        on_release: print("ahhh")
        on_state:
        #print("my current state is {}".format(self.state))
        size_hint: (0.3,0.3)

test.py:

import kivy
kivy.require('2.0.0')

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


class TestBoxLayout(BoxLayout):
    pass


class TestApp(App):
    def build(self):
        return TestBoxLayout()


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

Edit: This is an extension of the solution from my previous question: How do I load an image into a kivy window using a button?


Solution

  • <TestBoxLayout>:
        orientation:'vertical'
        size: root.width,root.height
        font_size: 20
        padding: 100
        spacing: 10
    
        Slider:
            id: slider
            min: 1
            max: 2
            step: 1
    
        Button:
            text: 'press me'
            on_press: img.source = 'test_1.jpg' if slider.value == 1 else 'test_2.jpg'
            size_hint: (0.3,0.3)
    
        Image:
            id: img
            color: (0, 0, 0, 0) if self.source is None else (1, 1, 1, 1)
            pos_hint: {'centre_X':0.7}