Search code examples
pythonbuttongtk

How do I highlight a button in Gtk?


I notice that in many of the system dialogs on Ubuntu, there is a button (usually Open, Save, etc.) that is a different color than normal. But also, these buttons' colors change with the system theme; in Adwaita, they are blue. In Yaru, they are green. So no, I'm not asking how to set the background of a button to a specific color.

My question is, how do I make a button highlighted according to the current theme without having to manually set the color? Is it even possible to do this in Python? I've looked in Gtk, Gtk.Dialog, GtkSource, Gdk, GLib, and Pango, and found nothing. Ideally, the solution would work for any button, not just a button in a dialog.


Solution

  • You can use StyleContext to highlight widget. Gtk widgets such as Gtk.Button that inherits from Gtk.Widget can obtain its StyleContext by calling get_style_context. You can then add class(a str) to the context by calling add_class on it. gtk itself provides suggested-action and destructive-action. You can also define your own style class.

    Below is an example using suggested aciton.

    import gi
    
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk
    
    win = Gtk.Window()
    
    box = Gtk.Box()
    button1 = Gtk.Button(label="button1")
    button2 = Gtk.Button(label="button2")
    box.pack_start(button1, True, True, 0)
    box.pack_start(button2, True, True, 0)
    
    button1_style_context = button1.get_style_context()
    button1_style_context.add_class('suggested-action')
    
    win.add(box)
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()
    

    enter image description here