Import CSS file in Python GTK3 program created using Glade

≯℡__Kan透↙ 提交于 2020-03-25 18:44:05

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/58389218/import-css-file-in-python-gtk3-program-created-using-glade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!