Tcl/Tk Tutorial on Tk Canvas Widgets

canvas is used for providing drawing areas. the syntax for canvas widget is shown below −

canvas canvasname options

options

the options available for the canvas widget are listed below in the following table −

sr.no. syntax & description
1

-background color

used to set background color for widget.

2

-closeenough distance

sets the closeness of mouse cursor to a displayable item. the default is 1.0 pixel. this value may be a fraction and must be positive.

3

-scrollregion boundingbox

the bounding box for the total area of this canvas.

4

-height number

used to set height for widget.

5

-width number

sets the width for widget.

6

-xscrollincrement size

the amount to scroll horizontally when scrolling is requested.

7

-yscrollincrement size

the amount to scroll vertically when scrolling is requested.

a simple example for canvas widget is shown below −

#!/usr/bin/wish

canvas .mycanvas -background red -width 100 -height 100 
pack .mycanvas

when we run the above program, we will get the following output −

canvas widget example

widgets for drawing in canvas

the list of the available widgets for drawing in canvas is listed below −

sr.no. widget & description
1 line

draws a line.

2 arc

draws an arc.

3 rectangle

draws a rectangle.

4 oval

draws an oval.

5 polygon

draws a polygon.

6 text

draws a text.

7 bitmap

draws a bitmap.

8 image

draws an image.

an example using different canvas widgets is shown below −

#!/usr/bin/wish

canvas .mycanvas -background red -width 200 -height 200 
pack .mycanvas
.mycanvas create arc 10 10 50 50 -fill yellow
.mycanvas create line 10 30 50 50 100 10 -arrow both -fill yellow -smooth true
   -splinesteps 2
.mycanvas create oval 50 50 100 80 -fill yellow
.mycanvas create polygon 50 150 100 80 120 120 100 190 -fill yellow -outline green
.mycanvas create rectangle 150 150 170 170  -fill yellow
.mycanvas create text 170 20 -fill yellow -text "hello" -font {helvetica -18 bold}
.mycanvas create bitmap 180 50 -bitmap info

when we run the above program, we will get the following output −

canvas widget example2