Kivy:如何通过for循环从列表中加载图像?

问题描述

我有带有图像路径的列表:

images = ['./picture0.png','./picture1.png','./picture2.png']

我的应用仅显示第一张图像picture0.png,因为我已经使用StringProperty手动声明了它,并显示了第一张图像的路径,该路径存储在类中的pic变量下。

image = StringProperty(images[0])

然后在.kv文件中,图像的读取方式为:

AsyncImage:
    source: root.pic

要做的是,每次单击按钮时,显示的图像都会更改为列表中的下一个图像。 请注意列表中元素的数量更改

我猜想可以使用StringProperty完成,for loop浏览存储在images变量下的图像和id文件内的.kv ,但我不知道如何一一显示它们,而是一次全部显示。我在摆弄代码,试图提出一些有用的东西,这就是为什么我创建了Picture类而没有完成display方法的原因。

我的main.py文件

from kivy.app import App
from kivy.uix.Boxlayout import BoxLayout
from kivy.properties import StringProperty


images = ['./picture0.png','./picture2.png']


class Picture(BoxLayout):
    source = StringProperty(None)


class Test(BoxLayout):
    image = StringProperty(images[0])

    def hit_button(self):
        self.btn = display()


def display():
    for filename in images:
        pic = Picture(source=filename)


class MainApp(App):
    def build(self):
        return test()


if __name__ == '__main__':
    MainApp().run()

我的.kv文件

<Test>:
    BoxLayout:
        orientation: 'horizontal'
        rows: 2
        BoxLayout:
            Button:
                text: 'click'
            AsyncImage:
                source: root.image


<Picture>
    Image:
        id: img
        source: root.source

解决方法

是的,您需要跟踪自己在images列表中的位置。您可以这样操作NumericProperty()

class Test(BoxLayout):
    image = StringProperty(images[0])
    index = NumericProperty(0)

    def hit_button(self):
        self.index += 1
        self.index %= len(images)
        self.image = images[self.index]

还需要在Button中为kv指定操作:

<Test>:
    BoxLayout:
        orientation: 'horizontal'
        rows: 2
        BoxLayout:
            Button:
                text: 'click'
                on_release: root.hit_button()
            AsyncImage:
                source: root.image