Python kivy:如何在C盘外使用filechooser访问文件

时间:2014-09-24 23:39:02

标签: python kivy filechooser

我是Kivy的初学者。

当我尝试在kivy.uix.filechooser模块上重新实现教程时,我只能访问C:驱动器上的文件,而不能访问其他驱动器上的文件。我试图寻找filechoser的根源,但无济于事。

有没有办法访问其他驱动器?

1 个答案:

答案 0 :(得分:6)

您需要更改filechooser.path值:

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

Builder.load_string('''
<MyWidget>:
    file_chooser: file_chooser
    FileChooserListView:
        id: file_chooser
''')

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.file_chooser.path = "D:\\"

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

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

更高级的例子:

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

Builder.load_string('''
#:import lv kivy.uix.listview
#:import la kivy.adapters.listadapter

<MyWidget>:
    drives_list: drives_list
    file_chooser: file_chooser
    ListView:
        id: drives_list
        adapter:
            la.ListAdapter(data=root.get_win_drives(), selection_mode='single', allow_empty_selection=False, cls=lv.ListItemButton)
    FileChooserListView:
        id: file_chooser
''')

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.drives_list.adapter.bind(on_selection_change=self.drive_selection_changed)

    def get_win_drives(self):
        if platform == 'win':
            import win32api

            drives = win32api.GetLogicalDriveStrings()
            drives = drives.split('\000')[:-1]

            return drives
        else:    
            return []

    def drive_selection_changed(self, *args):
        selected_item = args[0].selection[0].text
        self.file_chooser.path = selected_item

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

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

here获取可用驱动器号的配方。