在 wxpython 中设置背景图像

Mik*_*ike 1 python wxpython

我在 wxpython 中有一些令人困惑的行为。我刚刚将最新版本 (3.0.0.0) 加载到带有 Python 2.6.6 的 RHEL 6.4 中。

大多数事情似乎都有效,但我之前运行带有背景图像的 gui 的代码失败了。所有按钮都可以工作,等等,但背景只是默认的灰色。

我尝试通过运行 Mike Driscoll 的 python 网站 ( http://www.blog.pythonlibrary.org/2010/03/18/wxpython-putting-a-background-image-on-a-panel /),并且遇到了同样的问题,除了默认的灰色背景之外没有其他背景显示(我之前在另一台机器上使用过他的示例,其中有旧版本的 wxpython [2.8.12.1] 没有问题):

import wx

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.frame = parent

        sizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        for num in range(4):
            label = "Button %s" % num 
            btn = wx.Button(self, label=label)
            sizer.Add(btn, 0, wx.ALL, 5)
        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(sizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75) 
        self.SetSizer(hSizer)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    #----------------------------------------------------------------------
    def OnEraseBackground(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()

        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("butterfly.jpg")
        dc.DrawBitmap(bmp, 0, 0)


########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, size=(600,450))
        panel = MainPanel(self)
        self.Center()

########################################################################
class Main(wx.App):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, redirect=False, filename=None):
        """Constructor"""
        wx.App.__init__(self, redirect, filename)
        dlg = MainFrame()
        dlg.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = Main()
    app.MainLoop()
Run Code Online (Sandbox Code Playgroud)

现在,当我运行它时,我没有收到任何错误,但我确定 onEraseBackground 函数似乎永远不会运行。我不知道这里出了什么问题;wxpython 3.0.0.0 是否停止允许这种图像背景设置程序?

Joh*_*yon 6

尝试注释掉

self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
Run Code Online (Sandbox Code Playgroud)

线。其他一些人也遇到过同样的问题,这条线是罪魁祸首——它阻止了EVT_ERASE_BACKGROUND事件被触发。

您也可以尝试用

self.SetBackgroundStyle(wx.BG_STYLE_ERASE)
Run Code Online (Sandbox Code Playgroud)

以确保触发擦除事件。