不知道我是否应该回答我自己的问题,但我确实找到了解决问题的方法,我想和大家分享。我用的是wx2.8版。我发现在2.9和3.0中有一个小部件被添加到WrapSizer。有一次我把wx版本升级到了3.0版本,这使得解决方案变得非常简单。下面是重要的代码片段。在self.PhotoMaxWidth = 100
self.PhotoMaxHeight = 100
self.GroupOfThumbnailsSizer = wx.WrapSizer()
self.CreateThumbNails(len(ListOfPhotots),ListOfPhotots)
self.GroupOfThumbnailsSizer.SetSizeHints(self.whateverPanel)
self.whateverPanel.SetSizer(self.GroupOfThumbnailsSizer)
self.whateverPanel.Layout()
def CreateThumbNails(self, n, ListOfFiles):
thumbnails = []
backgroundcolor = "white"
for i in range(n):
ThumbnailSizer = wx.BoxSizer(wx.VERTICAL)
self.GroupOfThumbnailsSizer.Add(ThumbnailSizer, 0, 0, 0)
thumbnails.append(ThumbnailSizer)
for thumbnailcounter, thumbsizer in enumerate(thumbnails):
image = Image.open(ListOfFiles[thumbnailcounter])
image = self.ResizeAndCenterImage(image, self.PhotoMaxWidth, self.PhotoMaxHeight, backgroundcolor)
img = self.pil_to_image(image)
thumb= wx.StaticBitmap(self.timelinePanel, wx.ID_ANY, wx.BitmapFromImage(img))
thumbsizer.Add(thumb, 0, wx.ALL, 5)
return
def pil_to_image(self, pil, alpha=True):
""" Method will convert PIL Image to wx.Image """
if alpha:
image = apply( wx.EmptyImage, pil.size )
image.SetData( pil.convert( "RGB").tostring() )
image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
else:
image = wx.EmptyImage(pil.size[0], pil.size[1])
new_image = pil.convert('RGB')
data = new_image.tostring()
image.SetData(data)
return image
def ResizeAndCenterImage(self, image, NewWidth, NewHeight, backgroundcolor):
width_ratio = NewWidth / float(image.size[0])
temp_height = int(image.size[1] * width_ratio)
if temp_height < NewHeight:
img2 = image.resize((NewWidth, temp_height), Image.ANTIALIAS)
else:
height_ratio = NewHeight / float(image.size[1])
temp_width = int(image.size[0] * height_ratio)
img2 = image.resize((temp_width, NewHeight), Image.ANTIALIAS)
background = Image.new("RGB", (NewWidth, NewHeight), backgroundcolor)
masterwidth = background.size[0]
masterheight = background.size[1]
subwidth = img2.size[0]
subheight = img2.size[1]
mastercenterwidth = masterwidth // 2
mastercenterheight = masterheight // 2
subcenterwidth = subwidth // 2
subcenterheight = subheight // 2
insertpointwidth = mastercenterwidth - subcenterwidth
insertpointheight = mastercenterheight - subcenterheight
background.paste(img2, (insertpointwidth, insertpointheight))
return background
我从另一个stackoverflow帖子中得到了pil-tu-to-tu图像部分,我写了ResizeAndCenterImage部分,使我所有的缩略图大小相同,同时保持纵横比不变,不做任何裁剪。如果您愿意,可以一起跳过resize和center调用。在