1
我正在學習使用基維,所以我走過了傍教程,並開始搞亂了代碼。所以,我除去了彈跳球之外的所有東西,並決定根據需要生成多個球。我遇到的問題是,雖然我可以在應用程序已經運行時將球放在我想要的位置(例如,添加一個觸摸球很好),但是當我在應用程序build()中添加球時,他們沒有得到放置正確。這是我的代碼。觸摸的球,正確地從中心開始。但build()中添加的球從左下角開始。爲什麼?我想添加更多具有不同屬性的移動小部件,但我似乎無法弄清楚如何將它們放置在應用程序啓動時。基維中心小工具
#:kivy 1.0.9 <World>: canvas: Ellipse: pos: self.center size: 10, 10 <Agent>: size: 50, 50 canvas: Ellipse: pos: self.pos size: self.size
from random import randint from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty, ListProperty from kivy.vector import Vector from kivy.clock import Clock class World(Widget): agents = ListProperty() def add(self): agent = Agent() agent.center = self.center agent.velocity = Vector(4, 0).rotate(randint(0, 360)) self.agents.append(agent) self.add_widget(agent) def on_touch_down(self, touch): self.add() def update(self, dt): for agent in self.agents: agent.move() if agent.y < 0 or agent.top > self.height: agent.velocity_y *= -1 if agent.x < 0 or agent.right > self.width: agent.velocity_x *= -1 class Agent(Widget): velocity_x = NumericProperty(0) velocity_y = NumericProperty(0) velocity = ReferenceListProperty(velocity_x, velocity_y) def move(self): self.pos = Vector(*self.velocity) + self.pos class WorldApp(App): def build(self): world = World() # add one ball by default world.add() Clock.schedule_interval(world.update, 1.0/60.0) return world if __name__ == '__main__': WorldApp().run()