【问题标题】:wxPython - SetBitmap results in repositioning and double imagewxPython - SetBitmap 导致重新定位和双重图像
【发布时间】:2019-10-09 21:07:39
【问题描述】:

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

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

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

这是我的代码:

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

【问题讨论】:

    标签: python python-3.x image wxpython


    【解决方案1】:

    使用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上的问题。


    使用这个我可以将项目放在窗口的中心

        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

    【讨论】:

    • 如果我使用self.panel.Layout() 执行此操作,我遇到的问题是,如果鼠标进入并离开 WIndow 而不是 StaticBitmap,则绑定会“触发”。
    • 正如我在 Linux 上所说的,我必须使用 self.panel.Bind(),因为 self.image.Bind() 不会触发事件。但如果 self.image.Bind() 在您的系统上工作,请保留它。
    • 我只使用了self.panel.Layout() 而不是self.panel.Bind(),因为我在Windows 操作系统上!
    • 这可能是不同的情况 - 静态图像可能会使用面板中的全部空间,即使位图小于面板并且您会看到图像周围的边距。当我使用self.image = wx.BitmapButton(self.panel, 1, self.png) 并设置其背景颜色self.image.SetBackgroundColour((255,0,0)) 时,我可以看到这个问题。
    • hbox.Add(self.image,-1) 在定位方面做到了。居中小部件也有效!谢谢!
    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多