如何在缩略图库中制作可点击的kivy图像

2024-04-27 16:39:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着通过做有趣的事情来学习kivy,但是有点难以掌握kivy做事的方式。在

在Tkinter中,我创建了一个带有forloop的缩略图库,并将每个单独的图像绑定到一个回调函数,它只是将单击图像的信息(路径)传递给回调函数来打开图像。但我似乎能理解如何用kivy做这么简单的事情,所以我需要一些帮助。在

使用按钮小部件是有效的;我尝试创建一个带有按钮的库,并将其背景更改为图像,但图像会被拉伸和扭曲(不是我想要的)。在

所以我用图像小部件制作了缩略图库,拇指显示的只是find,但是我找不到一种方法来将点击的拇指信息传递给每个拇指(回调事件)的回调函数。在

我用on_touch_down属性绑定每个拇指,但是当执行回调时,所有的拇指信息都会在一次单击中传递给回调,这不是我想要的,我只想将单击的单个拇指的信息传递给回调。我读过kivy文档,但越来越困惑。不管怎样这里都是我最基本的代码,任何帮助都会很感激的谢谢你。在

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()

Tags: 函数from图像imageimportself信息on
1条回答
网友
1楼 · 发布于 2024-04-27 16:39:25

on_touch事件会在应用程序中的所有小部件上显示事件,您必须定义自己的图像类并重新定义on_touch方法:

...
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)
...

相关问题 更多 >