2013-10-09 33 views
0

我已經插入了一個gtk.ColorButton(),但是當我檢索值(get_color)時,我得到一個12位十六進制字符串(對於某些顏色)。 問題是我需要它給我只有6位數字。ColorButton給出12位十六進制字符串而不是6

這裏有一個片段:

import pygtk 
pygtk.require("2.0") 

import gtk 

class TestColorButton(object): 

    def __init__(self): 
     self.win = gtk.Window() 
     self.colorbutton = gtk.ColorButton() 
     container = gtk.VBox() 
     Button = gtk.Button("Get color") 
     Button.connect("released", self.get_selected_color) 
     container.pack_start(self.colorbutton) 
     container.pack_start(Button) 
     self.win.add(container) 
     self.win.show_all() 

    def get_selected_color(self, widget): 
     print self.colorbutton.get_color() 

if __name__ == "__main__": 
    TestColorButton() 
    gtk.main() 

我不知道是不是唯一的解決辦法是嘗試將12位十六進制字符串轉換爲一個6位的一個(儘管我會丟失信息)。由於python中沒有可以使用12位數的顏色,所以我非常想知道這是什麼...

有趣的是,在彈出的窗口中,我可以看到一個6位數的十六進制字符串。也許,如果我能get_childs該窗口,直到我找到它...但它看起來很複雜的一件簡單的事......

+0

其實這應該返回一個對象gtk.gdk.Color http://www.pygtk.org/docs/pygtk/ class-gdkcolor.html 而不是一個字符串,從返回的對象中,您可以讀取文檔中所述的值 – gianmt

回答

0

我們的目標是獲得一個6位數的十六進制字符串,用於選擇一種顏色。一個臨時解決方案是採用每個四位數顏色的前兩位數字(#rrrrggggbbbb給出#rrggbb)。 我選擇的是 將每四位數的顏色轉換爲16位整數(0000-FFFF爲0-65535) 將其重新調整爲8位(0-65535至0-255) 將其轉換回十六進制字符串現在兩個字符,而不是四個)

我不認爲這是真的聰明,但至少它給了我近似我想要的顏色...

的片段更新:

import pygtk 
pygtk.require("2.0") 

import gtk 

class TestColorButton(object): 

    def __init__(self): 
     self.win = gtk.Window() 
     self.colorbutton = gtk.ColorButton() 
     container = gtk.VBox() 
     Button = gtk.Button("Get color") 
     Button.connect("released", self.get_selected_color) 
     container.pack_start(self.colorbutton) 
     container.pack_start(Button) 
     self.win.add(container) 
     self.win.show_all() 

    def get_selected_color(self, widget): 
     a = self.colorbutton.get_color() 
     print a 
     self.gdk_to_hex(a) 

    def gdk_to_hex(self, gdk_color): 
     colors = gdk_color.to_string() 
     a = "#"+"".join([self.fourtotwohexdigit(i) for i in (colors[1:5], colors[5:9], colors[9:13])]) 
     print a 

    def fourtotwohexdigit(self, hexa): 
     return hex(int(int(hexa,16)*255/65535))[2:]  

if __name__ == "__main__": 
    TestColorButton() 
    gtk.main() 
-1

當你從

color = self.colorbutton.get_color() 

對象gtk.gdk.Color你可以得到與

color.to_string() 

的12位#fcfce9e94f4f字符串的字符串表示含有每種顏色的十六進制形式的4位,在這種情況下紅色= 64764,綠色= 59881,藍色= 20303

red=64764 -> fcfc 
green=59881 -> e9e9 
blue=20303 -> 4f4f 

,你也可以從gtk.gdk.Color打印個別顏色如

color.red 
color.green 
color.blue 

,或者如果您在十進制值的範圍更喜歡0.0 - 1.0

color.red_float 
color.green_float 
color.blue_float 
1

這是一個使用一個小FUNC gdk.color的to_floats函數獲得[0..1]範圍內的rgb三連音,然後將其轉換爲適合2位十六進制的[0..255]。

def gdk_to_hex(gdk_color): 
    colors = gdk_color.to_floats() 
    return "#" + "".join(["%02x" % (color * 255) for color in colors]) 
+0

gtk.gdk.color對象我沒有任何to_floats()方法。但是我使用部分代碼更新了我的臨時更正的代碼。 – bserra

+0

http://lazka.github.io/pgi-docs/api/Gdk_3.0/structs/Color.html?highlight=to_floats#Gdk.Color.to_floats - 沒有提及版本,所以可能已經引入gtk3 –

相關問題