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

Python/KivyMD开发时自定义MDDialog仅显示标题与确认按钮无内容如何解决

问题根因

你使用的KivyMD 0.104.2版本不支持在confirmation类型的MDDialog中通过items参数渲染列表项,该特性是KivyMD 1.x及更高版本的新增能力。0.104.2版本要实现带自定义复选列表的对话框,需要使用custom类型手动指定内容容器。

修复步骤
  • 新增继承自MDList的自定义内容容器类,用来承载所有复选框选项
  • 将对话框类型从confirmation改为custom,通过content_cls属性绑定自定义的列表容器
  • 将原来写在items中的复选框项移动到自定义列表容器的kv规则中
修复后可正常运行的完整代码
from kivy.lang import Builder
from kivy.properties import BooleanProperty
from kivy.uix.button import Button
from kivymd.app import MDApp
from kivymd.uix.dialog import MDDialog
from kivymd.uix.list import OneLineAvatarIconListItem, MDList
from kivymd.uix.selectioncontrol import MDCheckbox

kv = '''
#:import Factory kivy.factory.Factory
<ItemConfirm>
    divider: None
    CheckboxLeftWidget:
        id: check
        score: root.text  # 把选项文本绑定到复选框属性方便读取
        group: "check"
        on_active: app.check_active(self.group)  # 勾选状态变化时更新全局激活状态

<ConfirmButton@MDFlatButton>:
    text: '确认'
    disabled: not app.active  # 无勾选时禁用按钮
    on_release: app.score_limit()

<DialogContent@MDList>
    # 所有复选框选项放到自定义列表容器中
    ItemConfirm:
        text: "30"
    ItemConfirm:
        text: "40"
    ItemConfirm:
        text: "50"
    ItemConfirm:
        text: "60"

<ConfirmDialog>:
    title: "分数限制"
    type: "custom"
    auto_dismiss: False
    content_cls: Factory.DialogContent()
    buttons: [ Factory.ConfirmButton() ]
'''

class ItemConfirm(OneLineAvatarIconListItem):
    pass

class DialogContent(MDList):
    pass

class ConfirmDialog(MDDialog):
    pass

class TestApp(MDApp):
    active = BooleanProperty(False)  # 记录是否有复选框被勾选

    def build(self):
        Builder.load_string(kv)
        return Button(text='打开对话框', on_release=self.show_confirmation_dialog)

    def show_confirmation_dialog(self, *args):
        self.dialog = ConfirmDialog()
        self.dialog.open()

    def score_limit(self, *args, **kwargs):
        print('选中的分数限制:', self.check_active('check'))
        self.dialog.dismiss()
        self.dialog = None  # 清除当前复选框组状态
        self.active = False

    def check_active(self, group):  # 更新全局激活状态,返回选中的分数,未选中返回None
        for cb in MDCheckbox.get_widgets(group):
            if cb.active:
                self.active = True
                return cb.score
        self.active = False
        return None

TestApp().run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:27:03