Question

I am trying to set the green of a rectangle equal to the red of a rectangle in kivy.

Here is what I tried:

<Road>:
    id:label
    canvas:
        Color:
            r: random.randint(11,14)*0.04
            g: r
            b:random.randint(14,15)*0.04
            a:1

        Rectangle:
            pos: self.pos
            size: self.size

Following this,I get the error:

 NameError: name 'r' is not defined

I have tried using kivy.properties but they appear to only remain constant and I have to call this widget several times (each with a different colour).

Was it helpful?

Solution

Here's a way to do it by creating and using a property of the Road.

<Road>:
    id:label
    random_colours: [random.randint(11,14)*0.04, random.randint(14,15)*0.4]
    canvas:
        Color:
            r: root.random_colours[0]
            g: root.random_colours[0]
            b: root.random_colours[1]
            a: 1

        Rectangle:
            pos: self.pos
            size: self.size

You'll probably find something like this to be most convenient when working with vertex instructions like this, as in kv you can't easily refer to their other attributes, but you can easily work with widget properties.

Edit: as you comment, this doesn't quite work. The problem seems to be that the dynamic property creation happens too late so it doesn't exist when the Color tries to access it. This may be a bug.

You can fix it by declaring the property in the normal way with your Road's normal definition:

class Road(Widget):
    random_colours = ListProperty([0.1, 0.1])

It doesn't matter what you set as the default value, as the kv definition still overrides it and the rectangle will update appropriately.

You'll currently always get the same colour (almost), because kivy's rgba takes values in the 0-1 range, but that's easily fixed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top