python - 如何在 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
解决方案
您可以只定义一个执行您想要的方法,然后使用以下方法调用该方法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))
推荐阅读
- angular - 带有对 3rd 方组件的模板引用的 Angular ContentChild
- c# - c# string.split 只工作几次
- javascript - 按钮没有图标
- javascript - 离开jQuery,写了一个简单的ajax函数,但是链式方法不会等待
- rust - 函数适用于推断的生命周期,但不适用于显式生命周期
- java - Java charAt() 返回随机整数而不是字母
- google-sheets - 在子表中查找
- delphi - 图像幻灯片效果。BitBlt 闪闪发光
- reactjs - antd datepicker 使用 formik 预填充值
- python - 查找最长重复子串的快速算法