KivyMD2.0.0界面出现两个红点的问题排查与解决
KivyMD 2.0.0中MDBadge导致意外红点的问题与修复
在KivyMD 2.0.0版本中,通过KV字符串渲染界面时,屏幕出现两个意外红点,移除MDBadge组件后红点消失。以下是复现问题的简化代码:
from kivy.lang import Builder from kivymd.app import MDApp KV = """ MDScreen: MDBoxLayout: orientation: "vertical" MDTopAppBar: font_style: "Display" role: "small" size_hint_x: 1 # 确保顶部栏占满屏幕宽度 pos_hint: {"top": 1} # 确保顶部栏位于屏幕顶部 MDTopAppBarLeadingButtonContainer: MDActionTopAppBarButton: icon: "arrow-left" on_release: app.back_to_previous_screen() MDTopAppBarTitle: id: edit_cards_top_app_title text: "Manager App" MDTopAppBarTrailingButtonContainer: MDActionTopAppBarButton: icon: "file-document-multiple" MDBadge: id: edit_cards_badge_table_rows text: "0" md_bg_color: 0/255, 128/255, 128/255, 1 # 默认蓝绿色(RGBA) MDActionTopAppBarButton: icon: "database" MDBadge: id: edit_cards_badge_table text: "0" md_bg_color: 0, 0, 1, 1 # 默认蓝色(RGBA) MDScrollView: pos_hint_x: 1 size_hint_y: 1 MDList: pos_hint_x: 1 id: double_card_list MDBoxLayout: orientation: 'horizontal' size_hint_y: None height: "480dp" # 定义两张卡片的高度 padding: "10dp" # 卡片外部间距 spacing: "10dp" # 卡片之间的水平间距 # 第一行第一张卡片 MDCard: size_hint_x: None width: "400dp" elevation: 10 radius: [10] MDBoxLayout: orientation: 'vertical' padding: "10dp" # 卡片内部间距 spacing: "5dp" MDLabel: text: "Product Information" halign: "center" # 第一行第二张卡片 MDCard: size_hint_x: None width: "400dp" elevation: 10 radius: [10] MDBoxLayout: orientation: 'vertical' padding: "10dp" # 卡片内部间距 spacing: "5dp" MDLabel: text: "Agency Information" halign: "center" MDListItem: id: status_bar size_hint_y: None height: "40dp" size_hint_x: 1 MDListItemHeadlineText: text: "Status :" MDListItemSupportingText: id: status_bar_supporting_text text: "Supporting text:" MDListItemTertiaryText: text: "Tertiary text" """ class Example_unexpected_2_red_dot_(MDApp): def build(self): return Builder.load_string(KV) Example_unexpected_2_red_dot_().run()
问题原因
KivyMD 2.0.0版本中,MDActionTopAppBarButton组件并未设计为直接嵌套MDBadge作为子元素,手动嵌套会触发布局定位逻辑混乱,导致徽章的视觉元素错位,显示为屏幕上的红点。
修复方案
方案1:使用组件原生badge属性(推荐)
MDActionTopAppBarButton自带badge相关属性,无需手动嵌套MDBadge,修改后的按钮代码如下:
MDTopAppBarTrailingButtonContainer: MDActionTopAppBarButton: icon: "file-document-multiple" badge_text: "0" badge_bg_color: 0/255, 128/255, 128/255, 1 MDActionTopAppBarButton: icon: "database" badge_text: "0" badge_bg_color: 0, 0, 1, 1
方案2:升级KivyMD版本
该布局bug在KivyMD 2.0.0之后的版本已被官方修复,执行以下命令升级到最新稳定版:
pip install --upgrade kivymd
内容的提问来源于stack exchange,提问作者Yannis Charles
相关产品推荐
相关产品推荐

