Displaying an image is a 2-step process:
- Create an image object in memory
- Display the image object in the canvas (or other widget)
You create the image object with the image create
command, which is where you'd specify the name of the file containing the image data. For example:set img [image create photo -file myImg.pgm]
A couple of notes here. The example above assumes that the image file is in the current working directory. If it isn't, you can use a relative or absolutive path for the file name. The second note is that the image create
command automatically creates a name for the image object, and that is the return value of the command. You'll need this image name later on, so you'll want to store it in a variable, as shown above.
Now that we've got an image object created, we can display it in our canvas (or other widget). For a canvas, you do so with the canvas's create image operation, and providing it the position and the name of the image object to display. For example:canvas .c
pack .c -expand yes -fill both
.c create image 10 10 -anchor nw -image $img
This example tell the canvas, .c, to display the image object I created earlier so that its northwest corner (upper-left corner) is anchored to the position x=10, y=10 on the canvas.
As an aside, Tcl/Tk has built-in support only for GIF and PPM/PGM format full-color images. If you want to display images from other file formats, you'll need to download and install the Img
extension, which allows you to display other formats such as JPEG, TIFF, and others.
- Ken Jones, President, firstname.lastname@example.org
Avia Training and Consulting, www.avia-training.com
866-TCL-HELP (866-825-4357) US Toll free