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

前端 未结 3 822
盖世英雄少女心
盖世英雄少女心 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 03:17

    Inspired by @boosth, this is the modified code (wrap the button, and apply the colour to the wrapper - see lines commented with # <----).

    However, while it changes the colour of the event box, the button itself remains the same. So, this is NOT what I was looking for, but so far this is the best answer.

    from gi.repository import Gtk, Gdk
    
    class ButtonWindow(Gtk.Window):
    
        def __init__(self):
            super().__init__(title="Button Test")
            self.set_border_width(10)
    
            hbox = Gtk.Box(spacing=10)
            self.add(hbox)
            hbox.set_homogeneous(False)
    
            # make the button
            button = Gtk.Button('Test Button')
            buttonWrapper = Gtk.EventBox()                  # <----
            buttonWrapper.add(button)                       # <----
            hbox.pack_start(buttonWrapper, True, True, 0)   # <----
    
            # change the colour of the wrapper ....
            buttonWrapper.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse("green"))
            buttonWrapper.modify_bg(Gtk.StateType.ACTIVE, Gdk.color_parse("red"))
            buttonWrapper.modify_bg(Gtk.StateType.SELECTED, Gdk.color_parse("blue"))
    
    
    window = ButtonWindow()        
    window.connect("delete-event", Gtk.main_quit)
    window.show_all()
    Gtk.main()
    

    There must be a way to do this....

提交回复
热议问题