FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 4.6 | Next Entry >>

4.6. How do I change the colour of a widget (or how do I get a GdkColor)?

Important! See also FAQ 4.16.

There is some confusion about GdkColor and how it is created. There are both the GdkColor() class and colour_alloc() that seem to do the right thing, but they are both duds (as far as I can tell).

The right way of creating a colour is getting the colormap from the widget and using it to allocate a new colour using the GtkColorMap's alloc method:

 e = gtk.Entry()
 map = e.get_colormap()
 colour = map.alloc_color("red") # light red
This way you end up with a red GdkColor in the variable colour. Apart from the X11 rgb.txt names, you can also use hex triplets:

 colour = map.alloc_color("#FF9999") # light red
See FAQ 4.8 for more information on alloc_color.

The next step is understanding how to manipulate GtkStyle's colour attributes, which are actually dictionaries: each attribute maps a number of different gtk constants that indicate states:

So, to change the default border of our entry above to red:

 style = e.get_style().copy()
 style.bg[gtk.STATE_NORMAL] = colour
 e.set_style(style)
Final hint: the default colour for a GtkEntry background is gray84.

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org