【问题标题】:Python's Kivy FileBrowser doesn't index the files properlyPython 的 Kivy FileBrowser 无法正确索引文件
【发布时间】:2017-11-28 06:54:00
【问题描述】:

我有一个具有浏览功能的 Kivy 应用。浏览带有数字名称的文件时,它会以一种奇怪的方式显示它,它会按“最高有效位”样式对其进行排序。添加屏幕截图。 任何人都知道如何修复它以以正确的顺序显示它? (1,2,3... 而不是 1,10,100...)

非常感谢!

【问题讨论】:

    标签: python python-3.x python-2.7 kivy kivy-language


    【解决方案1】:

    您想要自然排序。为此,您需要使用类kivy.uix.filechooser.FileChooserControllersort_func 属性替换对文件排序的函数。

    一个基于@Darius Bacon 在他对Natural Sorting algorithm 的回答中展示的算法的示例:

    ma​​in.py

    import re
    from kivy.app import App
    from kivy.properties import ObjectProperty
    
    
    
    
    def natural_key(path):
        return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', path)]
    
    
    def natural_sort(files, filesystem):    
        return (sorted((f for f in files if filesystem.is_dir(f)), key = natural_key) +
                sorted((f for f in files if not filesystem.is_dir(f))))
    
    
    class RootWidget(FloatLayout):
        sort_func = ObjectProperty(natural_sort)
    
    
    
    class MainApp(App):
        def build(self):
            return RootWidget()
    
    if __name__ == '__main__':
        MainApp().run()
    

    ma​​in.kv:

    <RootWidget>:
        TabbedPanel:
            do_default_tab: False
    
            TabbedPanelItem:
                text: 'List View'
                BoxLayout:
                    orientation: 'vertical'
                    FileChooserListView:
                        sort_func: root.sort_func
    
    
            TabbedPanelItem:
                text: 'Icon View'
                BoxLayout:
                    orientation: 'vertical'
                    FileChooserIconView:
                        sort_func: root.sort_func
    

    以截图为例:

    【讨论】:

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