8

How to list only directories in Kivy FileChooser? I've read about callback filters, but didn't found any examples.

My Kv code:

<Saveto>:
    select: select
    chooser: chooser
    orientation: 'vertical'
    FileChooserIconView:
        id: chooser
        size_hint_y: 0.9
        rootpath: home
        dirselect: True
        filters: ['How to list folders only?']
    Button:
        ...select button...
Cyber Tailor
  • 443
  • 7
  • 18

4 Answers4

14

Here's an example:

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

from os.path import join, isdir

Builder.load_string("""
<MyWidget>:
    FileChooserListView:
        filters: [root.is_dir]
""")

class MyWidget(BoxLayout):
    def is_dir(self, directory, filename):
        return isdir(join(directory, filename))

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

if __name__ == '__main__':
    MyApp().run()

Note that the property is called filters, not filter, because it's a list, for example, a list of callbacks.

Nykakin
  • 8,657
  • 2
  • 29
  • 42
3

You can also do it in KV directly:

<Saveto>:
    select: select
    chooser: chooser
    orientation: 'vertical'
    FileChooserIconView:
        id: chooser
        size_hint_y: 0.9
        rootpath: home
        dirselect: True
        filters: [lambda folder, filename: not filename.endswith('')]
    Button:
        ...select button...
Roman B.
  • 117
  • 9
2

If you want to use the directory without any file on it you can use:

os.path.dirname(filename)

in the following way (example where the directory is just used to print the directory as a label in the right side of the screen):

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
import os


Builder.load_string("""
<MyWidget>:
    FileChooserIconView:
        filters: [root.selected]
    BoxLayout:
        Label:
            id: mypath
            text: ''
""")

class MyWidget(BoxLayout):
    def selected(self, directory, filename):
        self.ids.mypath.text = os.path.dirname(filename)


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

if __name__ == '__main__':
    MyApp().run()

Hope it helps

Ivan
  • 759
  • 10
  • 18
0

This is a bit of a hack, but seems to work and can be done in the kv file only:

dirselect: True
filters: ['']

Only folders are shown in FileChooser.

Nando Machado
  • 182
  • 1
  • 11