Adding Text and Background Color in Kivy: A Beginner’s Tutorial – Part 2

Posted by

Kivy Tutorial for Beginners: Part 2

Kivy Tutorial for Beginners: Part 2 – Add Text And Background Color

Welcome to part 2 of our Kivy tutorial series for beginners. In this tutorial, we will learn how to add text and background color to our Kivy application.

Adding Text

To add text to our Kivy application, we can use the Label widget. Here’s an example of how to add a simple label with the text “Hello, Kivy!”:

“`html

In the above example, we’ve created a Label widget with the text “Hello, Kivy!” and set the font size to 24. We’ve also set the text color to red using RGBA values (1 for red, 0 for green, 0 for blue, and 1 for alpha).

Adding Background Color

To add a background color to our Kivy application, we can use the canvas and Color widgets. Here’s an example of how to set the background color to blue:

“`html

canvas:
Color:
rgba: 0, 0, 1, 1
Rectangle:
size: self.size
pos: self.pos
“`

In the above example, we’ve created a Widget and added a canvas with a Color widget to set the background color to blue (RGBA values of 0, 0, 1, 1). We’ve also added a Rectangle widget to fill the entire size of the Widget with the specified background color.

Putting It All Together

Now let’s put the text and background color together in a simple Kivy application. Here’s the complete code:

“`html
#:kivy 1.0.9

BoxLayout:
orientation: ‘vertical’
Label:
text: ‘Hello, Kivy!’
font_size: 24
color: 1, 0, 0, 1
Widget:
canvas:
Color:
rgba: 0, 0, 1, 1
Rectangle:
size: self.size
pos: self.pos
“`

In the above code, we’ve used a BoxLayout to arrange the Label and Widget vertically. The Label displays the text “Hello, Kivy!” in red color and the Widget has a blue background color.

Now that you’ve learned how to add text and background color to your Kivy application, you can continue to explore more features and widgets to create amazing user interfaces with Kivy.