Standard
Standard

Reputation: 1512

Import CSS file in Python GTK3 program created using Glade

I try to find information about adding a colored button widget. I tried adding suggested-action as class, but the button is still grey. So i want to write my own css file with my own style information. I'm using glade to create the glade file and build the gui from that in my main.py.

Where do I have to put the css file in my source tree and how do I import it?

Upvotes: 1

Views: 2199

Answers (1)

lb90
lb90

Reputation: 958

There is a HowDoI guide here: https://wiki.gnome.org/HowDoI/CustomStyle

In Python you have to first import Gdk:

gi.require_version('Gdk', '3.0')
from gi.repository import Gdk

Then you can set the CSS at startup:

screen = Gdk.Screen.get_default()
provider = Gtk.CssProvider()
provider.load_from_path("/path/to/style.css")
Gtk.StyleContext.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

Here I recommend using an absolute path. If you use relative paths you will get into problems if the working directory is not the directory of the project. For example, if you use relative paths, this will not work:

cd somedirectory
python /home/user/project/main.py
# Error: cannot find style.css

NOTE: of course, the background-color property only works if there is no background-image set filling the background. The Adwaita theme sets the background-image on buttons. So remove it:

button {
  background: none;
  background-color: red;
}

Upvotes: 7

Related Questions