简体   繁体   中英

Kivy: How to change a widget's background color at runtime?

I want to create rows of widgets that contains different column widgets, some of those are textLabels. What I want to do is to be able to change the background color of a row during runtime. To do this I use horizontal box layouts as rows. Is it possible to change the background color of this layouts during runtime?

All the solutions I've found are to change the background color at the moment they are created but doesn't work during runtime.

kivy.uix.boxlayout.BoxLayout(orientation="horizontal", size_hint_y=None)

This are the widgets I am currently working with but I am open to use another type of widget for this.

Some widgets inside the layout block the layout's background, those doesn't have to change color but it wouldn't matter either way, I am interested in changing the background in all the textLabels from a row at least.

You mention textLabel (I assume you mean Label ). You can easily modify the background color of a Label by defining a custom Label , let's call it MyLabel as:

class MyLabel(Label):
    rgba = ListProperty([0.5, 0.5, 0.5, 1]) # will be used as background color

This defines a rgba property of MyLabel that can be referenced in a kv file as:

<MyLabel>:
    canvas.before:
        Color:
            rgba: self.rgba
        Rectangle:
            pos: self.pos
            size: self.size

Then the background color of an instance of MyLabel (call it mylab ) can be changed with:

mylab.rgba = [1, 0, 0, 1] # or any other rgba

If you want to change the background color of a row of MyLabel widgets, just do the above in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM