1
votes

What is the best way to add text to a custom button, from the python-side? Here is my code so far:

class CircularButton(ButtonBehavior, Widget):

        # code inspired from:
        # https://github.com/kivy/kivy/issues/4263#issuecomment-217430358
        # https://stackoverflow.com/a/42886979/6924364
        # https://blog.kivy.org/2014/10/updating-canvas-instructions-declared-in-python/

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

        self.add_widget(Label(text='test')) # <-- put this in the middle of the button

        with self.canvas:
            Color(rgba=(.5,.5,.5,.5))
            self.shape = Ellipse(pos=self.pos,size=self.size)

        self.bind(pos=self.update_shape, size=self.update_shape)

    def update_shape(self, *args):
        self.shape.pos = self.pos
        self.shape.size = self.size

    def collide_point(self, x, y):
        return Vector(x, y).distance(self.center) <= self.width / 2

When linked to a widget in the .kv file, you see that the 'text' label appears at (0,0) rather than on top of the button. What is the best way to set the text for this custom button?

1

1 Answers

1
votes

If you intend to place a Label in the middle of the button the on_press event will not work if you click on the text, it is best to use Label directly, and the painting must be done on canvas.before.

class CircularButton(ButtonBehavior, Label):
    def __init__(self, **kwargs):
        super(CircularButton,self).__init__(**kwargs)
        self.text='test'
        with self.canvas.before:
            Color(rgba=(.5,.5,.5,.5))
            self.shape = Ellipse(pos=self.pos,size=self.size)
        self.bind(pos=self.update_shape, size=self.update_shape)

    def update_shape(self, *args):
        self.shape.pos = self.pos
        self.shape.size = self.size

    def collide_point(self, x, y):
        return Vector(x, y).distance(self.center) <= self.width / 2