Search code examples
pythonwidgetkivybackground-colorhsv

Can I use HSV colors inside a background_color parameter in python/kivy?


I want to use HSV to define some Widget colors, I can do it easily the 'Color' module as in:

Color((1, 0, 0), mode = 'hsv')

But my question is, sometimes you want to be faster and more specific so is there a way to do the same or similar with the background_color parameter? Almost needless to say I've tried and failed on this:

my_hsv_color = Color((0.5, 1, 0.6), mode='hsv')
my_button = Button(background_color = my_hsv_color)

Solution

  • Color is a class or better said, the thing that you pass to background_color is an instance of Color (object). The background_color requires a list/tuple or something else that's iterable.

    Color i.e. class has such properties right here and since Kivy works with rgba in interval of 0.0 - 1.0, you need to feed the property with rgb or rgba.

    from kivy.lang import Builder
    from kivy.base import runTouchApp
    from kivy.uix.boxlayout import BoxLayout
    Builder.load_string('''
    #:import Color kivy.graphics.Color
    <Test>:
        Button:
            background_color: tuple(Color(0.5, 1, 0.6, mode='hsv').rgba)
    ''')
    class Test(BoxLayout): pass
    runTouchApp(Test())
    

    I even think you can use this kind of unpacking in Python 3:

    background_color: *Color(0.5, 1, 0.6, mode='hsv').rgba