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

KivyMD运行报错AttributeError: 'MainApp'对象无'check_1'属性如何解决

问题修复方案

错误原因

  • 你调用Test.turn_active_on_theme(self)时传入的self是MainApp的实例,而turn_active_on_theme方法需要接收Test类的实例才能访问到kv文件中定义的check_1控件,自然会抛出MainApp无check_1属性的错误
  • 你在build方法中先执行修改控件属性的逻辑,再创建返回Test实例,控件未完成初始化就操作属性,调用逻辑顺序错误
  • 补充注意:kv中定义的id默认存放在控件实例的ids字典中,规范写法需要通过实例.ids.id名访问控件

修正代码

.py文件修改后内容

from kivy.uix.boxlayout import BoxLayout
from kivymd.app import MDApp

class Test(BoxLayout):
    def turn_active_on_theme(self):
        self.ids.check_1.active = True

class MainApp(MDApp):
    theme = 'Dark'

    def build(self):
        self.theme_cls.theme_style = self.theme
        # 先创建Test控件实例
        test_root = Test()
        if self.theme == "Dark":
            # 调用实例的方法操作内部控件
            test_root.turn_active_on_theme()
        return test_root

MainApp().run()

.kv文件不需要修改,保持原有内容即可

<Test>:
    BoxLayout:
        orientation: 'vertical'
        MDCheckbox:
            group:'group'
            id: check_1
            active: False
        MDCheckbox:
            group:'group'
            id: check_2
            active: False

补充说明

如果后续需要在MainApp的其他方法中操作Test内部的控件,可以在build时将实例挂载到App的属性上:

def build(self):
    self.theme_cls.theme_style = self.theme
    self.test_root = Test()
    if self.theme == "Dark":
        self.test_root.turn_active_on_theme()
    return self.test_root

之后在其他方法中直接通过self.test_root.ids.check_1就能访问对应控件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:06:03