Search code examples
pygobject

PyGObject, hex color to Gdk.RGBA


i found this code

gdk_rgba_parse ()

which should allow me to do something like

Gdk.RGBA.parse(#7F7F7F)

Error:

 TypeError: unbound method parse() must be called with RGBA instance as first argument   (got str instance instead)

using the RGBA color ( in percent, from 0 to 1 )

Docs:

https://developer.gnome.org/gdk3/stable/gdk3-RGBA-Colors.html#gdk-rgba-parse http://www.crategus.com/books/cl-cffi-gtk/pages/gdk_fun_gdk-rgba-parse.html

But I'm kinda lost, i struggle to translate from C to PyGOBject and understanding the arguments of the function.. any help would be appreciated!


Since i didn't find the right solution, i made this converter:

def hex_to_rgba(value):
    value = value.lstrip('#')
    if len(value) == 3:
        value = ''.join([v*2 for v in list(value)])
    (r1,g1,b1,a1)=tuple(int(value[i:i+2], 16) for i in range(0, 6, 2))+(1,) 
    (r1,g1,b1,a1)=(r1/255.00000,g1/255.00000,b1/255.00000,a1)

    return (r1,g1,b1,a1)

It works..


Solution

  • The function requires an instance of a GdkRGBA struct:

    gboolean
    gdk_rgba_parse (GdkRGBA *rgba,
                    const gchar *spec);
    

    This translates to Python as a method on a Gdk.RGBA instance which mutates the structs contents:

    color = Gdk.RGBA()
    color.parse('#7F7F7F')
    color.to_string()  # 'rgb(127,127,127)'
    

    It's not a very nice API for Python but every once in a while you have to deal with these kind of things with introspection based bindings. lazka's docs should be more helpful than the C ones:

    http://lazka.github.io/pgi-docs/#Gdk-3.0/structs/RGBA.html#Gdk.RGBA.parse