| FAQ Index - Search - Recent Changes - Everything - Add 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:
- gtk.STATE_NORMAL, the normal state of the widget.
- gtk.STATE_ACTIVE, a clicked button or checkbutton, etc.
- gtk.STATE_INSENSITIVE, when the widget is insensitive (set_sensitive(0))
- gtk.STATE_PRELIGHT, when onmouseovered
- gtk.STATE_SELECTED, when part of the widget is selected (text in a GtkEntry, or a selected radiobutton)
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.
