如何在MDBoxLayout中居中放置Button组件?
核心问题修正
首先注意你的kv文件中<screenone>需要改为<ScreenOne>,Kivy要求kv中的类名必须与Python中定义的类名完全匹配(首字母大写),否则布局不会生效,这可能是你之前效果不符合预期的原因之一。
方法1:使用pos_hint实现精准居中
不需要手动计算pos坐标,直接给Button设置pos_hint: {'center_x': 0.5, 'center_y': 0.5},即可让按钮在父布局(MDBoxLayout)中水平、垂直双向居中。修改后的单格子示例代码如下:
<ScreenOne>: GridLayout: cols: 2 rows: 2 size: root.size MDBoxLayout: size_hint: (None, None) size: (self.parent.width / 2, self.parent.height / 2) md_bg_color: 0, 1, 1, .5 Button: text: 'button' size_hint: (None, None) size: (self.parent.width / 2, self.parent.height / 2) pos_hint: {'center_x': 0.5, 'center_y': 0.5}
方法2:适配多按钮场景的完整实现
如果要创建四个分别位于GridLayout四个格子内的居中按钮,推荐使用dp()(密度无关像素)定义尺寸以适配不同屏幕,同时让每个MDBoxLayout默认占满GridLayout的格子。完整kv代码如下:
<ScreenOne>: GridLayout: cols: 2 rows: 2 size: root.size # 第一行第一列 MDBoxLayout: md_bg_color: 0, 1, 1, .5 Button: text: 'Button 1' size_hint: (None, None) size: (dp(100), dp(50)) pos_hint: {'center_x': 0.5, 'center_y': 0.5} # 第一行第二列 MDBoxLayout: md_bg_color: 1, 0, 1, .5 Button: text: 'Button 2' size_hint: (None, None) size: (dp(100), dp(50)) pos_hint: {'center_x': 0.5, 'center_y': 0.5} # 第二行第一列 MDBoxLayout: md_bg_color: 1, 1, 0, .5 Button: text: 'Button 3' size_hint: (None, None) size: (dp(100), dp(50)) pos_hint: {'center_x': 0.5, 'center_y': 0.5} # 第二行第二列 MDBoxLayout: md_bg_color: 0, 0, 1, .5 Button: text: 'Button 4' size_hint: (None, None) size: (dp(100), dp(50)) pos_hint: {'center_x': 0.5, 'center_y': 0.5}
内容的提问来源于stack exchange,提问作者fenixfoux
相关产品推荐
相关产品推荐

