如何用ListView显示文件列表? Python - Kivy

时间:2017-12-15 05:00:15

标签: python kivy

我有一个文件列表的路径,我希望在kivy中显示如下:

excel_file.xlsx

D.xlsx

U.xlsx

another_route.xlsx

test.txt

G.xlsx

当我实现相同的算法以kivy作为项目列表显示它们时,我只得到一个完全相同的列表:

G

.

x

l

s

x

我想知道我做错了什么。让我告诉你我的代码:

class Routes_List_Screen(Screen):
    path = "/home/pi/Documents/myRoutes"
    dirs = os.listdir(path)
    for file in dirs:
        my_data = ListProperty(file)
        print(file) # this is just to know what exactly is printing file variable

kv文件:

<Routes_List_Screen>:
    canvas:
        Color:
            rgb: [.30, .30, .30]
        Rectangle:
            pos: self.pos
            size: self.size
    BoxLayout:
        orientation: 'vertical'
        ListView:
            size_hint_y: .8
            adapter:
                ListAdapter(data=root.my_data,
                selection_mode='single',
                allow_empty_selection=False,
                cls=ListItemButton)
        Button:
            text: 'Load'

我的输出: What I've got from kivy with the current code

1 个答案:

答案 0 :(得分:1)

您必须将列表直接传递给ListProperty

class Routes_List_Screen(Screen):
    path = "/home/pi/Documents/myRoutes"
    dirs = os.listdir(path)
    my_data = ListProperty(dirs)

输出:

enter image description here

<强>解释

代码:

for file in dirs:
    my_data = ListProperty(file)
    print(file) # this is just to know what exactly is printing file variable

在上一段代码中,您每时都会更新变量my_data:

another_route.xlsx
excel_file.xlsx
G.xlsx
U.xlsx
test.xlsx
D.xlsx

最后存储的值是字符串D.xlsx,字符串是可迭代的,因此它将其分隔为字母。