Search code examples
csspython-2.7windows-10gtk3msys2

How to change the background-color of a Gtk.InfoBar to yellow?


The default background color seems to be blue (from the Adwaita theme), even if I set the type of message to Warning. I prefer using CSS.

example.py:

# coding=utf-8

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

w = Gtk.Window()
ib = Gtk.InfoBar()

w.add(ib)
w.connect("delete-event", Gtk.main_quit)

provider = Gtk.CssProvider()
provider.load_from_path("style.css")

w.get_style_context()\
     .add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)

w.show_all()
Gtk.main()

style.css:

infobar {
    background-color: yellow;
}

Screenshot:

Screenshot with the problem

I use Python 2.7.13 and GTK+ 3.22 on Windows 10 with all the updates installed and through MSYS2 with all the updates installed with pacman -Syyu.


Solution

  • From the Python Gtk API:

    Gtk.InfoBar has a single CSS node with name infobar. The node may get one of the style classes .info, .warning, .error or .question, depending on the message type.

    By default, Gtk.InfoBar message type is Gtk.MessageType.INFO and your style.css file should be, eg.:

    infobar.info {
        background-color: yellow;
    }
    

    This way you can be more specific to the message type your are setting but infobar by itself will also work. The advantage is that you can have custom settings for each message type using infobar.<messagetype>.

    EDIT:

    change the widget that will receive the css class to the Gtk.InfoBar instance:

    ib.get_style_context()\
         .add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
    

    EDIT 2:

    To add a CssProvider (StyleProvider) as a whole to the application you have the Gdk.Screen class method Gdk.Screen.add_provider_for_screen (more info here)

    Changing your code to reflect these changes, you'll have:

    # coding=utf-8
    
    import gi
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk, Gdk
    
    w = Gtk.Window()
    ib = Gtk.InfoBar()
    
    w.add(ib)
    w.connect("delete-event", Gtk.main_quit)
    
    provider = Gtk.CssProvider()
    provider.load_from_path("style.css")
    
    Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default (), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
    
    w.show_all()
    Gtk.main()