Search code examples
pythongtk3pygobject

Button not getting styled in PyGI


I am trying to create a button that is red instead of the default colour. I am applying the style through a CssProvider() but the button's colour does not change. What am I doing wrong ?

Here is the code:

from gi.repository import Gtk, Gdk

CSS = """
GtkButton {
    background-color: red;
}
"""

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Theme")
        self.resize(640, 480)
        self.connect("delete-event", Gtk.main_quit)

        cssprovider = Gtk.CssProvider()
        cssprovider.load_from_data(CSS)

        screen = Gdk.Screen.get_default()
        sc = Gtk.StyleContext()
        sc.add_provider_for_screen(screen, cssprovider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        btn = Gtk.Button(label="Click")
        self.add(btn)

win = MyWindow()
win.show_all()
Gtk.main()

Solution

  • The problem is background-image takes precedence over background-color, the former is most likely already set in the theme (button gradient). You can force a complete replacement of the background using the "background" property or by using "background-color" along with un-setting "background-image":

    GtkButton {
        background: red;
    }
    

    or:

    GtkButton {
        background-image: none;
        background-color: red;
    }
    

    See: https://bugzilla.gnome.org/show_bug.cgi?id=728027