I can’t figure out how to display a simple list and a list with dictionaries in BoxLayout (class Content), I’m trying to display the “data_name_list” list line by line, and the “data_all_list” list line by line, but only the values by the key “item_name”.
Here is .py file
JavaScript
x
22
22
1
from kivy.app import App
2
from kivy.uix.boxlayout import BoxLayout
3
4
data_all_list = [
5
{"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"}},
6
{"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"}}
7
]
8
data_name_list = ["name_1", "name_2", "name_3"]
9
10
class Main(BoxLayout):
11
pass
12
13
class Content(BoxLayout):
14
pass
15
16
class MyApp(App):
17
def build(self):
18
return Main()
19
20
if __name__ == "__main__":
21
MyApp().run()
22
Here is .kv file
JavaScript
1
21
21
1
#:kivy 2.0.0
2
Main:
3
<Main>:
4
orientation: "vertical"
5
canvas.before:
6
Color:
7
rgba: 255, 255, 255, 1
8
Rectangle:
9
pos: self.pos
10
size: self.size
11
12
Content:
13
orientation: "vertical"
14
spacing: 15
15
canvas.before:
16
Color:
17
rgba: 0.16, 0.62, 0.39, 1
18
Rectangle:
19
pos: self.pos
20
size: self.size
21
Advertisement
Answer
You can just define a method that does what you want, then call that method using Clock.schedule_once()
:
JavaScript
1
15
15
1
class MyApp(App):
2
def build(self):
3
Clock.schedule_once(self.add_lists)
4
return Main()
5
6
def add_lists(self, dt):
7
content = self.root.children[0] # this can be replaced by an ids access if an id is assigned to Content
8
for name in data_name_list:
9
content.add_widget(Label(text=name))
10
for d in data_all_list:
11
for key, d1 in d.items():
12
if isinstance(d1, dict):
13
item_name = d1['item_name']
14
content.add_widget(Label(text=item_name))
15