【问题标题】:Kivy: How to load images from a list by a for loop?Kivy:如何通过 for 循环从列表中加载图像?
【发布时间】:2020-10-10 16:58:22
【问题描述】:

我有图片路径列表:

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

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

image = StringProperty(images[0])

然后在.kv 文件中读取图像:

AsyncImage:
    source: root.pic

我努力做的事情是,每次单击按钮时,显示的图像都会更改为列表中的下一个。 注意列表中元素的数量变化

我想这可以使用StringProperty 来完成,for loop 遍历存储在images 变量下的图像和ids 在.kv 文件中,但我不知道如何显示它们一个接一个,而不是一次。我正在摆弄代码,试图想出一些有用的东西,这就是为什么我创建了Picture 类但没有完成display 方法。

我的 main.py 文件:

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


images = ['./picture0.png', './picture1.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

【问题讨论】:

    标签: python python-3.x image kivy


    【解决方案1】:

    是的,您需要跟踪您在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]
    

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

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

    【讨论】:

    • 非常感谢!我真的很喜欢您使用模数按顺序选择特定图像的方式。
    猜你喜欢
    • 2020-04-25
    • 2021-11-20
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2023-03-03
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多