我很难用Python的Kivy语言为各种对象(在本示例中为标签)定义背景颜色。附带的代码创建一个框布局,其中每个框都有特定的背景颜色。
ForeignLanguage = ColoredLabel(..., size = (a,b))
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.properties import ListProperty
from kivy.lang import Builder
from kivy.core.window import Window
kv = '''
<ColoredLabel>:
size: (self.size_x,self.size_y)
pos: (0,0) # no effect
background_color:
canvas.before:
Color:
rgba: self.background_color
Rectangle:
pos: self.pos
size: (self.size_x,self.size_y)
'''
Builder.load_string(kv)
class ColoredLabel(Label):
background_color = ListProperty((0,0,0,1))
s_global = Window.size
size_x = s_global[0]
size_y = s_global[1]/3
class MyWidget(BoxLayout):
#init
def __init__(self, **kwargs):
super().__init__(**kwargs)
ForeignLanguage = ColoredLabel(text="ForeignLanguage", size_hint=(None, None), background_color=(0/255,171/255,169/255, 1))
Translation = ColoredLabel(text="Translation", size_hint=(None, None), background_color=(45/255,137/255,239/255, 1))
Example = ColoredLabel(text="Example", size_hint=(None, None), background_color=(43/255,87/255,151/255, 1))
verticalBox = BoxLayout(orientation='vertical')
verticalBox.add_widget(ForeignLanguage)
verticalBox.add_widget(Translation)
verticalBox.add_widget(Example)
self.add_widget(verticalBox)
class BoxLayoutDemo(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
BoxLayoutDemo().run()
答案 0 :(得分:1)
如何修改此代码,以便我可以定义代码的大小 通过变量来确定标签,而不是对其进行硬编码。最好是 如果我们能提出这样的解决方案:
ForeignLanguage = ColoredLabel(..., size = (a,b))
在您的kv文件中只需具有以下设计。随着Label小部件的继承,定义的所有属性都将可用,例如size
,size_hint
,color
,markup
等。
<ColoredLabel>:
canvas.before:
Color:
rgba: root.background_color
Rectangle:
pos: self.pos
size: self.size
我的代码对我来说似乎很复杂。是否可以设置 标签的背景颜色,例如Label(..., background_color =(1,1,1,1))?
您的代码看起来不错。
ForeignLanguage = ColoredLabel(text="ForeignLanguage", size_hint=(None, None), size=(300, 40),
background_color=(1, 0, 0, 1))
Translation = ColoredLabel(text="Translation", size_hint=(None, None), size=(100, 30),
background_color=(0, 1, 0, 1))
Example = ColoredLabel(text="Example", size_hint=(None, None), size=(200, 20),
background_color=(0, 0, 1, 1))