这与其他问题非常相关。唯一的区别是我动态添加椭圆with self.canvas
而不是使用生成器(Builder.load_string
或Builder.load_file
)。所以这里是有效的代码。当您单击椭圆时,它会移动并更改颜色:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
from kivy.graphics import Color, Ellipse
Builder.load_string("""
<CircleWidget>:
canvas:
Color:
rgba: self.r,1,1,1
Ellipse:
pos: self.pos
size: self.size
""")
class CircleWidget(Widget):
r = NumericProperty(0)
def __init__(s, **kwargs):
s.size= [50,50]
s.pos = [100,50]
super(CircleWidget, s).__init__(**kwargs)
def on_touch_down(s, touch):
if s.collide_point(touch.x,touch.y):
s.pos = [s.pos[1],s.pos[0]] # this works
s.r = 1.0 # this also works
class TestApp(App):
def build(s):
parent = Widget()
parent.add_widget(CircleWidget())
return parent
if __name__ == '__main__':
TestApp().run()
如果我尝试在不使用 的情况下做同样的事情Builder
,它就不再起作用了:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
from kivy.graphics import Color, Ellipse
class CircleWidget(Widget):
r = NumericProperty(0)
def __init__(s, **kwargs):
s.size= [50,50]
s.pos = [100,50]
super(CircleWidget, s).__init__(**kwargs)
with s.canvas:
Color(s.r,1,1,1)
Ellipse(pos = s.pos, size = s.size)
def on_touch_down(s, touch):
if s.collide_point(touch.x,touch.y):
s.pos = [s.pos[1],s.pos[0]] # This doesn't work anymore
s.r = 1.0 # Neither do this
class TestApp(App):
def build(s):
parent = Widget()
parent.add_widget(CircleWidget())
return parent
if __name__ == '__main__':
TestApp().run()
代码运行并实际调用事件。此外,Widget 被移动(即使它在视觉上不清晰),但画布的 Instructions 没有更新。
有任何想法吗?