我在Python 2.7上使用wxPython。 我想帮助创建一个带位图图像的按钮。
我正在使用此视频https://www.youtube.com/watch?v=Y7f0a7xbWHI, 然后我按照代码输入了
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Frame aka window',size=(300,200))
panel=wx.Panel(self)
pic=wx.Image("back.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap()
self.button=wx.BitmapButton(panel, -1, pic, pos=(10,10))
self.Bind(wx.EVT_BUTTON, self.doMe, self.button)
self.button.SetDefault()
def doMe(self, event):
self.Destroy
创建带图像的按钮。我收到一条错误,指出无效图片。 我将位图图像保存在我正在使用的.py文件的文件夹中。 我觉得我把图像保存在错误的地方? 先感谢您。
我收到的错误
Traceback (most recent call last):
File "C:\Python27\FrameWindow.py", line 81, in <module>
frame=bucky(parent=None,id=-1)
File "C:\Python27\FrameWindow.py", line 17, in __init__
pic=wx.Image("back.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap()
File "C:\Python27\lib\site-packages\wx\core.py", line 708, in _Image_ConvertToBitmap
bmp = wx.Bitmap(self, depth)
wxAssertionError: C++ assertion "image.IsOk()" failed at ..\..\src \msw\bitmap.cpp(922) in wxBitmap::CreateFromImage(): invalid image
答案 0 :(得分:0)
使用wx.BITMAP_TYPE_ANY
而不是wx.BITMAP_TYPE_BMP
它是否需要猜测它是否真的是BMP
或直接使用wx.Bitmap()
。
import wx
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,'Frame aka window',size=(300,200))
panel=wx.Panel(self)
#
# Use wx.BITMAP_TYPE_ANY rather than wx.BITMAP_TYPE_BMP
#
#pic=wx.Image("Discord.bmp", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
#
# or use wx.Bitmap()
pic = wx.Bitmap("Discord.bmp", wx.BITMAP_TYPE_ANY)
#
self.button=wx.BitmapButton(panel, -1, pic, pos=(10,10))
self.Bind(wx.EVT_BUTTON, self.doMe, self.button)
self.Show()
def doMe(self, event):
self.Destroy()
if __name__ == "__main__":
app = wx.App()
frame = MainFrame()
app.MainLoop()
原则上,您应该使用完整路径名命名您的图像。如果您有许多图像,那么在您使用它们时,请为您的图像名称设置一个图像目录并join
该目录名称,这将再次为您提供完整路径(/home/images/back_button.bmp)
答案 1 :(得分:0)
我通过添加
来实现它"locale = wx.Locale(wx.LANGUAGE_ENGLISH)"
下
class MainFrame(wx.Frame):
def __init__(self):
现在我没有收到错误消息,它按预期运行。 我收到的这个问题的错误代码是:
Traceback (most recent call last):
File "C:\Python27\panel test.py", line 21, in <module>
frame = MainFrame()
File "C:\Python27\panel test.py", line 11, in __init__
pic = wx.Bitmap("back.bmp", wx.BITMAP_TYPE_ANY)
wxAssertionError: C++ assertion "strcmp(setlocale(LC_ALL, NULL), "C") == 0" failed at ..\..\src\common\intl.cpp(1579) in wxLocale::GetInfo(): You probably called setlocale() directly instead of using wxLocale and now there is a mismatch between C/C++ and Windows locale.
Things are going to break, please only change locale by creating wxLocale objects to avoid this!
我的主要问题给出的错误是由Rolf by Saxony给出的代码解决的。