如何从Python中的另一个类更改kivy中的标签文本?

问题描述 投票:0回答:1

我是Python大佬。 这是我的 python 文件:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
kv = Builder.load_file('test.kv')


class LessonsList(Screen):
    def press(self):
        manager.current = "lesson"


class LessonWindow(Screen):
    def back(self):
        manager.current = "lessons"
        manager.transition.direction = "left"


manager = ScreenManager()
manager.add_widget(LessonsList(name="lessons"))
manager.add_widget(LessonWindow(name="lesson"))


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


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

这是我的 kv 文件:

<LessonsList>:
    BoxLayout:
        size: root.width, root.height
        orientation: 'vertical'
        Button:
            text:'Lesson 1'
            on_press: root.press()
        Button:
            text:'Lesson 2'
            on_press:root.press()
        Button:
            text:'Lesson 3'
            on_press: root.press()

<LessonWindow>:
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'Lesson'
        Button:
            text:'Back'
            on_press: root.back()

我不知道如何从LessonList类更改LessonWindow类中Label的文本。当我按下 LessonsList 类中的任何按钮时,标签的文本必须带有按钮的编号。你能帮我解决这个问题吗?谢谢)

python class kivy kivy-language
1个回答
0
投票

您可以在

id
中为该
Label
添加
kv

<LessonWindow>:
    BoxLayout:
        orientation: 'vertical'
        Label:
            id: lab  # added id
            text: 'Lesson'
        Button:
            text:'Back'
            on_press: root.back()

然后您可以在您的

id
方法中使用该
press()

def press(self):
    manager.current = "lesson"
    lesson_window = self.manager.get_screen('lesson')
    label = lesson_window.ids.lab
    label.text = 'Changed Text'
© www.soinside.com 2019 - 2024. All rights reserved.