wxPython - SetBitmap 导致重新定位和双重图像

wxPython - SetBitmap results in repositioning and double image

我想在鼠标悬停在小部件上时更新 wx.StaticBitmap 的图像。 Baiscally,切换到黑白进行测试。

我的问题是,当调用 self.image.SetBitmap(...) 时,图像在我的 window 中重新定位,旧图像也留在旧位置。

附加问题:是否可以在不加载新黑白图像的情况下将我的图像设为黑白?

这是我的代码:

import wx

class Example(wx.Frame):
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)
        self.InitUI()

    def InitUI(self):
        self.panel = wx.Panel(self)
        hbox = wx.BoxSizer(wx.HORIZONTAL)

        self.png = wx.Bitmap("TestButton.png")
        self.png_bw = wx.Bitmap("TestButton_bw.png")

        self.image = wx.StaticBitmap(self.panel, 1, self.png)

        self.image.Bind(wx.EVT_ENTER_WINDOW, self.OnOver)
        self.image.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)

        hbox.Add(self.image,1)        

        self.panel.SetSizer(hbox)

        self.SetTitle('Button Test')
        self.Centre()

    def OnOver(self, event):
        self.image.SetBitmap(self.png_bw)
    def OnLeave(self, event):
        self.image.SetBitmap(self.png)

def main():
    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

使用self.panel.Layout()强制排列物品

def OnOver(self, event):
    self.image.SetBitmap(self.png_bw)
    self.panel.Layout()

def OnLeave(self, event):
    self.image.SetBitmap(self.png)
    self.panel.Layout()

在 Linux 我必须将事件绑定到 self.panel 而不是 self.image

    self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnOver)
    self.panel.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)

如果 self.image.Bind() 在您的系统上工作,请不要更改它。 也许它只在 Linux 上有问题。


使用这个我可以将项目放在 window

的中心
    hbox.Add(self.image, 1, wx.EXPAND|wx.ALL)    

使用wx.Image()你可以加载图像,它有方法转换成灰度。

    img = wx.Image("TestButton.png")
    img_bw = img.ConvertToGreyscale(0.3, 0.3, 0.3)

    self.png = wx.Bitmap(img)
    self.png_bw = wx.Bitmap(img_bw)

文档:wx.Image