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

如何在KivyMD的MDTopAppBar中居中MDTextButton?

解决MDTopAppBar中MDTextButton居中定位问题

要在MDTopAppBar里正确居中MDTextButton,别直接把按钮当子控件塞进去——MDTopAppBar内部有固定的布局结构(左操作区、标题区、右操作区),直接添加控件会和左右action_items的布局冲突,导致错位。

正确的做法是利用MDTopAppBar自带的title_widget属性自定义标题区域,这样按钮会自动纳入顶部栏的布局体系,既能和左右操作按钮和平共处,又能实现自动居中。

修改后的KV代码如下:

KV = '''<DrawerClickableItem@MDNavigationDrawerItem>
    focus_color: "#e7e4c0"
    text_color: "#b3b198"
    icon_color: "#a86e0a"
    ripple_color: "#c5bdd2"
    selected_color: "#0c6c4d"


<DrawerLabelItem@MDNavigationDrawerItem>
    text_color: "#b3b198"
    icon_color: "#b3b198"
    focus_behavior: False
    selected_color: "#4a4939"
    _no_ripple_effect: True


MDScreen:

    MDTopAppBar:
        id: toolbar
        pos_hint: {"top": 1}

        right_action_items:
            [['menu', lambda x: nav_drawer.set_state("open")]]            
        left_action_items:
            [['home', lambda x: setattr(screen_manager, "current", "screen_Home")]]
        
        # 通过title_widget将MDTextButton纳入标题布局容器
        title_widget:
            MDTextButton:
                text: "Test"
                text_color: "white"
                # 无需额外设置pos_hint,标题容器会自动处理水平+垂直居中
'''

关键说明

  • title_widget是MDTopAppBar专门用于自定义标题的属性,它会将你的按钮放入顶部栏的标题容器中,该容器默认就是水平、垂直居中的,且不会和左右action_items的布局区域重叠。
  • 之前直接添加MDTextButton作为子控件的方式,相当于把按钮悬浮在顶部栏最上层,不仅会和操作按钮错位,pos_hint: {"center_y": 1}的设置还会把按钮中心定位在顶部栏的上边缘,导致垂直位置偏移。

如果需要微调按钮的间距,可给MDTextButton添加padding属性,但默认布局已能满足居中需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 17:46:10