Python 的 Kivy FileBrowser 无法正确索引文件

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

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

Bad image indexing...

非常感谢!

最佳答案

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

基于 @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

一些屏幕截图作为示例:

enter image description here

enter image description here

关于Python 的 Kivy FileBrowser 无法正确索引文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47525588/

相关文章:

python - 使用透视代理传递多个对象(复杂类型)

python-3.x - 在 Python 中使用 multiprocessing.Pool 和返回自定义对象的函数

python - 调用返回的函数对象不显示相同的结果? Python3.x

python-2.7 - 在编辑器中设置 Google App Engine

python - 如果脚本使用 Python 2 运行,如何抛出异常?

python - 需要澄清 socket.recv 的行为方式

python - 让父方法返回子类实例

python-2.7 - 在 Python Pandas 中进行机器学习时出现内存错误

python-2.7 - 如何从 pandas 数据框中的分区数据访问前一行值

Python - 将字符串拆分成更小的 block 并分配一个变量