Kivy设置size_hint后Button文本消失及尺寸异常问题
问题解决:Kivy按钮设置size_hint后文本消失+尺寸不对的问题
核心问题分析
- size_hint用法错误:你写的
size_hint: root.width * 0.1, root.height * .1完全搞错了这个属性的用途——size_hint是相对于父布局的比例系数,取值范围一般是0到1(或大于1表示超出父布局),不是直接计算具体像素尺寸。正确写法应该是size_hint: 0.1, 0.1,表示按钮占父布局(此处FloatLayout和窗口等大)宽高的10%。 - 文本消失原因:固定
font_size:22后,当按钮缩小到窗口的1/10时,22号字体大概率超出按钮显示范围,导致文字被裁剪无法看到。
修正后的KV代码
#:kivy 2.3.0 <GameScreen>: canvas: Color: rgba: 0, 0, 1, 1 # Blue (For the border) Rectangle: pos: root.x, root.y size: root.width, root.height Color: rgba: 1, 1, 1, 1 # White Rectangle: pos: root.x + 5, root.y + 5 size: root.width - 10, root.height - 10 FloatLayout: pos: 0,0 size: root.width, root.height Button: pos_hint: {'x': .05, 'y': .05 } size_hint: 0.1, 0.1 # 改为比例值 font_size: self.height * 0.6 # 用按钮高度比例设置字体,适配尺寸 bold: True background_normal: '' background_color: 0.2, 0.7, .2, 1 # Green color: 1, 0, 0, 1 # Red text: 'Hello'
额外说明
- 移除了无用的
text_box_size属性,Button控件本身没有这个属性,设置后无效果。 - 用
self.height * 0.6设置字体大小,能保证文字始终在按钮内部显示,适配按钮尺寸变化。 - FloatLayout中,size_hint(控制相对尺寸)和pos_hint(控制相对位置)配合是标准用法。
内容的提问来源于stack exchange,提问作者Rick Freeman
相关产品推荐
相关产品推荐

