如何在Kivy中设置背景图片?图片始终遮挡按钮等控件
解决Kivy背景图片显示在控件上方的问题
你的核心问题是Kivy控件的绘制顺序:布局内的控件会按照你在kv语言中编写的顺序渲染,先写的控件在底层,后写的在顶层。你当前把AsyncImage放在了FloatLayout的最后,所以它覆盖了所有按钮和标签。
一、把背景图置于底层
只需要把背景图的AsyncImage移到FloatLayout的最开头即可,修改后的MenuScreen部分kv代码如下:
<MenuScreen>: FloatLayout: # 背景图放在最前面,成为底层 AsyncImage: source: 'blackboard.png' size_hint: 1, .7 pos_hint: {'center_x':.5, 'center_y': .5} # 后续的按钮、标签会渲染在背景图上方 Button: text: "LEARN" font_name: 'DK Lemon Yellow Sun.otf' font_size: '50sp' pos: 60, 180 size_hint: .4, .4 Button: text: "TRANSLATE" font_name: 'DK Lemon Yellow Sun.otf' font_size: '50sp' pos: 410, 180 size_hint: .4, .4 Button: text: "QUIT" font_size: '50sp' font_name: 'DK Lemon Yellow Sun.otf' pos: 60, 50 size_hint: .1, .1 Label: text: 'Education App' pos: -10, 200 font_size: '70sp' font_name: 'DK Lemon Yellow Sun.otf'
二、给按钮添加自定义背景图片
如果你想给按钮单独设置背景图,可以利用Button自带的background_normal和background_down属性,示例如下:
Button: text: "LEARN" font_name: 'DK Lemon Yellow Sun.otf' font_size: '50sp' pos: 60, 180 size_hint: .4, .4 background_normal: 'your_button_bg.png' # 按钮常态下的背景图 background_down: 'your_button_pressed_bg.png' # 按钮按下时的背景图 background_color: 1, 1, 1, 1 # 关闭默认的颜色 tint,确保原图正常显示 background_size: 'cover' # 让背景图自适应按钮大小(可选,值还可以是'contain'等)
这样修改后,背景图会稳定处于底层,所有控件都能正常显示在它上方,同时按钮也能拥有自定义背景。
内容的提问来源于stack exchange,提问作者Tyler Joseph
相关产品推荐
相关产品推荐

