如何在kivy python中制作一个不规则的四边形按钮?

How to make an irregular quadrilateral shaped button in kivy python?

我正在尝试用 kivy 制作一个 android 应用程序。它的用户界面以这两个名为“2D”和“3D”的按钮开始。请帮我用kivy制作一个不规则的四边形按钮。

您可以扩展 Button 使其表现得好像它是两个 Buttons:

class MyButton(Button):
    my_state = StringProperty('')  # this will be 'b1' or 'b2', even when button is not down
    my_down_image = StringProperty('')
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            rx, ry = self.to_widget(*touch.pos, relative=True)
            if ry > self.height/2.0:  # more complex geometry calculation required
                self.my_down_image = 'B2Down.png'
                self.my_state = 'b2'
            else:
                self.my_down_image = 'B1Down.png'
                self.my_state = 'b1'
        return super(MyButton, self).on_touch_down(touch)

MyButton class 在 Button 的基础上增加了两个属性,即 my_statemy_down_image 属性。 my_state 属性 将是 b1b2,具体取决于按下的是哪个子按钮(由 on_touch_down() 设置)。 my_down_image 属性 设置为 B1Down.pngB2Down.png 描述了我们希望 MyButtonB1 或 [=29 时的样子=] 被按下。上面代码中简单的 y 坐标比较将不起作用,必须更复杂才能正确确定按下了哪个子按钮。 MyButton 可以像这样在 kv 中使用:

MyButton:
    background_normal: 'B1andB2.png'
    on_press: app.do_butt_press(self)
    on_release: app.do_butt_release(self)

app 方法看起来像:

def do_butt_press(self, button):
    print('on_butt_press', button.state, button.my_state)

def do_butt_release(self, button):
    print('on_butt_release', button.state, button.my_state)

kv中:

<-MyButton>:
    state_image: self.background_normal if self.state == 'normal' else self.my_down_image
    disabled_image: self.background_disabled_normal if self.state == 'normal' else self.background_disabled_down
    canvas:
        Color:
            rgba: self.background_color
        BorderImage:
            border: self.border
            pos: self.pos
            size: self.size
            source: self.disabled_image if self.disabled else self.state_image
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            texture: self.texture
            size: self.texture_size
            pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)

上面的 kv 规则大部分只是 Kivy 使用的默认 Button 规则的副本。唯一的变化是在 state_image 定义中使用了 my_down_image

对于此示例,B1andB2.png 可以是:

B1Down.png:

B2Down.png