首页 > 解决方案 > 如何在 BoxLayout 中显示简单列表和带有字典的列表

问题描述

我不知道如何在 BoxLayout(内容类)中显示一个简单列表和一个带有字典的列表,我试图逐行显示“data_name_list”列表和“data_all_list”列表逐行,但是只有键“item_name”的值。

这是.py文件

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

data_all_list = [
    {"list_id": 1, "list_name": "List 1", "item1": {"item_id": 1, "item_name": "Product 1", "item_quantity": "1", "item_weight": "2", "item_price": "35"}, "item2": {"item_id": 2, "item_name": "Product 2", "item_quantity": "2", "item_weight": "2", "item_price": "35"}},
    {"list_id": 2, "list_name": "List 2", "item1": {"item_id": 1, "item_name": "Product 1", "item_quantity": "2", "item_weight": "2", "item_price": "40"}, "item2": {"item_id": 2, "item_name": "Product 2", "item_quantity": "2", "item_weight": "2", "item_price": "35"}, "item3": {"item_id": 3, "item_name": "Product 3", "item_quantity": "1", "item_weight": "2", "item_price": "35"}}
]
data_name_list = ["name_1", "name_2", "name_3"]

class Main(BoxLayout):
    pass

class Content(BoxLayout):
    pass

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

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

这是.kv文件

#:kivy 2.0.0
Main:
<Main>:
    orientation: "vertical"
    canvas.before:
        Color:
            rgba: 255, 255, 255, 1
        Rectangle:
            pos: self.pos
            size: self.size

    Content:
        orientation: "vertical"
        spacing: 15
        canvas.before:
            Color:
                rgba: 0.16, 0.62, 0.39, 1
            Rectangle:
                pos: self.pos
                size: self.size

标签: pythonpython-3.xkivykivy-language

解决方案


您可以只定义一个执行您想要的方法,然后使用以下方法调用该方法Clock.schedule_once()

class MyApp(App):
    def build(self):
        Clock.schedule_once(self.add_lists)
        return Main()

    def add_lists(self, dt):
        content = self.root.children[0]  # this can be replaced by an ids access if an id is assigned to Content
        for name in data_name_list:
            content.add_widget(Label(text=name))
        for d in data_all_list:
            for key, d1 in d.items():
                if isinstance(d1, dict):
                    item_name = d1['item_name']
                    content.add_widget(Label(text=item_name))

推荐阅读