Search code examples
pythonpython-3.xgtk3

Gtk3 Python Widget Background Image


I'm using Python 3.4 with Gtk 3.18. I've been able to figure out how to implement a background image via CSS for a widget (a Gtk.Box in my case). However, I want to be able to dynamically change that background image to one that the user specifies. How can that be done?

The portion of the css file currently being used for the box's background.

.backImagePitPass {
    background-image: url('../software/resources/PitPass.png');
    background-size: contain;
    background-position: left top;
    background-repeat: no-repeat;
    border: 1px solid black;
    outline-style: solid;
}

Implementing the style sheet for the app.

def _initStyles(self):
    css_provider = Gtk.CssProvider()
    css_provider.load_from_path('ui/main/gtk-widgets.css')

    Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
        css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)

I tried this as a test, but the box and its contents don't even display.

context = self._boxPreview.get_style_context()
css_provider = Gtk.CssProvider()
css_provider.load_from_data(b'''
    .backImagePitPass {
        background-image: url('../software/resources//PitPass2.png');
        background-size: contain;
        background-position: left top;
        border: 1px solid black;
        }
        ''')

context.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)

Solution

  • After doing more searching, I found a solution here Setting Selected property of Row in TreeView dynamically in Gtk3 (python) that pointed me to a workable solution.