Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add background colour to a Label in Kivy?

Tags:

python

kivy

Using Kivy, how can you change the background colour of a label in Python and not by using the Kv language?

I have tried this:

with self.canvas:
    Color(1., 0, 0)
    Rectangle(pos=(10, 10), size=(500, 500))

However this just creates a red square on the bottom left of the screen. It would be really useful if there was a alternative to the idea above and I could change the background colour of a label using python and not kv language.

like image 333
m.adam Avatar asked Oct 16 '25 14:10

m.adam


2 Answers

Well, Rectangle position and size should rather match Label position and size:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle

class MyApp(App):
    def build(self):
        layout = FloatLayout()
        label = Label(
            text='test',
            pos=(20, 20),
            size=(180, 100),
            size_hint=(None, None))
        with label.canvas:
            Color(0, 1, 0, 0.25)
            Rectangle(pos=label.pos, size=label.size)

        layout.add_widget(label)

        return layout


if __name__ == '__main__':
    MyApp().run()

Version with auto-adjusting:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle

class MyLabel(Label):
    def on_size(self, *args):
        self.canvas.before.clear()
        with self.canvas.before:
            Color(0, 1, 0, 0.25)
            Rectangle(pos=self.pos, size=self.size)

class MyApp(App):
    def build(self):
        layout = FloatLayout()
        label = MyLabel(
            text='test',
            pos=(20, 20),
            size_hint=(0.5, 0.5))
        layout.add_widget(label)
        return layout


if __name__ == '__main__':
    MyApp().run()
like image 126
Nykakin Avatar answered Oct 18 '25 07:10

Nykakin


Just to share my trick after nearly 5 years of your question is that instead of using canvas, you can just simply use Button: with disabled: True. Because button is a clickable label, then why don't we reuse it's background (This to make you code as simplest as possible)

If you are wonder how to remove it's darken color, you can see here.

like image 44
Ten Kho Avatar answered Oct 18 '25 05:10

Ten Kho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!