简体   繁体   English

如何更改 gtk.MenuItem() 的背景颜色

[英]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.对于用 Gtk 制作的弹出菜单,我想将第一个菜单项作为标题。 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.由于---根据文档---不能更改gtk.Label的背景颜色,而必须更改其容器的背景,所以在我gtk.MenuItem应该修改gtk.MenuItem本身。

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.这适用于gtk.EventBox容器,但不适用于gtk.MenuItem What's not working here above and what can I do to have this gtk.MenuItem background white?什么在上面不起作用,我该怎么做才能让这个gtk.MenuItem背景gtk.MenuItem白色?

PS: i'd rather not use any .rc file for this. PS:我宁愿不为此使用任何 .rc 文件。

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:但是如果你想让整个菜单背景变白,你需要改变父菜单,而不是MenuItem,像这样:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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