1

我无法通过 id 从另一个类获取小部件。我试过app.root.ids.first_lbl.text了,但没有用。有没有办法做到这一点?

这是我的代码:

主要.py:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout


class MainWidget(Widget):
    pass

class SecondWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MainWidget()


if __name__ == "__main__":
    MyApp().run()

我的.kv:

<MainWidget>
    BoxLayout:
        size: root.width, root.height

        BoxLayout:
            Label:
                id: first_lbl
                text: "TEXT123"

        SecondWidget:

<SecondWidget>:
    Label:
        text: app.root.ids.first_lbl.text
4

1 回答 1

1

这是一个可行的技巧:

<MainWidget>
    BoxLayout:
        size: root.width, root.height

        BoxLayout:
            Label:
                id: first_lbl
                text: "TEXT123"

        SecondWidget:
            t1: first_lbl.text  # set the t1 property of SecondWidget to the text of first_lbl

<SecondWidget>:
    t1: ''
    Label:
        text: root.t1  # use the t1 property of SecondWidget
于 2021-07-24T03:17:02.057 回答