Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kivy: how to make an image act like a button

I'm new to Kivy. I want an image to change into a different one when it is pressed (touched). There should be some easy way of doing this but I can't figur out what.

<Game>
   Image:
     id: "11"
     center_x: root.width / 2 - root.height * 1/5 * 1.5 
     center_y: root.height * 1/5
     size: root.height / 6, root.height / 6
     source: root.images[0]

This is part of my code. I don't know how to make my image 'pressable'. Does it have to be a button of some sort?

like image 387
Mariusz Avatar asked Oct 19 '25 04:10

Mariusz


1 Answers

No it doesn't have to be a button. Without adding any extra objects, you can also use the on_touch_down event of the widget class (which also happens to be the base class of Image).

<Game>
    Image:
        id: "11"
        center_x: root.width / 2 - root.height * 1/5 * 1.5 
        center_y: root.height * 1/5
        size: root.height / 6, root.height / 6
        source: root.images[0]
        on_touch_down: root.image_press(*args) 

The args contains the extra parameter for the event: http://kivy.org/docs/api-kivy.uix.widget.html?highlight=on_touch_down#kivy.uix.widget.Widget.on_touch_down. Here I'm assuming your handler is named image_press and is added to the Game class.

Before you start down this road though, consider whether your objective would be fulfilled by the predefined classes e.g. modifying the background property of a button as you suggested. That's likely to be much simpler in the long run if you also want some of the other complex behaviours that the kivy devs have already built in.

like image 186
tiktok Avatar answered Oct 20 '25 18:10

tiktok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!