You need to enable JavaScript to run this app. KivyMD开发导航抽屉访问类root属性触发ValueError如何解决
优惠活动
大模型
产品
解决方案
定价
更多

KivyMD开发导航抽屉访问类root属性触发ValueError如何解决

问题原因

你在KV规则中把IconLeftWidget的text_color属性绑定到了父类ItemDrawer的text_color属性,但你自定义的ItemDrawer类没有为text_color设置初始值,控件初始化时该属性默认值为None,而IconLeftWidget.text_color不允许接收None值,因此触发报错。

解决方案

你只需要给ItemDrawer的text_color设置初始默认值即可,两种实现方式选其一即可:

方式一:修改Python代码的ItemDrawer类定义

给ItemDrawer添加text_color属性,初始化时赋值为主题默认文本颜色:

# 导入ColorProperty,也可以用你已经引入的ObjectProperty,ColorProperty对颜色值适配性更好
from kivy.properties import ColorProperty

class ItemDrawer(OneLineIconListItem):
    icon = StringProperty()
    # 声明text_color属性
    text_color = ColorProperty()
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 初始化赋值为主题默认文本色
        self.text_color = self.theme_cls.text_color

方式二:修改KV规则的ItemDrawer部分

直接在KV规则里给ItemDrawer加默认text_color赋值,不需要改Python代码:

<ItemDrawer>:
    theme_text_color: "Custom" 
    # 新增这一行即可
    text_color: app.theme_cls.text_color
    on_release: self.parent.set_color_item(self) 

    IconLeftWidget:
        id: icon
        icon: root.icon 
        theme_text_color: "Custom"
        text_color: root.text_color

修改完成后运行即可正常生效,菜单点击切换颜色的逻辑也能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 20:27:02