无法使用Kivy移动小部件
我想移动一个矩形,并且遵循了youtube中使用的代码( Alexander Taylor编写的kivy crash course 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>
没有错误消息。但无法移动小部件
发布于 2019-05-23 01:23:54
您需要以某种方式引用矩形。您可以在python中这样做,并将矩形定义为小部件的类属性。在下面的示例中,我只获取画布的最后一个子项,在本例中是矩形,并设置其位置。
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()
https://stackoverflow.com/questions/56261420
复制相似问题