我有一个具有浏览功能的 Kivy 应用程序。当浏览带有数字名称的文件时,它以一种奇怪的方式显示它,它按“最高有效位”样式对其进行排序。添加屏幕截图。 有人知道如何修复它以正确的顺序显示它吗? (1,2,3...而不是 1,10,100...)
非常感谢!
最佳答案
您想要自然排序。为此,您需要使用 sort_func
替换对文件进行排序的函数。类 kivy.uix.filechooser.FileChooserController
的属性。
基于 @Darius Bacon 在其对 Natural Sorting algorithm 的回答中所示算法的示例:
main.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()
main.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
一些屏幕截图作为示例:
关于Python 的 Kivy FileBrowser 无法正确索引文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47525588/