Kivy:如何在没有kv语言的情况下通过FileChooser select目录?

Kivy: How select directory by FileChooser without kv language?

Kivy manual中是使用kivy语言使用FileChooser的例子。我只想在 python 代码中使用 FileChooser。当我用鼠标标记目录时,按下按钮 Select Dir,实际上值在变量 FileChooser.path 中。 Select不使用此按钮的离子没有结果。 在示例的 kv 文件中使用了事件 on_selection,我将此事件与我的函数绑定,但没有效果。

我的问题:

  1. 如何仅使用鼠标获取路径值?
  2. 哪个class使用事件on_selection?

谢谢!

class Explorer(BoxLayout):   
    def __init__(self, **kwargs):
        super(Explorer,self).__init__(**kwargs)

        self.orientation = 'vertical'
        self.fichoo = FileChooserListView(size_hint_y = 0.8)
        self.add_widget(self.fichoo)

        control   = GridLayout(cols = 5, row_force_default=True, row_default_height=35, size_hint_y = 0.14)
        lbl_dir   = Label(text = 'Folder',size_hint_x = None, width = 80)
        self.tein_dir  = TextInput(size_hint_x = None, width = 350)
        bt_dir = Button(text = 'Select Dir',size_hint_x = None, width = 80)
        bt_dir.bind(on_release =self.on_but_select)

        self.fichoo.bind(on_selection = self.on_mouse_select)

        control.add_widget(lbl_dir)
        control.add_widget(self.tein_dir)
        control.add_widget(bt_dir)

        self.add_widget(control)

        return

    def on_but_select(self,obj):
        self.tein_dir.text = str(self.fichoo.path)
        return

    def on_mouse_select(self,obj):
        self.tein_dir.text = str(self.fichoo.path)
        return

    def on_touch_up(self, touch):
        self.tein_dir.text = str(self.fichoo.path)
    return super().on_touch_up(touch)
        return super().on_touch_up(touch)

几乎不需要做任何更改。

没有这样的事件on_selection,class里面有属性selection in FileChooserListView. You can use functionson_<propname>有这些属性,但是当你使用绑定,你应该只使用 bind(<propname>=.

第二件事是,正如您在文档中看到的那样,默认情况下 selection 包含选定文件的列表,而不是目录。要使目录真正可选择,您应该将 dirselect 属性 更改为 True.

最后一个是 on_mouse_select 签名:属性 用它的值触发,你应该算一下。

摘要更改为:

self.fichoo.dirselect = True
self.fichoo.bind(selection = self.on_mouse_select)

# ... and

def on_mouse_select(self, obj, val):

之后你会和按钮一样。


如果你不想用你实际所在的路径,而是选择的路径来填充输入,你可以执行以下操作:

def on_touch_up(self, touch):
    if self.fichoo.selection:
        self.tein_dir.text = str(self.fichoo.selection[0])
    return super().on_touch_up(touch)