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

时间:2017-04-17 13:42:47

标签: python user-interface kivy kivy-language

我是Kivy的初学者,尝试使用kivy fileChooser浏览图像文件,然后在窗口中显示它。你找到我的代码,但它不会完成任务。它只是在控制台上显示“?PNG”。请和我一起检查一下!

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

1 个答案:

答案 0 :(得分:2)

试试这个:
我排除了打开按钮,只在选中时显示它 所以我们添加一个Image小部件,并在选中时设置其来源。

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

这只是一个很小的例子。如果你去一个目录,它会抛出一个错误。所以你需要处理它。

轻松修复:

class MyWidget(BoxLayout):

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