我使用wxpython设计了一个界面,我现在希望为他添加一个背景图片,但不是图片显示不出来,就是图片把按键盖住了。
我在网上找到一段代码如下:
import wx
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,"My Frame",size=(400,300),
style = wx.DEFAULT_FRAME_STYLE)
self.panel = wx.Panel(self)
self.panel.Bind(wx.EVT_ERASE_BACKGROUND,self.OnEraseBack)
def OnEraseBack(self,event):
dc = event.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
bmp = wx.Bitmap(r'C:\Users\gztsrayz\PycharmProjects\flask-test\img\爬 - 副本.jfif')
dc.DrawBitmap(bmp, 0, 0)
if __name__ == '__main__':
app = wx.App()
frame = Frame()
frame.Show()
app.MainLoop()
这段代码是可以正确运行的,以下是我的代码:
import wx
import random
# from wx import MessageBox
class Frame(wx.Frame):
def __init__(self):
# Create a new app, don't redirect stdout/stderr to a window.
wx.Frame.__init__(self,None,-1,title="酒泉",size=(500,600),style = wx.DEFAULT_FRAME_STYLE)
self.panel = wx.Panel(self)
self.panel.Bind(wx.EVT_ERASE_BACKGROUND,self.OnEraseBack)
# image_file = r'C:\Users\gztsrayz\PycharmProjects\flask-test\img\爬 - 副本.jfif'
# to_bmp_image = wx.Image(image_file, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# self.bitmap = wx.StaticBitmap(frame, -1, to_bmp_image, (0, 0))
bt1=wx.Button(frame,label='拳头',pos=(100,50),size=(300,100))
bt2=wx.Button(frame,label='剪刀',pos=(100,200),size=(300,100))
bt3=wx.Button(frame,label='布',pos=(100,350),size=(300,100))
bt1.Bind(wx.EVT_BUTTON,self.quantou)
bt2.Bind(wx.EVT_BUTTON,self.jiandao)
bt3.Bind(wx.EVT_BUTTON,self.bu)
# frame.Show()
# app.MainLoop()
def OnEraseBack(self,event):
dc = event.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
bmp = wx.Bitmap(r'C:\Users\gztsrayz\PycharmProjects\flask-test\img\爬 - 副本.jfif')
dc.DrawBitmap(bmp, 0, 0)
def quantou(self,event):
a=random.choice(['拳头','剪刀','布'])
if a=='拳头':
wx.MessageBox('平手了,但是'+random.choice(['你的拳头更大','你的拳头被打穿了']))
elif a=='剪刀':
wx.MessageBox('you win !')
else:
wx.MessageBox('you lose !')
def jiandao(self,event):
a=random.choice(['拳头','剪刀','布'])
if a=='拳头':
wx.MessageBox('you lose !')
elif a=='剪刀':
wx.MessageBox('平手了,但是'+random.choice(['你的剪刀更锐利','你的剪刀不得劲']))
else:
wx.MessageBox('you win !')
def bu(self,event):
a=random.choice(['拳头','剪刀','布'])
if a=='拳头':
wx.MessageBox('you win !')
elif a=='剪刀':
wx.MessageBox('you lose !')
else:
wx.MessageBox('平手了,但是'+random.choice(['你的布更大','你被包住了']))
if __name__ == '__main__':
app = wx.App()
frame = Frame()
frame.Show()
app.MainLoop()
报错:PyNoAppError: The wx.App object must be created first!
当我将按键删除后则没有报错,请问这是什么原因,我应该如何设置背景图片?