基于Python实现图片浏览器的应用程序

  import os

  import wx

  class ImageFrame(wx.Frame):

  def __init__(self, parent, title):

  super(ImageFrame, self).__init__(parent, title=title, size=(800, 600))

  self.panel = wx.Panel(self)

  self.sizer = wx.GridSizer(rows=0, cols=3, hgap=5, vgap=5)

  self.panel.SetSizer(self.sizer)

  self.file_picker = wx.DirPickerCtrl(self.panel, style=wx.DIRP_USE_TEXTCTRL)

  self.file_picker.Bind(wx.EVT_DIRPICKER_CHANGED, self.on_folder_selected)

  self.sizer.Add(self.file_picker, 0, wx.EXPAND|wx.ALL, 5)

  self.image_panels = []

  self.Show()

  def on_folder_selected(self, event):

  selected_folder = self.file_picker.GetPath()

  image_files = self.get_image_files(selected_folder)

  if image_files:

  self.display_images(image_files)

  def get_image_files(self, folder):

  image_files = []

  for root, dirs, files in os.walk(folder):

  for file in files:

  if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):

  image_files.append(os.path.join(root, file))

  return image_files

  def display_images(self, image_files):

  # Clear existing image panels

  for panel in self.image_panels:

  panel.Destroy()

  self.image_panels = []

  num_images = len(image_files)

  if num_images == 0:

  return

  num_rows = (num_images - 1) // 3 + 1

  self.sizer.Clear(True)

  self.sizer.SetCols(3)

  self.sizer.SetRows(num_rows)

  for image_file in image_files:

  image_panel = wx.Panel(self.panel)

  image_panel.SetBackgroundColour(wx.WHITE)

  image = wx.Image(image_file, wx.BITMAP_TYPE_ANY)

  image_bitmap = self.scale_image(image)

  image_ctrl = wx.StaticBitmap(image_panel, bitmap=image_bitmap)

  image_sizer = wx.BoxSizer(wx.HORIZONTAL)

  image_sizer.Add(image_ctrl, 1, wx.EXPAND|wx.ALL, 5)

  image_panel.SetSizer(image_sizer)

  self.sizer.Add(image_panel, 0, wx.EXPAND|wx.ALL, 5)

  self.image_panels.append(image_panel)

  self.panel.Layout()

  self.Refresh()

  self.Update()

  def scale_image(self, image):

  max_width = 200

  max_height = 200

  width = image.GetWidth()

  height = image.GetHeight()

  if width > max_width or height > max_height:

  if width > height:

  new_width = max_width

  new_height = int(max_width * height / width)

  else:

  new_height = max_height

  new_width = int(max_height * width / height)

  image = image.Scale(new_width, new_height, wx.IMAGE_QUALITY_HIGH)

  return image.ConvertToBitmap()

  if __name__ == '__main__':

  app = wx.App()

  frame = ImageFrame(None, title="Image Viewer")

  app.MainLoop()