Skip to content
Advertisement

Using hex color code from py file in kv file

I am making this program that deals with a lot of colors and it gives the user the freedom to change many of them. In one part of my program I use markup for one of my labels and and I realized something about the ‘color’ tag.

When my program starts I want my label to follow the theme but I get this warning when trying to set the color to the theme and it does not show the color correctly:

[WARNING] [ColorParser ] Invalid color format for 'app.hex_txt_color'

I don’t know how to have the hex code that is inside my py file work in the kv file. How can I solve this? My Code:

from kivy.lang import Builder
from kivy.utils import get_hex_from_color
from kivy.app import App


class Example(App):
    txt_color = [1, 0, 0, 1]
    hex_txt_color = get_hex_from_color(txt_color)[:-2]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print(self.hex_txt_color)
        self.kv = Builder.load_string('''
Label:
    markup: True
    text: "[color=app.hex_txt_color]I am red[/color] but not this!"
    ''')

    def build(self):
        return self.kv


if __name__ == "__main__":
    Example().run()

Advertisement

Answer

loadString interprets the entire value of text as a string when enclosed by quotes. In order to make it interpret app.hex_txt_color as a variable you can concatenate the variable to the string. As an example:

text: "[color="+ app.hex_txt_color +"]I am red[/color] but not this!"

You can use python code like:

text: "[color={}]I am red[/color] but not this!".format(app.hex_txt_color)
Advertisement