Detecting Theme Brightness in GtkΒΆ

In a Gtk application, I wanted to change certain settings based on the theme brighness, to not have clashing colours and make text more readable.

PyGObject does not contain an easy way to check to theme brightness, but one can compare the back- and foreground colours of the theme (ie. text colour versus its background).

In [1]: from gi.repository import Gtk

In [2]: s =

In [3]: _, fg = s.lookup_color('fg_color')

In [4]: fg
Out[4]: Gdk.RGBA(red=0.854902, green=0.854902, blue=0.854902, alpha=1.000000)

In [5]: sum(fg)
Out[5]: 3.564705882352941

In [6]: _, bg = s.lookup_color('bg_color')

In [7]: bg
Out[7]: Gdk.RGBA(red=0.219608, green=0.219608, blue=0.219608, alpha=1.000000)

In [8]: sum(bg)
Out[8]: 1.6588235294117646

We can then compare the sums to figure out which is brighter. Brighter colours are closer to white (0, 0, 0) and have a lesser value. Darker colours are closer to black (255, 255, 255), and have a higher value.

if sum(fg) < sum(bg):
    links = 'deeppink'

In the screenshot below, which uses the Mint-Y theme, the links were set to a default blue colour.

A screenshot of a Gtk application on Linux Mint 2020 with the light Mint-Y theme, showing blue links, as it historically was.

With the Mint-Y-Dark theme, shown here, the links were set to deeppink.

A screenshot of a Gtk application on Linux Mint 2020 with the dark Mint-Y-Dark theme, showing pink links, contrasting better with the dark grey background, thus more readable.

Note that Gtk loads Style preferences only at startup, and that with this method, the application needs to be relaunched when the theme is changed.