环境:python 3.6.6, wxPython 4.0.3
在使用wxpython进行可视化界面编程时,可能遇到的一些需要插入图片的地方有:窗口图标、工具栏图标、按钮图标等,且这些地方使用的图片格式可能不一样。
这里介绍一种处理图片的方法,以二进制形式打开图片文件,并将其以base64编码,再解码为字符串形式。这里的picture可以是各种格式的图片(png、jpg、ico、bmp等)
with open(picture 'rb') as f:
base64_data = base64.b64encode(f.read())
pic_data = base64_data.decode()
这里得到的字符串pic_data就可以直接存放入代码中,替代放在目录中的图片
之后再通过类wx.lib.embeddedimage.PyEmbeddedImage来获取图片对象
(官方参考文档:https://docs.wxpython.org/wx.lib.embeddedimage.PyEmbeddedImage.html?highlight=pyembeddedimage)
class PyEmbeddedImage(object):
def __init__(self, data, isBase64=True):
self.data = data
self.isBase64 = isBase64
def GetBitmap(self):
return wx.Bitmap(self.GetImage())
def GetData(self):
data = self.data
if self.isBase64:
data = b64decode(self.data)
return data
def GetIcon(self):
icon = wx.Icon()
icon.CopyFromBitmap(self.GetBitmap())
return icon
def GetImage(self):
stream = BytesIO(self.GetData())
return wx.Image(stream)
这里简单列举几个应用场景(pic_data为图片的base64字符串)
1.设置窗口图标(图标必须是ico对象图片,因此调用方法GetIcon())
self.SetIcon(PyEmbeddedImage(pic_data).GetIcon())
2.设置位图按钮(必须是位图格式,因此调用方法GetBitmap())
picture= PyEmbeddedImage(pic_data).GetBitmap()
start_button = wx.BitmapButton(parent=self.left_panel, id=-1, bitmap=picture, pos=(20, 20), style=0)
3.工具栏
picture= PyEmbeddedImage(pic_data).GetBitmap()
self.tool_bar = self.CreateToolBar()
self.tool_bar.AddTool(toolId=1, label="refresh", bitmap=picture, shortHelp="refresh tree")
self.tool_bar.Realize()
看下效果(工具栏没有设置)