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

1,072 views
Skip to first unread message

ivan limonov

unread,
May 22, 2015, 3:03:17 PM5/22/15
to kivy-...@googlegroups.com

I'm having trouble changing the color of a simple widget in Kivy. I can set the color when I create the widget, but I can't change it afterwards.

Here is the simple layout definition file test.kv. It defines a circle where the color (actually just the r, from rgba), position and size are all linked to variables in the widget class.

<CircleWidget>:
    canvas.before:
        Color:
            rgb: self.rgb
        Rectangle:
            pos: self.pos
            size: self.size
class CircleWidget(Widget):
    def __init__(s, **kwargs):
        s.size= [50,50]
        s.pos = [100,50]
        s.rgb = [1,0,0]
        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.rgb = [0,0,1]                       # <---- This does nothing!

class TestApp(App):
    def build(s):
        parent = Widget()
        w = CircleWidget()
        parent.add_widget(w)
        return parent

if __name__ == '__main__':
    TestApp().run()


Can anyone see the problem?

Kovak

unread,
May 22, 2015, 3:23:08 PM5/22/15
to kivy-...@googlegroups.com
It looks like rgb is a regular list and not a ListProperty, regular python data types will not have event dispatching.

ivan limonov

unread,
May 22, 2015, 3:32:31 PM5/22/15
to kivy-...@googlegroups.com
Yes, I have already noticed, but how do I change the color during operation?

пятница, 22 мая 2015 г., 23:23:08 UTC+4 пользователь Kovak написал:

Kovak

unread,
May 22, 2015, 3:35:31 PM5/22/15
to kivy-...@googlegroups.com
If you defined
class CircleWidget(Widget):
    rgb
= ListProperty([1., 1., 1.)]


   
def __init__(s, **kwargs):
        s
.size= [50,50]
        s
.pos = [100,50]
        s
.rgb = [1,0,0]
       
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
.rgb = [0,0,1]        


Your rgb would now be observed and it should automatically update the canvas instruction that watches it when it changes.

ivan limonov

unread,
May 22, 2015, 5:03:55 PM5/22/15
to kivy-...@googlegroups.com
Thank you, it works now, I tried to do likewise, but he not worked

пятница, 22 мая 2015 г., 23:35:31 UTC+4 пользователь Kovak написал:
Reply all
Reply to author
Forward
0 new messages