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

2024-09-27 09:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个奇维屏幕。它包含一些元素和一个小部件,而小部件又包含自己的元素。当我尝试像

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

和测试电压(千伏)

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

Tags: textfromposimportselfids元素size
1条回答
网友
1楼 · 发布于 2024-09-27 09:27:27

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

def ButtonTwo(self):
    self.ids.some_widget.ids.label_two.text = 'Something else'
SomeScreen:
    # ...
    SomeWidget:
        id: some_widget
        size_hint: (0.2, 0.2)
        pos_hint: {"x": 0.4, "y": 0.2}
    # ...

相关问题 更多 >

    热门问题