[英]GTK and python. How convert RGBA to HEX?
# a colorbutton (which opens a dialogue window in
# which we choose a color)
self.button_err_bg = Gtk.ColorButton()
# with a default color (blue, in this instance)
color_bg = Gdk.RGBA()
color_bg.red = 0.5
color_bg.green = 0.4
color_bg.blue = 0.3
color_bg.alpha = 1.0
color_error_background = self.button_err_bg.set_rgba(color_bg)
# choosing a color in the dialogue window emits a signal
self.button_err_bg.connect("color-set", self.on_color_fg_error_chosen)
和方法
def on_color_fg_error_chosen(self, user_data):
print("You chose the color: " + self.button_err_bg.get_rgba().to_string())
color_rgba = self.button.get_rgba().to_string()
color_rgba_bracket = color_rgba[color_rgba.find("(")+1:color_rgba.find(")")]
color_hex = '#{:02x}{:02x}{:02x}'.format(color_rgba_bracket)
print(color_hex)
color_hex:color_hex = '#{:02x}{:02x}{:02x}'.format(color_rgba_bracket) ValueError: 未知格式代码 'x' 用于 object 类型为 'str'
根据您的代码,我将假设self.button.get_rgba()
返回一个元组。
由于您将假定的元组转换为字符串(出于某种原因),格式失败,因为如您的错误所示,它不知道如何将字符串转换为十六进制。 此外,即使它确实具有字符串的x
格式,它也会因IndexError: tuple index out of range
而失败,因为它需要 3 个项目而你只传递了 1 个。
如果您完全跳过字符串转换并解压缩元组,您应该得到正确的格式:
def on_color_fg_error_chosen(self, user_data):
print("You chose the color: " + self.button_err_bg.get_rgba().to_string())
color_rgba = self.button.get_rgba()
color_hex = '#{:02x}{:02x}{:02x}'.format(*color_rgba)
print(color_hex)
使用一个基本示例:
>>> color_rgba = (12, 28, 200, 28) # R, G, B, Alpha
>>> '#{:02x}{:02x}{:02x}'.format(*color_rgba) # 4th item is ignored because only looking for 3 items
'#0c1cc8'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.