How to change the source image from a KV file

37 views Asked by At

I wanted to create a simple rectangular widget with an image source. When I run it, of course the source image will show on screen. But if in the py file I wanted to change the image with something else like from a dog to a cat. I can't figure out how to go about it.

<RectBlock>:
    canvas:
        Rectangle
            size: 65, 90
            pos: self.pos
            source: 'dog.png' 
<MyWidget>:


class RectBlock(Widget):
    def __init__(self, **kwargs):
      super(RectBlock, self).__init__(**kwargs)

class MyWidget(Widget): 
  def __init__(self, **kwargs):
      super(MyWidget, self).__init__(**kwargs)
  
  block = (RectBlock(pos=(140,150)))
  self.add_widget(block)

I thought it is as simple as these below:

block.source = Image('cat.png') 

Nothing, it still shows the dog picture.

1

There are 1 answers

1
Tristan Casemajor On

I understand your question. You want the image to "refresh" while the application is being used, so if the source file changes, the image displayed by the widget will also change. There's no 'miracle formula' for this, the two files need to have the same name. Let me explain: we change the name of the image "dog.png" to animal.png and we also change the name of "cat.png" to animal.png. When you replace one file with the other you keep the same name but you change the data and so Kivy realises on its own that the content of the file has changed and refreshes the image but to do this the 2 files must have the same name. Tell me if I'm not clear, I can explain again.

Translated with DeepL.com (free version)