【问题标题】:How to create Variables / properties in the kv file?如何在 kv 文件中创建变量/属性?
【发布时间】:2019-11-11 21:29:32
【问题描述】:

我想在我的 rouded 按钮中创建一个“属性”,以便能够执行以下操作:

RoundedButton:
    radius: 30

我的python代码:我在Python中有这个类:

class RoundedButton(Button):
    radius = NumericProperty(30)
        

在我的 kv 文件中:

<RoundedButton@Button>:
    background_color: 0,0,0,0  # the last zero is the critical on, make invisible
    canvas.before:
        Color:
            rgba: (.4,.4,.4,1) if self.state=='normal' else (0,.7,.7,1)  # visual feedback of press
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [10,]



<MenuScreen>
    GridLayout:
        size: root.width, root.height
        GridLayout:
            RoundedButton:
                size: 300, 300

我想写这样的东西:

<RoundedButton@Button>:
    radius: radius
    background_color: 0,0,0,0  # the last zero is the critical on, make invisible
    canvas.before:
        Color:
            rgba: (.4,.4,.4,1) if self.state=='normal' else (0,.7,.7,1)  # visual feedback of press
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [radius,]


<MenuScreen>
    GridLayout:
        size: root.width, root.height
        GridLayout:
            RoundedButton:
                size: 300, 300
                radius: 10

【问题讨论】:

    标签: python python-3.x kivy kivy-language


    【解决方案1】:
    RoundedButton:
        radius: 30
    

    你可以而且……有。这就是这样做的方法。

    但是,它带有一些陷阱和竞争条件,这些问题与属性的确切创建时间和可以访问的时间有关。你可能会也可能不会击中这些。我通常认为在 Python 中定义类及其属性是更好的做法。

    radius: radius
    

    这一行没有意义,你的变量半径没有定义,设置为一些实际值。

    【讨论】:

    • 另外,如果您在 Python 中定义 RoundedButton,然后在您的 kv 中包含 &lt;RoundedButton@Button&gt;: 规则,您应该会看到 [WARNING] [Factory ] Ignored class "RoundedButton" re-declaration. 尽管它似乎仍然尊重内容您可以通过从kv 规则中删除@Button 来消除警告。这会将其从动态类声明更改为定义任何 RoundedButton 的一些默认属性的简单规则。
    猜你喜欢
    • 2023-03-09
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2017-10-04
    • 2013-08-22
    相关资源
    最近更新 更多