Python Kivy新手GridLayout布局定位未达预期效果问题求助
问题原因
- 你编写的kv代码中,顶层
GridLayout设置了rows=2和cols=2,总计4个单元格,但目前只添加了2个子控件,剩余2个空单元格会占用布局空间,导致控件排布和预期不符 - 父容器内的
test01-1按钮尺寸设置不合理:它的父GridLayout是1行2列,原设置总尺寸200*200,每个单元格默认分配的宽度为100、高度为200,你设置按钮宽200高100会直接溢出单元格 - 顶层
GridLayout的canvas.before属性缩进错误,Rectangle的size和pos没有对应缩进,导致背景色无法正常渲染 - 装
test0-1和test0-2的内层GridLayout没有设置固定尺寸和size_hint: None, None,调整外层尺寸时会出现控件偏移
修正后的完整kv代码
<TestWidget>: title: "Test" GridLayout: rows:2 cols:2 spacing: 20 size_hint: None, None size: self.minimum_size # 自动适配子控件总尺寸 canvas.before: Color: rgba: 0, 1, 0, 1 Rectangle: size: self.size pos: self.pos GridLayout: rows:1 cols:2 size: 300, 100 # 调整为刚好容纳子控件的尺寸 size_hint: None, None GridLayout: rows: 1 cols: 2 size_hint: None, None size: 200, 100 # 适配两个100宽按钮的总尺寸 Button: text: "test0-1" size: 100, 100 size_hint: None, None Button: text: "test0-2" size: 100, 100 size_hint: None, None Button: text: "test01-1" size: 100, 100 # 调整为适配单元格尺寸 size_hint: None, None Button: text: "test1" size_hint: None, None size: 500, 500
补充说明
如果需要顶层布局占满整个窗口,去掉顶层GridLayout的size_hint: None, None和size配置即可,所有固定尺寸的控件会按设置的大小排布在布局左上角,剩余位置留空。
内容的提问来源于stack exchange,提问作者Hakob
相关产品推荐
相关产品推荐

