Circular (Oval like) Button Using Canvas in Kivy


Kivy is a free and open−source Python framework that allows developers to create cross−platform applications. It comes with a plethora of pre−built widgets such as buttons, labels, text inputs, and many more. However, there may be situations where these pre−built widgets do not fit the project's requirements, and we may need to create custom widgets. In such cases, the Canvas module in Kivy provides an excellent solution to create bespoke user interface elements.

In this article, we will focus on creating a circular button with an oval−like shape using the Canvas module in Kivy. We will guide you through the steps of creating a simple circular button and then demonstrate how to further personalize it by adding a label to the center. Armed with this knowledge, you will be able to design and implement a wide variety of custom user interface elements using the Canvas module in Kivy.

What is the Canvas Module?

With the canvas module in Kivy, developers can easily display various shapes and graphics on the screen, all rendered efficiently and quickly using OpenGL technology. This powerful module provides a wide range of drawing instructions, such as Rectangles, Ellipses, and Lines, which allows developers to create complex and intricate designs and shapes for their applications.

Creating a Kivy Application

To create a Kivy application, we need to define a root widget that will contain all other widgets. In this case, we will use a BoxLayout widget. Here's the code:

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class MyBoxLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        button = Button(text='Click Me!')
        self.add_widget(button)

class MyApp(App):
    def build(self):
        return MyBoxLayout()

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

The code above creates a simple Kivy application that displays a button with the text "Click Me!".

Creating a Circular Button

After setting up our Kivy application, it's time to create a circular button using the canvas module in Kivy. We can achieve this by creating a new widget called CircularButton. This widget will inherit from the Button widget and replace its draw() method with a custom one that draws a circular shape on the canvas.

from kivy.graphics import Ellipse, Color
from kivy.uix.button import Button

class CircularButton(Button):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def draw(self):
        with self.canvas:
            Color(0, 1, 0, 1) # set the color of the button
            d = min(self.size) # diameter of the button
            Ellipse(pos=self.pos, size=(d, d)) # draw the button

The code above defines a new widget called CircularButton that inherits from the Button widget. It overrides the draw() method and uses the canvas module to draw a circular button. We set the color of the button to green (0, 1, 0, 1) and the diameter of the button to the minimum of its width and height.

Let's go through the code step by step:

  • We import the Ellipse and Color classes from the kivy.graphics module.

  • We define a new widget called CircularButton that inherits from the Button widget.

  • We override the draw() method of the Button widget. The draw() method is called whenever the widget needs to be redrawn, such as when it is added to the screen or when its size or position changes.

  • We use the with a statement to create a canvas context. All the drawing instructions that follow will be executed on the canvas.

  • We set the color of the button to green using the Color instruction.

  • We calculate the diameter of the button by taking the minimum of its width and height.

  • We use the Ellipse instruction to draw a circular button with the calculated diameter and position at the same position as the widget.

  • We can modify our Kivy application to use the CircularButton widget instead of the regular Button widget.

class MyBoxLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        button = Circular
        Button(text='Click Me!')
        self.add_widget(button)

class MyApp(App):
    def build(self):
        return MyBoxLayout()

if name == 'main':
    MyApp().run()

By updating the MyBoxLayout class to use the CircularButton widget instead of the Button widget in the code provided above, we can now observe a circular button instead of a rectangular one when the Kivy application is executed.

Customizing the Circular Button

The circular button we created above is a simple example, but we can customize it further by adding more drawing instructions to the canvas context. For example, we can add a label to the center of the button:

from kivy.graphics import Ellipse, Color
from kivy.uix.button import Button
from kivy.uix.label import Label

class CircularButton(Button):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.label = Label(text=self.text)

    def draw(self):
        with self.canvas:
            Color(0, 1, 0, 1) # set the color of the button
            d = min(self.size) # diameter of the button
            Ellipse(pos=self.pos, size=(d, d)) # draw the button
            self.label.texture_update()
            w, h = self.label.texture_size
            x = self.center_x - w / 2
            y = self.center_y - h / 2
            Color(1, 1, 1, 1) # set the color of the label
            Rectangle(texture=self.label.texture, pos=(x, y), size=self.label.texture_size) # draw the label

Above, we included a label at the center of the circular button. This involved creating a new Label widget and setting its text to that of the button. Then, we overrode the draw() method of the Button widget and appended a Rectangle instruction to draw the label in the center of the button.

We first call the texture_update() method of the label to update its texture. We then get the size of the texture and calculate the position of the label so that it is centered on the button.

Conclusion

To summarize, we can create a circular button using the canvas module in Kivy by using the Ellipse instruction. We can customize the button further by adding more drawing instructions to the canvas context, such as a label. The canvas module in Kivy provides a powerful way to create custom user interface elements, and it is a useful tool to have in our Kivy development environment.

Updated on: 19-Jul-2023

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements