magenulcus
magenulcus

Reputation: 400

Kivy image update

I'm absolutely new to GUI desing and trying to create a very simple App using python and kivy with a little bit of animations after pressing buttons. But as I'm completely new to kivy I'm stuck. I think the answer is very easy but after roundabout 8h of trial and error and googling through the internet I'm desperate :-)

I have created a little App with a button and an Image. What I'm trying to do is changing the Image after "button_pressed". The code in kivy file:

<FirstTest>:
    my_image: my_image
    source_image: self.source_image
    Button:
        on_press: root.gamer.changeImage()
    My_Image:
        id: my_image
        source: self.parent.source_image    
<My_Image>:
    allow_stretch:True
    keep_ratio: False

And the python Code (only the necessary part):

class Player(object):

    def changeImage(self):
        FirstTest.source_image = 'new_image.png'


class My_Image(Image):
    pass  


class FirstTest(FloatLayout):
    my_image = ObjectProperty(None)
    source_image = StringProperty(None)
    source_image = 'First_Image.png'
    gamer = Player()
    def update(self, dt):
        print(self.source_image) #To see in realtime if the image source changed


class MyApp(App):
    def build(self):    
        game = FirstTest()
        Clock.schedule_interval(partial(FirstTest.update, FirstTest), 1/60)
        return game

When I start the App I see the Button and the "First_Image" loaded. But when I hit the button nothing changes. The only thing I see is that the source_image path changed in the console. I do not understand why the Image isn't reloaded with the new source. I thought when I change the path I will get a new Image and if I do this repeated I would get some kind of animation. But not even a single image changes. If I try to change the Objectproperty of "my_image" I got an error message with "ObjectProperty has no attribute source"

What do I miss? Please help!

Thanks in advance!

Upvotes: 0

Views: 3038

Answers (1)

bj0
bj0

Reputation: 8223

The most obvious problem I see with your code is that you are confusing class objects with instance objects.

FirstTest is a class object, and when you do:

game = FirstTest()

You are creating an instance of FirstTest. The instance will have its own properties and methods. This means that you don't want to call FirstTest.update but game.update.

Also, FirstTest.source_image = ... is wrong, as you are not changing the image source on the instance object in the GUI, but modifying the class definition. You will need to modify game.source_image instead. The easiest way to do this is to save a reference of game in the App object (self.game = game in build), and then reference it with App.get_running_app().game.

Upvotes: 2

Related Questions