Reputation: 961
I am trying to learn kivy by doing fun stuff, but is kind of hard to grasp the kivy way of doing things.
In Tkinter I created thumbnail gallery with a forloop and bind each individual image to a callback, It just passes the info (path) of the clicked image to the callback to open the image. But I can seem to understand how to do such a simple thing in kivy, so I need some help.
Using the Button widget worked; I tried creating a gallery with buttons and change their background to images but the images get stretched and distorted (Not what I want).
So I made the thumbnail gallery with the Image widget and the thumbs showed just find, but I can't find a way to pass the clicked thumb info to the callback for each thumb (callback event) to work the way is supposed to.
I bind each thumb with on_touch_down property but when the call back is executed all the thumbs info is passed to the callback in one click witch is not what I want, I want only the info of the individual thumb that was clicked to be passed to the callback. I read kivy docs but get more and more confused. Any way here is my bare bone code, any help will be appreciated thank you so much.
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
import glob
class Image_Gallery(GridLayout):
def __init__(self):
super(Image_Gallery, self).__init__()
images = glob.glob('C:\Users\Public\Pictures\Sample Pictures\*.jpg') # windows 7 sample pictures dir looks great
self.cols=3
for img in images:
thumb = Image(source=img)
thumb.bind(on_touch_down=self.callback) # I tried on_touch property but does not work with images only buttons
self.add_widget(thumb)
def callback(self, obj, touch):
# This should print only the clicked image source.
# (but instead is printing all images sources at once)
print obj.source
class mainApp(App):
def build(self):
return Image_Gallery()
if __name__ == '__main__':
mainApp().run()
Upvotes: 3
Views: 3408
Reputation: 2645
The on_touch events dispach the event on all the widgets in your app, you must define your own Image class and redefine the on_touch method:
...
class MyImage(Image):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
print self.source
class Image_Gallery(GridLayout):
def __init__(self, **kwargs):
super(Image_Gallery, self).__init__(**kwargs)
images = glob.glob('C:\Users\Public\Pictures\Sample Pictures\*.jpg')
self.cols = 3
for img in images:
thumb = MyImage(source=img)
self.add_widget(thumb)
...
Upvotes: 9