Search code examples
pythongtkpygtkmenuitem

How to change the background color of a gtk.MenuItem()


For a pop-up menu made in Gtk, I would like to have the first menu item as a header. Preferably its background should be white. Since---according to the documentation---one cannot change a gtk.Label's background colour, but rather must change its container's background, it seemed to me the gtk.MenuItem itself should be modified.

However, I have tried the following in vain:

menu_item.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#FFFFFF'))

This would work for a container as gtk.EventBox, but for gtk.MenuItem it does not. What's not working here above and what can I do to have this gtk.MenuItem background white?

PS: i'd rather not use any .rc file for this.


Solution

  • Here is a sample that puts the "exit" menu in white when mouse hovvers over it. Hope it can help you !

    #!/usr/bin/python
    
    import gtk
    
    class PyApp(gtk.Window):
    
        def __init__(self):
            super(PyApp, self).__init__()
    
            self.set_title("Simple menu")
            self.set_size_request(250, 200)
            self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(6400, 6400, 6440))
            self.set_position(gtk.WIN_POS_CENTER)
    
            mb = gtk.MenuBar()
    
            filemenu = gtk.Menu()
            filem = gtk.MenuItem("File")
            filem.set_submenu(filemenu)
    
            exit = gtk.MenuItem("Exit")
            style = exit.get_style().copy ()
            style.bg[gtk.STATE_NORMAL] = exit.get_colormap().alloc_color (0xffff, 0x0000, 0x0000)
            exit.set_style (style)
    
            exit.connect("activate", gtk.main_quit)
            filemenu.append(exit)
    
            mb.append(filem)
    
            vbox = gtk.VBox(False, 2)
            vbox.pack_start(mb, False, False, 0)
    
            self.add(vbox)
    
            self.connect("destroy", gtk.main_quit)
            self.show_all()
    
    PyApp()
    gtk.main()
    

    To do this, I play with the "style".