Get GTK+ theme colors with python and GObject introspection
Asked Answered
R

1

7

With introduction of GObject introspection the way to access theme colors through widget.get_style() method is gone. I am interested on how to get theme colors when GTK+ is used through GOBject introspection. The solution should preferably work with both versions (2 and 3) but a solution for each of these is acceptable as well.

Romberg answered 28/6, 2011 at 0:54 Comment(0)
E
6

I'm not sure how to get it from gtk+-2.0, unless your using a pure gtk+-2.0 environment, in which case I think the old GtkStyle methods work. for example, assuming your not running a Gtk-3.0 environment like gnome-shell

import gi
# make sure you use gtk+-2.0
gi.require_version('Gtk', '2.0')
from gi.repository import Gtk

window = Gtk.Window()

...

style = window.get_style()
print style.lookup_color('fg_color')

I think that should still work under a gtk+-2.0 environment. I don't know for sure as my system is running gnome-shell, and can't easily try this out.

However this method has been deprecated and replaced by GtkStyleContext. If I use the above code in a gtk+-3.0 environment like gnome-shell it will run, but does not give me the information I'm after. What I get is

(False, <Gdk.Color(red=0, green=0, blue=0)>)

EDIT: Looking back at this, I think the above is still giving the correct info. The colour for fg_color is not found, as indicated by the first entry in the tuple result, which is False. Also the window must be visible for the colours to be found.

If I want colour information I want to use the new GtkStyleContext, for example

import gi
# make sure you use gtk+-3.0
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

window = Gtk.Window()

...

style_context = window.get_style_context()
print style_context.lookup_color('fg_color')

this will give me some real data, which is telling me the 'fg_color' has been found, due to the first entry in the tuple is True.

(True, <Gdk.Color(red=0.000000, green=0.000000, blue=0.000000, alpha=1.000000)>)

I hope this answers your question.

Ecg answered 17/7, 2011 at 3:13 Comment(3)
Thanks a lot... I've been looking for this so hard.Romberg
where can I reference color names (like fg_color)? Apparently there is no bg_color, or fg_color on my system!Shun
@Shun I can't really answer your question directly. The above should work, but if your system doesn't have these colour definitions, it's not going to work. There was a move to using css to style widgets since gnome-shell. I've looked for definitions, the closest I have come up with is this github.com/GNOME/gtk/blob/…, but I doubt that'll help you. Try asking a questionEcg

© 2022 - 2024 — McMap. All rights reserved.