The problem is that you're not loading your kv rules until after creating the widget. If you load them first, it works fine.
You can load your rules at any time - not just in build()
. So you can just remove Builder.load_string(kvCode)
from build()
and change kvCode=('''
to Builder.load_string('''
. I put a Builder.load_string()
at the top of every widget file I create.
Also, Kivy supports more advanced property setups that will work better. Here is our way of doing this:
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import BoundedNumericProperty, ReferenceListProperty
from kivy.uix.label import Label
Builder.load_string('''
<BackgroundWidget>:
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: root.size
pos: root.pos
''')
class BackgroundWidget(Widget):
'''BackgroundWidget class
'''
background_color_r = BoundedNumericProperty(0., min=0., max=1.)
background_color_g = BoundedNumericProperty(0., min=0., max=1.)
background_color_b = BoundedNumericProperty(0., min=0., max=1.)
background_color_a = BoundedNumericProperty(0., min=0., max=1.)
background_color = ReferenceListProperty(background_color_r, background_color_g, background_color_b, background_color_a)
class BackgroundLabel(BackgroundWidget, Label): pass
You can change or animate each color component separately, the color values are constrained appropriately, and BackgroundWidget
is a mixin which adds background functionality to any widget (like BackgroundLabel
).