问题
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()
回答1:
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.
Easy fix:
class MyWidget(BoxLayout):
def selected(self,filename):
try:
self.ids.image.source = filename[0]
except:
pass
来源:https://stackoverflow.com/questions/43452697/browse-an-image-file-and-display-it-in-a-kivy-window