How do I get info of a file selected with fileChooser in Kivy?

妖精的绣舞 提交于 2019-11-29 08:32:29
btn.bind(on_release=self.load(fileChooser.path, fileChooser.selection))

...
def load(self, path, selection):
    print path,  selection

This is a misuse of python syntax. The problem is, you need to pass a function to btn.bind. The function is stored, then when the on_release event occurs, the function is called.

What you have done is not pass in the function, but simply call it and pass the result. That's why you see the path and selection printed once when you open the filechooser - that's the one and only time the function is actually called.

Instead, you need to pass in the actual function you want to call. You have to be a bit careful here because of variable scoping, and there are multiple potential solutions. Below is the basics of one possibility:

def load_from_filechooser(self, filechooser):
    self.load(filechooser.path, filechooser.selection)
def load(self, path, selection):
    print path,  selection
...
from functools import partial
btn.bind(on_release=partial(self.load_from_filechooser, fileChooser))

The partial function takes a function and some arguments, and returns a new function that automatically passes those arguments. That means bind actually has something to call when on_release occurs, which in turn calls load_from_filechooser which in turn calls your original load function.

You could also do this without partial, but it's a useful general technique and in this case helps (I think) to make it clear what's going on.

I used a reference to fileChooser because you can't reference fileChooser.path and fileChooser.selection directly in your function - you would only get their values at the time the function is defined. This way, we track the fileChooser itself and only extract the path and selection when the function is later called.

This example might help you:

import kivy

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

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):
        print "selected: %s" % filename[0]


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

if __name__ == '__main__':
    MyApp().run()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!