我有一个按钮(button_child_A
),用on_press
调用def。
在这个def中,我想更改3个标签的文本:
- `label_child_A` is in the same class as the `button_child_A`
- `label_parent` is in the parent class of `button_child_A`
- `label_child_B` is in the sister class of `button_child_A` (same parent class)
我可以通过简单地调用label_child_A
来修改label_parent
和ids
,但我无法通过调用label_child_B
修改id
,我得到错误:"object has no attribute"
。 (参见下面def change_label
中的.py
)
我知道我必须创建ObjectProperty
,但为什么?当我从同一个类或父类更改窗口小部件时,为什么我不需要ObjectProperty
但是当我从“姐妹类”(同一个父级)更改窗口小部件时我需要它?
.py
:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class Class_Parent(BoxLayout):
pass
class Class_Child_A(BoxLayout):
def change_labels(self):
self.ids.label_child_A.text = "changed"
self.parent.ids.label_parent.text= "changed"
#self.parent.ids.classAb_id.label_child_B.text = "changed" ## get the error 'Class_Child_B' object has no attribute 'label_child_B'
self.parent.ids.classAb_id.label_child_b_object_property.text = "changed" # why do I need to use ObjectProperty here ?
pass
class Class_Child_B(BoxLayout):
child_b_label_object_property = ObjectProperty(None)
class TestApp(App):
def build(self):
return Class_Parent()
TestApp().run()
.kv
:
<Class_Parent>:
Label:
id: label_parent
text: "label parent"
Class_Child_A:
id: classAa_id
Class_Child_B:
id: classAb_id
<Class_Child_A>:
Button:
id: button_child_A
text: "button child A"
on_press: root.change_labels()
Label:
id: label_child_A
text: "label child A"
<Class_Child_B>:
label_child_b_object_property: label_child_B
Label:
id: label_child_B
text: "label child B"