ObjectProperty类的用法

2024-09-28 21:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习kivy,我对ObjectProperty类的用法以及它如何将None作为参数感到非常困惑。有人能解释一下吗?我在kivy教程中找到的:

class PongGame(Widget):
    ball = ObjectProperty(None)

    def update(self, dt):
        self.ball.move()

        # bounce off top and bottom
        if (self.ball.y < 0) or (self.ball.top > self.height):
            self.ball.velocity_y *= -1

        # bounce off left and right
        if (self.ball.x < 0) or (self.ball.right > self.width):
            self.ball.velocity_x *= -1

Tags: orandselfrightnone用法参数if
1条回答
网友
1楼 · 发布于 2024-09-28 21:27:01

KivyProperty是一个类似于Python自己的property的便利类,但它还提供类型检查、验证和事件。ObjectPropertyProperty类的一个特殊子类,因此它具有与其相同的初始化参数:

By default, a Property always takes a default value[.] The default value must be a value that agrees with the Property type. For example, you can’t set a list to a StringProperty, because the StringProperty will check the default value.

None is a special case: you can set the default value of a Property to None, but you can’t set None to a property afterward. If you really want to do that, you must declare the Property with allownone=True[.]

(来自Kivy^{}

在代码中,PongGame有一个ball属性,该属性最初设置为None,稍后将被分配一个ball对象。这在kv文件中定义:

<PongGame>:
    ball: pong_ball

    PongBall:
        id: pong_ball
        center: self.parent.center

因为没有对象被传递给初始化器,所以任何对象都可以分配给该属性。可以通过使用虚拟值初始化球对象,将其限制为仅包含球对象:

ball = ObjectProperty(PongBall())

相关问题 更多 >