PYTHON 26
ImageBrowser.py Guest on 2nd May 2021 02:26:03 AM
  1. """
  2.  
  3. Solution to an exercise from
  4. Think Python: An Introduction to Software Design
  5. Allen B. Downey
  6.  
  7. This program requires Gui.py, which is part of
  8. Swampy; you can download it from thinkpython.com/swampy.
  9.  
  10. This program started with a recipe by Noah Spurrier at
  11. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521918
  12.  
  13. """
  14.  
  15. import os, sys
  16. from Gui import *
  17. import Image as PIL      # to avoid name conflict with Tkinter
  18. import ImageTk
  19.  
  20. class ImageBrowser(Gui):
  21.     """An image browser that scans the files in a given directory and
  22.    displays any images that can be read by PIL.
  23.    """
  24.     def __init__(self):
  25.         Gui.__init__(self)
  26.  
  27.         # clicking on the image breaks out of mainloop
  28.         self.button = self.bu(command=self.quit, relief=FLAT)
  29.  
  30.     def image_loop(self, dirname='.'):
  31.         """loop through the files in (dirname), displaying
  32.        images and skipping files PIL can't read.
  33.        """
  34.         files = os.listdir(dirname)
  35.         for file in files:
  36.             try:
  37.                 self.show_image(file)
  38.                 print file
  39.                 self.mainloop()
  40.             except IOError:
  41.                 continue
  42.             except:
  43.                 break
  44.  
  45.     def show_image(self, filename):
  46.         """Use PIL to read the file and ImageTk to convert
  47.        to a PhotoImage, which Tk can display.
  48.        """
  49.         image = PIL.open(filename)
  50.         self.tkpi = ImageTk.PhotoImage(image)
  51.         self.button.config(image=self.tkpi)
  52.  
  53. def main(script, dirname='.'):
  54.     g = ImageBrowser()
  55.     g.image_loop(dirname)
  56.  
  57. if __name__ == '__main__':
  58.     main(*sys.argv)

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.