无法使用Kivy移动小部件
我想移动一个矩形并遵循youtube中使用的代码(Alexander Taylor的kivy速成课程11)。输入代码后,矩形会显示在屏幕上,但不会移动
python代码
class CRect:
velocity = ListProperty([20, 10])
def __init__(self, **kwargs):
super(CRect, self).__init__(**kwargs)
Clock.schedule_interval(self.update, 1/60)
def update(self):
self.x += self.velocity[0]
self.y += self.velocity[1]
if self.x < 0 or (self.x+self.width) > Window.width:
self.velocity[0] *= -1
if self.y < 0 or (self.y+self.height) > Window.height:
self.velocity[1] *= -1
if __name__ == '__main__':
RRApp().run()
kv代码
<DemoCreator>:
CRect:
canvas:
Color:
rgba: 1,0,0,1
Rectangle:
pos: 100,0
size: 40,40
<CRect@Widget>
无错误消息。但是不能移动小部件
答案 0 :(得分:0)
您需要以某种方式引用矩形。您可以在python中进行创建,然后将tha矩形定义为小部件的类属性。在下面的示例中,我只取了画布的最后一个孩子(在本例中为矩形),然后设置其位置。
from kivy.uix.widget import Widget
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.clock import Clock
from kivy.core.window import Window
KV = """
CRect:
canvas:
Color:
rgba: 1,0,0,1
Rectangle:
pos: 100,0
size: 40,40
"""
class CRect(Widget):
velocity = ListProperty([20, 10])
rect_x, rect_y = 0, 0
def __init__(self, **kwargs):
super(CRect, self).__init__(**kwargs)
Clock.schedule_interval(self.update, 1/60)
def update(self, dt):
rect = self.canvas.children[-1]
self.rect_x += self.velocity[0]
self.rect_y += self.velocity[1]
rect.pos = self.rect_x, self.rect_y
if self.rect_x < 0 or (self.rect_x+rect.size[0]) > Window.width:
self.velocity[0] *= -1
if self.rect_y < 0 or (self.rect_y+rect.size[1]) > Window.height:
self.velocity[1] *= -1
class MyApp(App):
def build(self):
return Builder.load_string(KV)
MyApp().run()