1

我有一个按钮 ( button_child_A) 调用 def on_press。在这个定义中,我想更改 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_Alabel_parent通过简单地调用 then 与他们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"
4

0 回答 0