yashC
yashC

Reputation: 985

Update the source of rectangle in canvas to change background image

the basic snippet from KV file:

<FirstScreen>:
    background_image_rect: background_image_rect

    id: First_screen
    name: "First"
    canvas:
        Rectangle:
            id: background_image_rect
            pos: 0,0
            size: self.size
            source: "1.jpg"
    FloatLayout:
         ....

I have a button defined in the float layout that I want to result in changing the background image of the screen when pressed.

I have tried what my limited knowledge of Kivy permits but I dont seem to get it to work.

When I tried to use Id with the rectangle it wont give error running but the I wont be able to look up the id using root.ids.background_image_rect.souce in on_press function. is it legal to have id for rectangle in canvas ?

How to I achieve the goal of updating the background image of the screen when the button is pressed ?

Upvotes: 0

Views: 415

Answers (1)

inclement
inclement

Reputation: 29450

The id system is at the widget level, it doesn't work for graphics instructions.

The simplest solution is to bind the source to a property and update that property:

<FirstScreen>:
    background_image_rect: background_image_rect

    id: First_screen
    name: "First"

    canvas:
        Rectangle:
            id: background_image_rect
            pos: 0,0
            size: self.size
            source: root.the_rect_source

And in Python:

class FirstScreen:
    the_rect_source = StringProperty("...")

Upvotes: 1

Related Questions