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 : from gi.repository import Gtk In : s = Gtk.StyleContext.new() In : _, fg = s.lookup_color('fg_color') In : fg Out: Gdk.RGBA(red=0.854902, green=0.854902, blue=0.854902, alpha=1.000000) In : sum(fg) Out: 3.564705882352941 In : _, bg = s.lookup_color('bg_color') In : bg Out: Gdk.RGBA(red=0.219608, green=0.219608, blue=0.219608, alpha=1.000000) In : sum(bg) Out: 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.
With the Mint-Y-Dark theme, shown here, the links were set to deeppink.
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.