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
from kivy.uix.label import Label from kivy.properties import ListProperty from kivy.factory import Factory from kivy.lang import Builder Builder.load_string(""" <LabelB>: bcolor: 1, 1, 1, 1 canvas.before: Color: rgba: self.bcolor Rectangle: 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.
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 kivy.app import App from kivy.lang import Builder import LabelB Builder.load_string(""" <MyGrid>: rows: 2 LabelB: bcolor: 1,0,0,1 LabelB: bcolor: 0,1,0,1 """) class MyGrid(GridLayout): pass class TheApp(App): def build(self): return MyGrid() TheApp().run()
And here is the final screenshot.
How in a Label.text and textinput i can use arabic language or persian or urdu or …
Simple, clean solution for a basic kivy task. Works perfectly. Thank you for saving this rainy day at home in Finland (:
Thanks man, this helps me big time, cheers