浏览图像文件并将其显示在kivy窗口中

浏览图像文件并将其显示在kivy窗口中

本文介绍了浏览图像文件并将其显示在kivy窗口中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Kivy的初学者,尝试使用kivy fileChooser浏览图像文件,然后将其显示在窗口上.在下面,您找到了我的代码,但它无法完成任务.它仅在控制台上显示?PNG".请和我一起检查一下!

I am a beginner in Kivy and trying to browse an image file using kivy fileChooser and then displaying it on the window. Bellow you find my code but it wouldn't do the task. It just displays '?PNG' on the console. Please, check this out with me !

    import kivy
    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    from kivy.lang import Builder
    from kivy.uix.image import Image
    import os

    Builder.load_string("""
    <MyWidget>:
        id: my_widget
        Button
            text: "open"
            on_release: my_widget.open(filechooser.path,
    filechooser.selection)
        FileChooserListView:
            id: filechooser
            on_selection: my_widget.selected(filechooser.selection)
    """)

    class MyWidget(BoxLayout):
        def open(self, path, filename):
            with open(os.path.join(path, filename[0])) as f:
                print f.read()

        def selected(self, filename):
            return Image(source=filename[0])

    class MyApp(App):
        def build(self):
            return MyWidget()

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

推荐答案

尝试一下:
我排除了打开按钮,只是在选择时显示它.
因此,我们添加了Image小部件,并在选择它时设置其来源.

Try this:
I exclude the open button, and just display it when selected.
So we add an Image widget, and set its source when selected.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder


Builder.load_string("""
<MyWidget>:
    id: my_widget
    FileChooserListView:
        id: filechooser
        on_selection: my_widget.selected(filechooser.selection)
    Image:
        id: image
        source: ""
""")


class MyWidget(BoxLayout):

    def selected(self,filename):
        self.ids.image.source = filename[0]


class MyApp(App):
    def build(self):
        return MyWidget()


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

这只是一个最小的例子.如果您转到目录,它将引发错误.所以您需要处理.

This is just a minimal example. It will throw an error if you go a directory up. So you need to handle that.

轻松修复:

class MyWidget(BoxLayout):

    def selected(self,filename):
        try:
            self.ids.image.source = filename[0]
        except:
            pass

这篇关于浏览图像文件并将其显示在kivy窗口中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 09:03