[英]How to fix <NumericProperty name=> in list python kivy?
I tried to make kivy display my list.我试图让 kivy 显示我的列表。 This is my simple python code for testing:
这是我用于测试的简单python代码:
class test(BoxLayout):
pass
class testApp(App):
numberx = NumericProperty(10)
numbery = NumericProperty(5)
list = [numberx,numbery]
testApp().run()
this is my kv file:这是我的 kv 文件:
#: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请帮我
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).首先,使用
on_parent
事件会导致该代码被执行两次(一次是在parent
被初始化为None
,一次是在parent
被设置为testApp
窗口时)。 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.这就是为什么您会看到 4 个项目而不是 2 个。您可以使用
on_kv_post
事件让它只发生一次。
Second, the list
that you create contains the class attributes, numberx
and numbery
.其次,您创建的
list
包含类属性numberx
和numbery
。 But while Properties
are defined at the class level, they are actually instance attributes, so that list contains the wrong objects.但是,虽然
Properties
是在类级别定义的,但它们实际上是实例属性,因此该列表包含错误的对象。 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.要解决这个问题,您可以将该
list
定义为ReferenceListProperty
,或者通过在testApp
实例中(可能在__init__()
方法中)定义它,以便您使用实例属性。
Here is a modified version of your testApp
class that uses the ReferenceListProperty
:这是使用
ReferenceListProperty
testApp
类的修改版本:
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:这是使用
on_kv_post
事件的kv
的修改版本:
#: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) ))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.