简体   繁体   English

在使用 Glade 创建的 Python GTK3 程序中导入 CSS 文件

[英]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.我尝试将suggested-action添加为 class,但按钮仍然是灰色的。 So i want to write my own css file with my own style information.所以我想用我自己的样式信息编写我自己的 css 文件。 I'm using glade to create the glade file and build the gui from that in my main.py.我正在使用 glade 来创建 glade 文件并在我的 main.py 中构建 gui。

Where do I have to put the css file in my source tree and how do I import it?我必须将 css 文件放在我的源代码树中的什么位置以及如何导入它?

There is a HowDoI guide here: https://wiki.gnome.org/HowDoI/CustomStyle这里有一个 HowDoI 指南: https://wiki.gnome.org/HowDoI/CustomStyle

In Python you have to first import Gdk:在 Python 中,您必须首先导入 Gdk:

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

Then you can set the CSS at startup:然后您可以在启动时设置 CSS:

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.注意:当然, background-color属性仅在没有背景图像集填充背景时才有效。 The Adwaita theme sets the background-image on buttons. Adwaita 主题在按钮上设置背景图像。 So remove it:所以删除它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM