novice
novice

Reputation: 520

How to change background color in kivy?

I have just started learning kivy. Please bear with me in case of my absurdity and stupidity.

Here just copy pasted the code from official site.

import kivy
from kivy.app import App
from kivy.uix.label import Label

class MyApp(App):
   def build(self):
      return Label(text='Hello world',)

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

And the output is in the link.

What I essentially wanted to know that how I can change the background (currently black) to some different color.

I have read some parts of documents ,Found documentation for changing color of widget but screen (probably not the accurate word).

I would really appreciate the advices and suggestions.

Thanks in advance.

Upvotes: 1

Views: 1242

Answers (1)

John Anderson
John Anderson

Reputation: 38822

You can use the canvas of the Label to paint a background color like this:

import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label

class MyLabel(Label):
    pass

Builder.load_string('''
<MyLabel>:
    canvas.before:
        Color:
            rgba: 1,0,0,1
        Rectangle:
            pos: self.pos
            size: self.size
''')

class MyApp(App):
   def build(self):
      return MyLabel(text='Hello world',)

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

To do this without using the kv language is more complicated because you must set up the binding to pos and size that the kv language does for you automatically. Here is the equivalent without using kv:

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

class MyLabel(Label):
    def __init__(self, **kwargs):
        super(MyLabel, self).__init__(**kwargs)
        with self.canvas.before:
            Color(1, 0, 0, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)

    def on_pos(self, *args):
        self.rect.pos = self.pos

    def on_size(self, *args):
        self.rect.size = self.size

        
class MyApp(App):
    def build(self):
        return MyLabel(text='Hello world',)

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

For more information about the canvas, see the documentation

Upvotes: 2

Related Questions