Tcl/Tk Cookbook - Canvas Revisited


Step 2: Add other gui objects

Script


button .rect  -image [image create bitmap \
-file  "./bitmaps/boxOp.xbm"]  -com {set sb "rectangle"}
button .circ  -image [image create bitmap -file  "./bitmaps/ovalOp.xbm"] \
	 -com {set sb "oval" }
button .lin  -image [image create bitmap -file  "./bitmaps/lineOp.xbm"] \
	 -com {set sb "line" }
button .txt  -image [image create bitmap -file  "./bitmaps/textOp.xbm"] \
	 -com {set sb "text"}
button .selob  -image [image create bitmap -file  "./bitmaps/selectOp.xbm"] \
	 -com {set sb "obj" }
label .txtlab -text "Text : "
entry .txtstr -textvariable str -relief sunken -width 10

place .rect -in .fr.panl -x 2 -y 1
place .circ -in .fr.panl -x 60 -y 1
place .lin -in .fr.panl -x 2 -y 60
place .txt -in .fr.panl -x 2 -y 120
place .selob -in .fr.panl -x 60 -y 60
place .txtlab -in .fr.panl -x 2 -y 180
place .txtstr -in .fr.panl -x 20 -y 220

Image

The Tk command image is used to create, delete or query images. The first argument to image specifies the action to be taken (e.g. create and the second argument is the type of the image (e.g. bitmap). The "-file" option rreads the bitmap data from the file specified.

The "-image" option replaces the "-text" option in the button creation command to place the bitmap image as the labels for the buttons. Each button command sets the value of the global variable "sb" to a specific value. The value of the variable is used in the cnavas drawing routines to determine which type of drawing primitive should be drawn. i.e. the user selects, for example, the "rectangle" button; "sb" is set the value "rectangle" and in the canvas the command .can create $sb $x $y $x1 $y1 draws a rectangle object.

Text

In this example, drawing text in the canvas is simplified. The user inputs the text string in the entry widget, hits return and selects the button marked "A". Then the text string is created in the canvas wherever the left mouse button is clicked.

Selecting an Object

The button with the "dotted rectangle" label is used to specify a rectangular region within the canvas widget. To mark this a rectangle will be drawn with a red outline.

The widget placements should result in

The current drawing primitive changes only when the user explicitly selects another by selecting one of the other buttons.