如何解决在 kivy 中检查子交互的语法
我正在从一本涉及制作绘画应用程序的书中学习 kivy。作者曾在画布类(继承自 Widget)上引入了新按钮,并说我们必须检查应用程序在画布上接收到的点击是否也位于它的一个子项上。在这种情况下,我们会忽略前者并针对后者采取行动。 我想通过循环遍历 self.children 来实现这一点,检查 on_touch_down(touch) 成员函数是否为任何孩子返回 true,如果是这种情况,则从函数返回:
class CanvasWidget(Widget):
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.my_color = get_color_from_hex('#FF0000')
self.line_width=2
def on_touch_down(self,touch):
for child in self.children:
if(child.on_touch_down(touch)):
return
with self.canvas:
Color(rgba=self.my_color)
touch.ud['current_line'] = Line(points=(touch.x,touch.y),width=self.line_width)
但是,我不遵循并想了解他的速记语法:
class CanvasWidget(Widget):
def __init__(self,touch):
#I don't understand the following line
if Widget.on_touch_down(self,touch):
return
#Widget refers to the parent class (I hope?) how does it check with the
#children?
with self.canvas:
Color(rgba=self.my_color)
touch.ud['current_line'] = Line(points=(touch.x,width=self.line_width)
任何清晰度表示赞赏。谢谢!
解决方法
Widget
类是所有 kivy 小部件的基类,它通过其 touch
方法处理 on_touch_down()
事件向其子项的传播。与直接引用 Widget
基类不同,更好的方法是使用 super()
方法,如下所示:
if super(CanvasWidget,self).on_touch_down(touch):
return True
如果有任何孩子想要停止传播,这会进行传播并返回 True
(停止传播)。 Widget
中执行此操作的代码是:
for child in self.children[:]:
if child.dispatch('on_touch_down',touch):
return True
由于它不直接引用 Widget
基类,因此如果您决定更改 super()
的基类,CanvasWidget
方法更安全。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。