【问题标题】:How do I get info of a file selected with fileChooser in Kivy?如何获取在 Kivy 中使用 fileChooser 选择的文件的信息?
【发布时间】:2013-11-13 04:04:08
【问题描述】:

如何获取通过 fileChooser 选择的文件的信息?以下是我的一些代码块:

self.fileChooser = fileChooser = FileChooserListView(size_hint_y=None, path='/home/')
...
btn = Button(text='Ok')
btn.bind(on_release=self.load(fileChooser.path, fileChooser.selection))
...
def load(self, path, selection):
    print path,  selection

它的作用是在我最初打开 fileChooser 时打印实例中的路径和选择。当我选择一个文件并单击“确定”时,没有任何反应。

【问题讨论】:

标签: python kivy filechooser


【解决方案1】:

这个例子可能对你有所帮助:

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

【讨论】:

    【解决方案2】:
    btn.bind(on_release=self.load(fileChooser.path, fileChooser.selection))
    
    ...
    def load(self, path, selection):
        print path,  selection
    

    这是对 python 语法的误用。问题是,您需要将 function 传递给 btn.bind。该函数被存储,然后当on_release事件发生时,该函数被调用。

    你所做的不是传入函数,而是简单地调用它并传递结果。这就是为什么您在打开文件选择器时会看到打印一次路径和选择的原因 - 这是该函数实际调用的唯一一次。

    相反,您需要传入要调用的实际函数。由于范围可变,您必须在这里小心一点,并且有多种潜在的解决方案。以下是一种可能性的基础知识:

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

    partial 函数接受一个函数和一些参数,并返回一个自动传递这些参数的新函数。这意味着当 on_release 发生时,bind 实际上有一些东西要调用,这又会调用 load_from_filechooser,而 load_from_filechooser 又会调用你原来的加载函数。

    您也可以在不使用局部的情况下执行此操作,但这是一种有用的通用技术,在这种情况下(我认为)有助于弄清楚发生了什么。

    我使用了对 fileChooser 的引用,因为您不能直接在函数中引用 fileChooser.path 和 fileChooser.selection - 您只能在定义函数时获取它们的值。这样,我们跟踪 fileChooser 本身,仅在稍后调用该函数时提取路径和选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多