Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 33.  The Text Widget

Embedded Images

Tk 8.0 added embedded images that are much like embedded windows. They provide a more efficient way to add images than creating a canvas or label widget to hold the image. You can also put the same image into a text widget many times. Example 33-5 uses an image for the bullets in a bulleted list:

Example 33-5 Using embedded images for a bulleted list.
proc BList_Setup { t imagefile } {
   global blist
   set blist(image) [image create photo -file $imagefile]
   $t tag configure bulletlist -tabs ".5c center 1c left" \
      -lmargin1 0 -lmargin2 1c
proc BList_Item {t text {mark insert}} {
   global blist
   # Assume we are at the beginning of the line
   $t insert $mark \t bulletlist
   $t image create $mark -image $blist(image)
   $t insert $mark \t$text bulletlist

In Example 33-5, tabs are used to line up the bullet and the left edges of the text. The first tab centers the bullet over a point 0.5 centimeters from left margin. The second tab stop is the same as the -lmargin2 setting so the text on the first line lines up with the text that wraps onto more lines.

If you update the image dynamically, all the instances of that image in the text widget are updated, too. This follows from the image model used in Tk, which is described in Chapter 38 on page 541.

The options for embedded images are mostly the same as those for embedded windows. One difference is that images have a -name option so you can reference an image without remembering its position in the text widget. You cannot use the image name directly because the same image can be embedded many times in the text widget. If you do not choose a name, the text widget assigns a name for you. The image create operation returns this name:

$t image create 1.0 -image image1
=> image1
$t image create end -image image1
=> image1#1

Table 33-7 gives the complete set of options for creating embedded images. You can change these later with the image configure operation.

Table 33-7. Options to the image create operation.
-align whereAlignment: top, center, bottom, or baseline. Only has effect if image is shorter than the line height. See Table 33-5.
-image imageThe Tk image to add to the text widget.
-name nameA name for this instance of the image. A #num may be appended to generate a unique name.
-padx pixelsPadding on either side of the image.
-pady pixelsPadding above and below the image.

      Previous section   Next section