简体   繁体   中英

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.

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".

After messing around with it, I found this will work to change the text on the main menu:

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

But if you want the whole background of the menu white, you need to change the parent menu, not the MenuItem, like this:

menu = gtk.Menu()
menu_item = gtk.MenuItem("File")
menu_item.set_sumenu(menu)
menu.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(65355,65355,65355))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM