我创建一个菜单和菜单项,在菜单中不显示任何图像的某个时候第一个项目指定图像,我无法找到原因。 我试图做一个简单的独立的例子,下面是确实证明了我的机器上的问题的代码。 我使用Windows XP,宽x 2.8.7.1(MSW-Unicode)的”
import wx
def getBmp():
bmp = wx.EmptyBitmap(16,16)
return bmp
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, style=wx.DEFAULT_FRAME_STYLE, parent=None)
self.SetTitle("why New has no image?")
menuBar = wx.MenuBar()
fileMenu=wx.Menu()
item = fileMenu.Append(wx.ID_NEW, "New")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_OPEN, "Open")
item.SetBitmap(getBmp())
item = fileMenu.Append(wx.ID_SAVE, "Save")
item.SetBitmap(getBmp())
menuBar.Append(fileMenu, "File")
self.SetMenuBar(menuBar)
app = wx.PySimpleApp()
frame=MyFrame()
frame.Show()
app.SetTopWindow(frame)
app.MainLoop()
那么,你能看到问题,可能是什么原因呢?
结论 :是的,这是一个官方的错误,我创建了一个简单的菜单类来克服这一缺陷,使用选择的答案是“balpha”给出的诀窍
它覆盖每个menu.Append方法,如果被添加了第一次与图像菜单项,如果是创建一个虚拟的项目,后来删除它看到。
这也增加了功能/约束,这样的而不是调用SetBitmap,你应该通过位图作为可选参数图片
import wx
class MockMenu(wx.Menu):
"""
A custom menu class in which image param can be passed to each Append method
it also takes care of bug http://trac.wxwidgets.org/ticket/4011
"""
def __init__(self, *args, **kwargs):
wx.Menu.__init__(self, *args, **kwargs)
self._count = 0
def applyBmp(self, unboundMethod, *args, **kwargs):
"""
there is a bug in wxPython so that it will not display first item bitmap
http://trac.wxwidgets.org/ticket/4011
so we keep track and add a dummy before it and delete it after words
may not work if menu has only one item
"""
bmp = None
if 'image' in kwargs:
bmp = kwargs['image']
tempitem = None
# add temp item so it is first item with bmp
if bmp and self._count == 1:
tempitem = wx.Menu.Append(self, -1,"HACK")
tempitem.SetBitmap(bmp)
ret = unboundMethod(self, *args, **kwargs)
if bmp:
ret.SetBitmap(bmp)
# delete temp item
if tempitem is not None:
self.Remove(tempitem.GetId())
self._lastRet = ret
return ret
def Append(self, *args, **kwargs):
return self.applyBmp(wx.Menu.Append, *args, **kwargs)
def AppendCheckItem(self, *args, **kwargs):
return self.applyBmp(wx.Menu.AppendCheckItem, *args, **kwargs)
def AppendMenu(self, *args, **kwargs):
return self.applyBmp(wx.Menu.AppendMenu, *args, **kwargs)