Welcome, guest | Sign In | My Account | Store | Cart

Reads an image file from the filename specified as the 1st parameter on the command line and displays it on screen. Uses the PIL module so that it can load almost any image file type supported by that module and uses Tkinter to display the image on a Tkinter canvas.

I'm new to Python so excuse the clunkyness of implementation.

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#HelloImage - display an image file
# Simon Peverett - October 2003
# uses the PIL module: http://www.pythonware.com/products/pil/
# developed using ActivePython 2.2: http://www.activestate.com

from Tkinter import *
import Image            #PIL
import ImageTk          #PIL
import sys
import getopt

try:
    if len(sys.argv) == 1:
        raise ValueError, "No image filename specified"

    #will raise file IO error if no file found
    im = Image.open(sys.argv[1]) 

    #print im.size, im.mode, im.format
    #print im.size[0]

    root = Tk()

    # add 20 to account for border defined in create_image
    canvas = Canvas(root, height=im.size[1]+20, width=im.size[0]+20)
    canvas.pack(side=LEFT,fill=BOTH,expand=1)

    photo = ImageTk.PhotoImage(im)
    item = canvas.create_image(10,10,anchor=NW, image=photo)
    mainloop()

except Exception, e:
    print >>sys.stderr, e
    print "USAGE: HelloImage <image filename>"
    sys.exit(1)

My aim is to write a simple slideshow and was looking for a recipe on loading and displaying a simple image. Couldn't find one. Found one that used only Tkinter to display GIF files but this script should display any graphic image type that is supported by PIL.

1 comment

Chris Niekel 17 years, 6 months ago  # | flag

Note that if you change this example to have functions, you need to store the 'photo' variable somewhere. When photo has been garbage-collected once the mainloop starts, you won't see your picture.