gtk3+ 和 python rgba 转换为十六进制

kar*_*rim 1 python pygtk python-3.x gtk3

我使用gtk3我发现它使用RGBA用于表现颜色,但(红,绿,蓝,alpha)非整间0-255但之间浮动点数0-1.0,所以我不知道如何从转换rgba 到十六进制,反之亦然

我试过这段代码,但它似乎不起作用:

def convert_to_hex(rgba_color) :
red = str(hex(int(rgba_color.red*255)))[2:].capitalize()
green = str(hex(int(rgba_color.green*255)))[2:].capitalize()
blue = str(hex(int(rgba_color.blue*255)))[2:].capitalize()

return '0x' + red + green + blue
Run Code Online (Sandbox Code Playgroud)

M4r*_*ini 6

假设问题是当数字只有 1 位数字时,数字应该有前导零。这是一个解决方案。

def convert_to_hex(rgba_color) :
    red = int(rgba_color.red*255)
    green = int(rgba_color.green*255)
    blue = int(rgba_color.blue*255)
    return '0x{r:02x}{g:02x}{b:02x}'.format(r=red,g=green,b=blue)
Run Code Online (Sandbox Code Playgroud)