Kivy:了解应用程序中的widget实例

2024-04-27 00:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我还在热身,希望你不要介意我再问一个问题!在

我试图了解我的一些小部件的预定事件。出于上下文的考虑,我希望能够将节点移动到边上,并使边“捕捉”到节点。在

这是我的.kv文件:

<GraphInterface>:
    node: graph_node
    edge: graph_edge

    GraphNode:
        id: graph_node
        center: self.parent.center

    GraphEdge:
        id: graph_edge
        center: 200,200

<GraphNode>:
    size: 50, 50
    canvas:
        Color:
        rgba: (root.r,1,1,1)
    Ellipse:
        pos: self.pos
        size: self.size


<GraphEdge>:
    size: self.size
    canvas:
        Color:
            rgba: (root.r,1,1,1)
        Line:
            width: 2.0
            close: True

我在节点和边之间有一个冲突检测事件,我正在程序中动态创建节点和边。下面是相关的python代码:

^{pr2}$

好吧,那真是太多了(抱歉)!在

基本上,只有在.kv文件中创建的初始边和节点才会检测到碰撞。新创建的边和节点不能通过碰撞机制进行交互。在

如果人们愿意,我可以提供更多的代码,但我认为应该是所有相关的部分。谢谢!在

编辑:

新方法:

def on_touch_move(self, touch):
    if touch.grab_current is self:
        self.pos=[touch.x-25,touch.y-25]
    for widget in self.parent.children:
        if isinstance(widget, GraphEdge) and widget.collide_widget(self):
            print "collision detected"
            widget.snap_to_node(self)
            return True
    return super(GraphNode, self).on_touch_move(touch)

有了这段代码,我仍然可以通过快速移动节点来断开连接。在

编辑2:

我也许过早地给出了答案。我只能与我生成的第一个边交互。我还有一个奇怪的错误,第一条边和第一个节点似乎有相同的颜色属性。也许这应该在它自己的问题中提出。在


Tags: 代码posselfnodesize节点事件widget
1条回答
网友
1楼 · 发布于 2024-04-27 00:30:54

问题是你对新的GraphEdgeGraphNode添加到你的GraphInterface时没有反应。在update

    self.edge.snap_to_node(self.node)

self.edge始终是创建的kv GraphEdge。与self.node相同。在

您应该在触摸交互中尝试将此交互添加到GraphNode类本身。在GraphNode.on_touch_move()中尝试类似的操作:

^{pr2}$

这样,每个GraphNode在其同级中搜索可能与之发生碰撞的任何GraphEdge。在

相关问题 更多 >