You probably have noticed that there are many widgets in Kivy that lack a property to set the background color. This is mainly because the widgets of Kivy are thought to be the simplest as possible to avoid unnecessary overload.

The good news is that extend and create new widgets in Kivy is extremely easy. Here is an example of how to have our personalized widget with a background color property. I am applying this to a Label because a lot of people have asked and it seems like an expected property to have. Nonetheless, the below technique could be applied to any particular Widget class - and certainly to other things different than just colors in the canvas.

Here is the code for our LabelB:

from kivy.uix.label import Label
from import ListProperty

from kivy.factory import Factory
from kivy.lang import Builder

  bcolor: 1, 1, 1, 1
      rgba: self.bcolor
      pos: self.pos
      size: self.size

class LabelB(Label):
  bcolor = ListProperty([1,1,1,1])

Factory.register('KivyB', module='LabelB')

We create a class that contains the bcolor property. Properties are extremely useful and powerful, and basically are the ones that keep our interface updated when the user (or the application internally) interacts with it. If you want to understand properties you can check the Kivy Documentation, or my book is load with examples :).

But adding the property to the class is obviously not enough. We need to link the property with the actual color of the the background. We create the background of the Label with a Rectangle (in the same position and of the same size of the Label), and set the color of the canvas to self.bcolor, i.e. the value contained in the list property we just created.

The Kivy Factory (last line) gives the final trick to integrate our new BLabel to the available Kivy classes in the Kivy Language.

And that is it!. Here is an example of how to use the class. Notice that all we need to do is change the bcolor property and the color adjusts accordingly.

import kivy
from kivy.uix.gridlayout import GridLayout

from import App
from kivy.lang import Builder

import LabelB

  rows: 2
    bcolor: 1,0,0,1
    bcolor: 0,1,0,1

class MyGrid(GridLayout):

class TheApp(App):
    def build(self):
        return MyGrid()


And here is the final screenshot.

Screenshot from 2015-07-15 13:23:58

3 thoughts on “Kivy Label (or widget) with background color property

Leave a reply