Kivy自定义按钮文本

时间:2018-10-26 17:49:54

标签: python kivy

从python端向自定义按钮添加文本的最佳方法是什么?到目前为止,这是我的代码:

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

当链接到.k​​v文件中的小部件时,您会看到“文本”标签显示在(0,0)而不是按钮的顶部。设置此自定义按钮文本的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

如果打算将Label放置在按钮的中间,则单击文本时on_press事件将不起作用,最好直接使用Label,并且绘画必须在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