python - ObjectProperty 类的使用

标签 python kivy

我刚开始学习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

最佳答案

Kivy Property 是一个类似于 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[.]

(来自基维Property documentation)

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

<PongGame>:
    ball: pong_ball

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

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

ball = ObjectProperty(PongBall())

关于python - ObjectProperty 类的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580794/

相关文章:

Python - 将txt文件读入列表 - 显示新列表的内容

python - 新数据库和 Django manage.py shell 和 syncdb 没有运行

Python正则表达式删除花括号内的子字符串

python - 改变 Kivy 弹出窗口的背景

python - 在 Kivy 中构建一个简单的进度条或加载动画?

python - 基维 - MotionEvent : on_mouse_pos

python - 比较python中的旋转列表

Python:将列表转换为字典

python - 如何定义当用户在 TextInput 中输入文本并在 Kivy 中按 Enter 时会发生什么?

python - kivy 中的音频位置没有改变