如何使用self.ids方法访问kivy中小部件内部的屏幕元素?

时间:2019-12-03 12:27:32

标签: python kivy

我的屏幕很猕猴桃。它包含一些元素和一个小部件,而小部件又包含自己的元素。当我尝试类似

    self.ids.element_directly_on_a_screen.text = 'something' 

它有效,但是当我尝试

    self.ids.element_defined_inside_of_a_widget.text = 'something_else'

返回

     AttributeError: 'super' object has no attribute '__getattr__'

我该怎么办?

编辑:一个例子

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import Screen

class SomeWidget(FloatLayout):
    pass

class SomeScreen(Screen):
    def ButtonOne(self):
        self.ids.label_one.text = 'Something'
    def ButtonTwo(self):
        self.ids.label_two.text = 'Something else'

class TestApp(App):
    pass

if __name__ == '__main__':
    TestApp().run()

和test.kv

<SomeWidget>:
    Label:
        text: 'This is label inside of a widget'
        id: label_two
        size_hint: (0.2, 0.2)
        pos_hint: {"x": 0.4, "y": 0.5}

SomeScreen:
    Label:
        text: 'This is just a label'
        id: label_one
        size_hint: (0.2, 0.2)
        pos_hint: {"x": 0.4, "y": 0.5}
    SomeWidget:
        size_hint: (0.2, 0.2)
        pos_hint: {"x": 0.4, "y": 0.2}
    Button:
        text: 'Click me to test the first Label!'
        size_hint: (0.35, 0.2)
        pos_hint: {"x": 0.2, "y": 0}
        on_release:
            root.ButtonOne()
    Button:
        text: 'Click me to test the second Label!'
        size_hint: (0.35, 0.2)
        pos_hint: {"x": 0.6, "y": 0}
        on_release:
            root.ButtonTwo()

1 个答案:

答案 0 :(得分:1)

可以通过根访问ID,在您的情况下,只能通过SomeWidget访问“ label_two”,因此必须首先访问该元素,因此必须向在SomeScreen下创建的SomeWidget添加“ id”。

function register_html_support() {

    add_theme_support( 'html5', array( 'script', 'style' ) );

}

add_action( 'after_setup_theme', 'register_html_support' );
def ButtonTwo(self):
    self.ids.some_widget.ids.label_two.text = 'Something else'