我需要能够生成各种形状、大小和颜色的任意“行星”,并在多体模拟中四处移动它们,添加它们,并在模拟中发生事情时移除它们。
我已经向 kivy 小部件的 Canvas 实例添加了一些操作。在试图找到解决这个问题的方法时,为了比较,我还在 kivy lang 文件中为相应的派生 Widget 类定义了一个形状(基于 Pong 教程)。
当改变widget的位置时,只有kv lang文件中定义的shape会随着widget移动。 python 3代码中定义的不动。
在 Kivy 中移动小部件的 Canvas 项目以响应小部件位置的变化的正确方法是什么?
这里是一些示例代码,使用 Python 3 和 Kivy,一旦事件产生“星球”
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import *
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.lang import Builder
class Planet(Widget):
# velocity of the ball on x and y axis
dx = NumericProperty(0)
dy = NumericProperty(0)
def init(self, pos=(50,50), **kwargs):
""" Initialize the planet"""
self.pos = pos
print("Init planet. pos:", self.pos)
# These shapes do not move with the widget.
# Why?
# Only the white circle in .kv lang moves with it.
self.canvas.add(Color(0.8,0,0))
self.canvas.add(Ellipse(pos=self.pos, size=(50,50)))
def move(self):
""" Move the planet. """
self.pos = Vector(self.velocity) + self.pos
print("Planet now at", self.pos)
class System(Widget):
mars = ObjectProperty(None)
def update(self, dt):
print("Update! " , dt)
if self.mars:
self.mars.move()
def spawn(self, dt):
print("Insert!", dt)
self.mars = Planet()
self.mars.init()
self.add_widget(self.mars)
self.mars.velocity = (1,1)
class PlanetApp(App):
def build(self):
sys = System()
Clock.schedule_interval(sys.update, 1/4)
Clock.schedule_once(sys.spawn, 3)
return sys
if __name__ == '__main__':
Builder.load_string("""
#:kivy 1.0.9
<Planet>
canvas:
Ellipse:
pos: self.pos
size: self.size
""")
PlanetApp().run()
谢谢!
请您参考如下方法:
在发布我自己的问题后,我想通了...
更新小部件的位置不会更新该小部件 Canvas 中对象的位置。但是您可以单独更新小部件 Canvas 中的位置。
我不明白为什么 kv lang 实现会更新其 Canvas 中对象的位置,而 py 实现却不会 - 所以也许其他人可以提供更彻底的答案。文档定期指出在代码示例的 py 实现中完成的事情与 kv lang 相同。但这显然不完全正确。所以为什么?谁能解释一下?
但是,这有效...
class Planet(Widget):
...
# store the shapes in the canvas in the object.
# (could put in a list to iterate over them to update pos)
ellipse = ObjectProperty(None)
...
def init(self, pos=(50,50), **kwargs):
...
# save the element we're adding to the canvas
self.ellipse = Ellipse(pos=self.pos, size=(50,50))
self.canvas.add(self.ellipse)
def move(self):
self.pos = Vector(self.velocity) + self.pos
self.ellipse.pos = self.pos # move the canvas element too
print("Planet now at", self.pos)
