Search code examples
kivykivy-language

How create a circular button with kivy?


I need a perfect round button with no rectangle.I have made but when i click outside of the circle(corners) it also pressed, it behaves as if it is a rectangle inside which a circle is drawn that is a problem.Please Help!

class Dom(BoxLayout):
    pass

class CBB(ButtonBehavior, Label):
    pass

class CBApp(App):
    pass

CBApp().run()

Kivy file---CB.kv
Dom:
<CBB>:
    canvas:
        Color:
            rgba: (1, 0, 1, 0.1) if self.state == 'down' else (1,1,0,0.1)
        Ellipse:
            id:el
            pos: self.center[0]- 100,self.center[1]- 100
            size: 200, 200
            angle_start: 0
            angle_end: 360

        
<Dom>:
    BoxLayout:
        orientation:"vertical"
        CBB:
            text:"Hello World"
            on_press:print("Hello World")

Solution

  • You can add an on_touch_down() method to your CBB that checks if the button press occurs with the circle:

    class CBB(ButtonBehavior, Label):
        def on_touch_down(self, touch):
            dist = sqrt( pow(touch.pos[0] - self.center[0], 2) + pow(touch.pos[1] - self.center[1], 2) )
            if dist <= 100:  # radius of the circle
                return super(CBB, self).on_touch_down(touch)
            else:
                return False