不确定Kivy如何使用ObjectProperty()并将其与.kv文件中的属性链接

时间:2018-12-06 23:44:24

标签: python kivy kivy-language

我想对ObjectProperty(None)如何返回链接到文件“ pong.kv”中设置的属性的对象进行详细说明。

PongBall属性中的属性“ id:pong_ball”是什么,这行“ ball:pong_ball”是做什么的?

我可以连接大多数点,但是有些点不见了……我将不胜感激。在此先感谢!

pong.py(在下面...另外...我知道我在污染我的名称空间)

from random import random
import kivy
kivy.require('1.9.1')
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color, Ellipse, Line
from kivy.vector import Vector
from kivy.properties import NumericProperty, ReferenceListProperty, \
    ObjectProperty
from random import randint
from kivy.clock import Clock

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

    def serve_ball(self):
        self.ball.center = self.center
        self.ball.velocity = Vector(4, 0).rotate(randint(0, 360))
    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
class PongBall(Widget):

    # velocity of the ball on x and y axes
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)

    # referencelist property so we can use ball.velocity as
    # a shorthand, just like e.g. w.pos for w.x and w.y
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    # ''move'' function will move the ball one step. This
    # will be called in equal intervals to animate the ball

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PongApp(App):
    def build(self):
        game = PongGame()
        game.serve_ball()
        Clock.schedule_interval(game.update, 1.0/60.0)
        return game

if __name__ == '__main__':
    PongApp().run()

pong.kv(下)

#:kivy 1.9.1

<PongGame>:
    ball: pong_ball

    canvas:
        Rectangle:
            pos: self.center_x - 5, 0
            size: 10, self.height

    Label:
        font_size: 70
        center_x: root.width / 4
        top: root.top - 50
        text: "0"

    Label:
        font_size: 70
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: "0"

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

<PongBall>:
    size: 50, 50
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

0 个答案:

没有答案