简体   繁体   中英

How to fix <NumericProperty name=> in list python kivy?

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) ))

This is the output

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

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) ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM