CSS 样式未应用于 Gtk 小部件

CSS styles are not being applied on a Gtk widget

Whosebug 上的另一位用户在使用 CSS 设计他的 Gtk 应用程序时遇到了一些问题。我找到了部分问题的解决方案,但对于一个我什么都不知道。原来的post是用C代码的,但是下面的PythonMinimal Reproducible Example有同样的问题:

#!/usr/bin/python3
#-*-coding: utf-8-*-

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

win = Gtk.Window()
win.connect("destroy", lambda _: Gtk.main_quit())
box = Gtk.VBox()
win.add(box)
button = Gtk.Button("Button")
prov = Gtk.CssProvider.new()
prov.load_from_data("""
button {
    color: red;
    background-color: green;
    margin: 30px;
}
""".encode())
ctx = win.get_style_context()
ctx.add_provider(prov, 1000)
box.add(button)
win.show_all()
Gtk.main()

问题是,没有显示边距,也没有显示字体和背景颜色,而在本例中却正确显示:

#!/usr/bin/python3
#-*-coding: utf-8-*-

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

win = Gtk.Window()
win.connect("destroy", lambda _: Gtk.main_quit())
box = Gtk.VBox()
win.add(box)
button = Gtk.Button("Button")
prov = Gtk.CssProvider.new()
prov.load_from_data("""
* {
    color: red;
    background-color: green;
    margin: 30px;
}
""".encode())
ctx = button.get_style_context()
ctx.add_provider(prov, 1000)
box.add(button)
win.show_all()
Gtk.main()

这让我得出结论,select 或 button 不知何故没有达到我想要和期望的效果。为什么 selector 是错误的,哪个是正确的 selector 到 select 按钮?

请注意 gtk_style_context_add_provider() 的文档内容:

Note that a style provider added by this function only affects the style of the widget to which context belongs. If you want to affect the style of all widgets, use gtk_style_context_add_provider_for_screen().

样式仅适用于该小部件,不适用于该小部件及其子项。设置 GTK 应用程序样式的首选方法是为整个应用程序创建一个样式表,然后使用 gtk_style_context_add_class 将样式 类 添加到各个小部件。