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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With