Holzroller
Holzroller

Reputation: 89

kivy: press button -> change color of a label

in the kv File I added a Label and changed its color:

Label:
    id: ampel_rot
    canvas.before:
    Color:
        rgba: 1, 0, 0, 0.3
    Ellipse:
        size: self.size

My aim is to create some kind of a traffic light, so that the user of the GUI has some kind of visual feedback over a process. To do so, I have to change the color of this Label during runtime. But however in this case I dont understand the connection between the kv file and the main.py.

I tried something like:

self.ids.ampel_rot.canvas.before.Color.rgba(1, 0, 0, 1)

Which of course doesnt work.

So how do I change the Labels Color in the main.py? Can somebody enlighten me, please? Thanks alot!

Upvotes: 0

Views: 1460

Answers (1)

inclement
inclement

Reputation: 29460

The easiest way is to use an intermediary property

from kivy.properties import ListProperty
class ColourLabel(Label):
    ellipse_colour = ListProperty([1, 0, 0, 1])

Then in the kv

<ColourLabel>:
    canvas.before:
        Color:
            rgba: self.ellipse_colour
        Ellipse:
            size: self.size
            pos: self.pos

Note that I added the pos to Ellipse, which is presumably necessary in general.

You could then add a ColourLabel to the same rule that your original example was in, and the modification code becomes self.ids.ampel_rot.ellipse_colour = (1, 1, 1, 1) etc.

Upvotes: 2

Related Questions