How to make buttons different colours in Python GTK3 (using gi)?

前端 未结 3 812
盖世英雄少女心
盖世英雄少女心 2021-01-01 02:53

My latest head-scratcher is to build a silly little app in Python3 using GTK3, with colours other than fog-grey on the buttons. I have spent the last few days googling for h

3条回答
  •  执念已碎
    2021-01-01 02:57

    Even though this is a old question, I'd like to add an answer referring to question 3 just for the reference.

    GTK3 adds the concept of style classes. So to get different colored buttons you can address them directly be name or add a style class to its context. All this is explained in the links mike provided in his answer.

    Here is a simple example how to use style classes to highlight invalid text in entries:

    from gi.repository import Gtk, Gdk
    
    class MainWindow(Gtk.Window):
    
        def __init__(self):
            super().__init__()
            vbox = Gtk.Box(spacing=10,orientation=Gtk.Orientation.VERTICAL)
            self.add(vbox)
    
            self.entries = [ Gtk.Entry() for i in range(3) ]
            for e in self.entries:
                vbox.pack_start(e, True, True, 0)
                e.connect("changed", self.on_entry_changed)
                e.set_text('123')
    
            button=Gtk.Button('ok',name='ok-button')
            vbox.pack_end(button,True,True,0)
    
    
        def on_entry_changed(self,entry):
            ctx = entry.get_style_context()
            if not entry.get_text().isnumeric():
                ctx.add_class('invalid')
            else:
                ctx.remove_class('invalid')
    
    
    cssProvider = Gtk.CssProvider()
    cssProvider.load_from_path('style.css')
    screen = Gdk.Screen.get_default()
    styleContext = Gtk.StyleContext()
    styleContext.add_provider_for_screen(screen, cssProvider,
                                         Gtk.STYLE_PROVIDER_PRIORITY_USER)
    
    window = MainWindow()
    window.connect("delete-event", Gtk.main_quit)
    window.show_all()
    Gtk.main()
    

    with style.css:

    GtkEntry.invalid {
        background-color: #ffaaaa;
        background: #ffaaaa;
    }
    
    GtkButton#ok-button {
        background-color: green;
        background: green;
    }
    

提交回复
热议问题