在 kv 文件中使用 py 文件中的十六进制颜色代码

Using hex color code from py file in kv file

我正在制作这个处理很多颜色的程序,它让用户可以自由地改变其中的许多颜色。在我的程序的一部分中,我为我的一个标签使用了标记,并且我意识到了一些关于 'color' 标签的事情。

当我的程序启动时,我希望我的标签遵循主题,但是当我尝试将颜色设置为主题时收到此警告并且它没有正确显示颜色:

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

我不知道如何让我的 py 文件中的十六进制代码在 kv 文件中工作。我该如何解决这个问题?我的代码:

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()

我想你可以试试这个 我想你忘了使用 F-string 并得到了错误的值

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(f'''
Label:
    markup: True
    text: "[color={self.hex_txt_color}]I am red[/color] but not this!"
    ''')

    def build(self):
        return self.kv


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

loadStringtext 的整个值解释为用引号引起来的字符串。为了使其将 app.hex_txt_color 解释为变量,您可以将变量连接到字符串。例如:

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

您可以使用 python 代码,例如:

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