Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the background color of a widget in GTK and Python?

I want to get the normal background color of a widget (a GtkHeaderBar, in this case). I'm currently using

style = self.get_titlebar().get_style_context()

to get the style, and

color = style.get_property("background-color", Gtk.StateFlags.NORMAL)

to get the background color associated to that style.

However it returns a Gkd.RGBA object with the following properties:

Gdk.RGBA(red=0.000000, green=0.000000, blue=0.000000, alpha=0.000000)

But if I open GTK Inspector, select the HeaderBar, and goes to the style properties, it shows

background-color | rgb(57,63,63) | gtk-contained-dark.css:1568.29

What do I have to do to get these same values?

Edit:

I am experimenting with the GtkStyleContext.render_background(), but I'm having no success:

surfc = Cairo.ImageSurface (Cairo.FORMAT_ARGB32, 10, 10)
contx = Cairo.Context(surfc)
style = self.get_titlebar().get_style_context()
backg = Gtk.render_background(style, contx, 10, 10, 10, 10)
surfc.write_to_png("test.png")

The resulting file test.png is a rgba(0, 0, 0, 0) image.

like image 293
user3474251 Avatar asked Jul 25 '15 15:07

user3474251


1 Answers

You should have a look at modifying the background-color with css. There is a very good documentation of it. It can be used with python with

css_provider = Gtk.CssProvider()
css_provider.load_from_path('application.css')
Gtk.StyleContext.add_provider_for_screen(
    Gdk.Screen.get_default(),
    css_provider,
    Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)

and a css file like:

GtkHeaderbar {
    background-color:@theme_bg_color;
}

EDIT: As you commented you do not want to modify the background color but retrieve the value of it. You can do widget.get_style_context().get_background_color() and it will return something like Gdk.RGBA(red=0.913725, green=0.913725, blue=0.913725, alpha=1.000000).

However, you should note that get_background_color() is deprecated since there is not one background color. Some widget use a gradient as a background so it is not the best solution to use this method. See the documentation for reference.

like image 115
elya5 Avatar answered Sep 21 '22 02:09

elya5