PyGObject GTK3 小部件颜色不起作用

PyGObject GTK3 widget color does not work

我最近开始使用 pygtk/PyGObject 并一直在尝试应用或更改背景颜色或一个简单的按钮或任何其他小部件,使用从此处的 QA 之一获得的以下代码行。

self.button.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.0, 1.0, 0.0, 1.0))

但这似乎并不适用或不起作用。

完整的示例测试程序在这里。

#!/usr/bin/env python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


class MyWIndow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.button = Gtk.Button(label="Click")
        self.button.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.0, 1.0, 0.0, 1.0))
        self.button.connect("clicked", self.on_button_clicked)
        self.add(self.button)

    def on_button_clicked(self, widget):
        Gtk.main_quit()


win = MyWIndow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

有什么我遗漏的吗? 提前致谢。

此方法用于 Gtk+ 2.0,似乎也用于 Gtk+ 3.0 的第一个版本,但在 3.16 版中已弃用:

来自Python API

New in version 3.0.

Deprecated since version 3.16: This function is not useful in the context of CSS-based rendering. If you wish to change the way a widget renders its background you should use a custom CSS style, through an application-specific Gtk.StyleProvider and a CSS style class. You can also override the default drawing of a widget through the Gtk.Widget ::draw signal, and use Cairo to draw a specific color, regardless of the CSS style.

有关 Migration to CSS 的更多信息。

您的示例使用预定义 css 类(建议和破坏性操作):

#!/usr/bin/env python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


class MyWIndow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)

        self.button = Gtk.Button(label="Click")
        self.button.get_style_context().add_class("suggested-action")
        self.button.connect("clicked", self.on_button_clicked)
        self.add(self.button)

    def on_button_clicked(self, widget):
        self.button.get_style_context().add_class("destructive-action")


win = MyWIndow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()