如何在kivy应用程序中正确地为MDLabel的背景上色



尝试在kivy应用程序中为MDLabel(Label(的背景上色。但不能将标签的宽度调整为文本(内容(的大小。

GridLayout:
cols: 1
BoxLayout:
orientation: 'vertical'
size_hint_y: None
padding: dp(7)
# pos_hint: {'top': 1}
background_color: (1,1,0,1)
height: self.minimum_height
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
BoxLayout:
size_hint_y: None
# pos_hint: {'top': 1}
height: self.minimum_height
background_color: (0,1,0,1)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
MDLabel:
text: 'Some text'
size_hint_y: None
size: self.texture_size
MDLabel:
id: trying_to_color_background
text: 'Width'
halign: 'right'
size_hint_x: None
size: self.texture_size

得到这个在此处输入图像描述

如果我试图删除代码"的最后一行;size:self.texture_size";。看起来像这样在此处输入图像描述

但我希望背景是文本内容的大小(下图中红色边框的大小(。如果文本中有更多的字母,我希望背景更宽在此处输入图像描述

将其设置为,

...
MDLabel:
id: trying_to_color_background
text: 'Width'
halign: 'right'
size_hint: None, None
size: self.texture_size
text_size: None, None
lbl_state = MDLabel(text="state", md_bg_color = [.119, .136, .153, 1])
lbl_state = MDLabel(text="state", theme_text_color = "Custom", md_bg_color = [.119, .136, .153, 1])
from kivy.utils import get_color_from_hex
lbl_state = MDLabel(text="state", theme_text_color = "Custom", md_bg_color = get_color_from_hex("#7dcbb1"))
MDLabel:
id: trying_to_color_background
theme_text_color: "Custom"
md_bg_color = .119, .136, .153, 1

不同颜色的示例:

0, 0, 0, 1 - dark
1, 1, 1, 1 - white
.7, .7, .7, 1 - gray
1, 0, 0, 1 - red
0, 1, 0, 1 - green
0, 0, 1, 1 - blue

最新更新