【问题标题】:Kivy Custom Button TextKivy 自定义按钮文本
【发布时间】:2018-10-26 17:49:53
【问题描述】:

从 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

当链接到 .kv 文件中的小部件时,您会看到“文本”标签出现在 (0,0) 而不是按钮顶部。为这个自定义按钮设置文本的最佳方式是什么?

【问题讨论】:

    标签: python kivy


    【解决方案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
    

    【讨论】:

    • 这太好了,谢谢!只是为了向未来的读者澄清,请确保在第 1 行使用“标签”而不是“小部件”。
    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 2023-04-09
    • 2014-02-15
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多