Reputation: 607
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?
Upvotes: 4
Views: 4561
Reputation: 11
You can do it in kv lang, and you don't need to use any callbacks or additional classes. Just use on_touch_down
with a condition. if self.collide_point(*args[1].pos)
then print("foo")
<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: if self.collide_point(*args[1].pos): print("foo")
Upvotes: 1
Reputation: 7349
I believe the best way you could do this, is using a dynamic class created on the fly in your kv file http://kivy.org/docs/api-kivy.lang.html#dynamic-classes
<ImageButton@ButtonBehavior+Image>:
on_press: self.parent.callback()
# this class is created on the fly, named ImageButton and subclasses ButtonBehavior and Image
# It's basically an Image that can act like a Button.
<Game>
ImageButton:
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]
Where callback()
is a method in Game
that changes the source of the image.
Inside Game
class:
def callback(self, instance, value):
self.ids['11'].source = new_source
# or you could switch sources each click for instance
or something similar(look here: http://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.ids)
Upvotes: 2
Reputation: 456
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.
Upvotes: 5