【发布时间】:2019-08-08 04:23:24
【问题描述】:
我正在尝试学习用于 Python GUI 编程的 Kivy 包的基础知识。我已经完成了 Pong 教程 (here) 并想通过改变乒乓球每次撞到墙上的颜色来测试我的理解力。它不起作用 - 每次球撞到墙上时,我都会收到一个错误,说没有颜色属性。我做错了什么?
main.py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.graphics import Color
from random import randint
class PongBall(Widget):
vel_x = NumericProperty(0)
vel_y = NumericProperty(0)
vel = ReferenceListProperty(vel_x,vel_y)
def move(self):
self.pos = Vector(*self.vel) + self.pos
class PongGame(Widget):
ball = ObjectProperty(None)
def serve_ball(self):
self.ball.center = self.center
self.ball.vel = Vector(4,0).rotate(randint(0,360))
def update(self, dt):
self.ball.move()
if(self.ball.y < 0) or (self.ball.top > self.height):
self.ball.vel_y *= -1
self.ball.Color(1,0,0)
if(self.ball.x < 0) or (self.ball.right > self.width):
self.ball.vel_x *= -1
self.ball.Color(0,1,0)
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()
KV 文件:
#:kivy 1.0.9
<PongBall>:
size: 50, 50
canvas:
Ellipse:
pos: self.pos
size: self.size
Color:
rgba: 1, 1, 0, 0
<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
【问题讨论】:
标签: python python-3.x kivy kivy-language