You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kivy中从另一个类修改Label组件的文本

问题解决方案

报错原因

  • 你调用self.parent.ids.label_id时,self.parent是ScreenManager实例,label_id是定义在SecondWindow类内部的属性,不属于ScreenManager的ids集合,所以触发属性不存在的报错
  • 你虽然自定义了WindowManager继承ScreenManager,但实际build方法中实例化的是原生ScreenManager,不过这不是本次报错的核心诱因

修复代码

首先修改Python代码中FirstWindow类的change_label方法:

class FirstWindow(Screen):
    def change_label(self):
        # 先通过ScreenManager的get_screen方法拿到SecondWindow实例,再访问其暴露的label_id属性
        self.parent.get_screen('second').label_id.text = 'label is changed'

(可选优化)如果要使用你自定义的WindowManager,修改App的build方法:

class FirstApp(App): 
    def build(self):
        # 替换为自定义的WindowManager实例
        screen_manager = WindowManager()
        screen_manager.add_widget(FirstWindow(name = 'first'))
        screen_manager.add_widget(SecondWindow(name = 'second'))
        return screen_manager

验证效果

修改后点击第一个窗口的change_label按钮,再切换到第二个窗口,即可看到Label文本已经被成功修改,不会再触发属性错误。

内容的提问来源于stack exchange,提问作者Nan Reven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:45:04