Kivy:实时更新小部件的颜色

Posted

技术标签:

【中文标题】Kivy:实时更新小部件的颜色【英文标题】:Kivy: Updating colour of widgets in real time 【发布时间】:2014-10-06 04:45:33 【问题描述】:

我发现了这个类似的问题:

How do I change the color of my widget in Kivy at run time?

我正在使用类似的方法来尝试在拖动和移动小部件时更改它们的颜色。


class GraphNode(Widget):
    r = NumericProperty(1.0)

def __init__(self, **kwargs):
    self.size= [50,50]
    self.pos = [175,125]
    super(GraphNode, self).__init__(**kwargs)

def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
        if touch.grab_current == None:
            self.r = 0.6
            touch.grab(self)             
            return True                
    return super(GraphNode, self).on_touch_down(touch)



def on_touch_move(self, touch):
    if touch.grab_current is self:
        self.pos=[touch.x-25,touch.y-25]
    # now we only handle moves which we have grabbed


def on_touch_up(self, touch):
    if touch.grab_current is self:
        touch.ungrab(self)
        self.r = 1.0
        # and finish up here


def onTouchMove(self, touch):
    if self.collide_point(touch.x, touch.y):
        self.pos=[touch.x-25, touch.y-25]
pass

我正在尝试使用此 (kv) 文件更新数字属性以更改颜色:

#:kivy 1.0.9

<GraphInterface>:
    node: graph_node

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

<GraphApp>:
    canvas:

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

<GraphEdge>:
    size: 10, 10
    canvas:

但是,当我抓住它们时颜色不会改变。如果我不在 on_touch_drop() 方法中更改颜色,那么我可以使用新颜色生成节点。知道如何解决这个问题吗?

【问题讨论】:

【参考方案1】:

看起来您的代码可能运行良好,但 Color 指令在所有其他内容之后,因此根本不会影响任何内容。你的意思是把它放在椭圆之前吗?

【讨论】:

我仍然不完全理解所有这些 Kivy 的东西,但这已经解决了我的问题。谢谢!

以上是关于Kivy:实时更新小部件的颜色的主要内容,如果未能解决你的问题,请参考以下文章

在 kivy (python) 中更新小部件

更改 Kivy 小部件部分文本的颜色

Kivy 更改标签小部件来自另一个类的文本

更新另一个类中的 kivy 标签文本

如何使用绑定动态更新 Kivy Label 的文本属性

从 Kivy 的另一个屏幕更改小部件