I tried to make kivy display my list. This is my simple python code for testing:
class test(BoxLayout):
pass
class testApp(App):
numberx = NumericProperty(10)
numbery = NumericProperty(5)
list = [numberx,numbery]
testApp().run()
this is my kv file:
#:import Label kivy.uix.label.Label
test:
<test>:
orientation: 'vertical'
on_parent: for x in app.list: self.add_widget(Label(text = str(x) ))
The output show:
NumericProperty name=numberx
NumericProperty name=numbery
NumericProperty name=numberx
NumericProperty name=numbery
But I want it to show:
10
5
Please help me
CodePudding user response:
There are two problems with your code.
First, Using the on_parent event results in that code being executed twice (once when parent is initialized to None, and once when parent is set to the testApp window). That is why you see 4 items instead of just 2. You can use the on_kv_post event to get it to happen just once.
Second, the list that you create contains the class attributes, numberx and numbery. But while Properties are defined at the class level, they are actually instance attributes, so that list contains the wrong objects. To fix that, you can define that list either as a ReferenceListProperty, or by defining it in the testApp instance (perhaps in an __init__() method) so that you are using the instance attributes.
Here is a modified version of your testApp class that uses the ReferenceListProperty:
class testApp(App):
numberx = NumericProperty(10)
numbery = NumericProperty(5)
list = ReferenceListProperty(numberx, numbery)
And here is a modified version of your kv that uses the on_kv_post event:
#:import Label kivy.uix.label.Label
test:
<test>:
orientation: 'vertical'
on_kv_post:
for x in app.list: self.add_widget(Label(text = str(x) ))
