Previous section   Next section

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

Table of Contents
Chapter 34.  The Canvas Widget

Canvas Coordinates

The coordinate space of the canvas has 0, 0 at the top left corner. Larger X coordinates are to the right, and larger Y coordinates are downward. The position and possibly the size of a canvas object is determined by a set of coordinates. Different objects are characterized by different numbers of coordinates. For example, text objects have two coordinates, x1 y1, that specify their anchor point. A line can have many pairs of coordinates that specify the end points of its segments. The coordinates are set when the object is created, and they can be updated later with the coords operation. By default, coordinates are in pixels. Append a coordinate with one of the following letters to change the units:

c   centimeters
i   inches
m   millimeters
p   printer points (1/72 inches)

The tk scale command, which is described on page 582, changes the mapping from pixels to other screen measures. Use it before creating the canvas.

The width and height attributes of the canvas determine the size of the viewable area. The scrollRegion attribute of the canvas determines the boundaries of the canvas. Its value is four numbers that specify the upper-left and lower-right coordinates of the canvas. If you do not specify a scroll region, it defaults to the size of the viewable area. Example 34-1 creates a canvas that has a 1000 by 400 scrolling region, and a 300 by 200 viewing area. The canvas is connected to two scrollbars to provide horizontal and vertical scrolling:

Example 34-1 A large scrolling canvas.
proc Scrolled_Canvas { c args } {
   frame $c
   eval {canvas $c.canvas \
      -xscrollcommand [list $c.xscroll set] \
      -yscrollcommand [list $c.yscroll set] \
      -highlightthickness 0 \
      -borderwidth 0}$args
   scrollbar $c.xscroll -orient horizontal \
      -command [list $c.canvas xview]
   scrollbar $c.yscroll -orient vertical \
      -command [list $c.canvas yview]
   grid $c.canvas $c.yscroll -sticky news
   grid $c.xscroll -sticky ew
   grid rowconfigure $c 0 -weight 1
   grid columnconfigure $c 0 -weight 1
   return $c.canvas
Scrolled_Canvas .c -width 300 -height 200 \
   -scrollregion {0 0 1000 400}
=> .c.canvas
pack .c -fill both -expand true


Borders are drawn in the canvas.

The highlight thickness and border width are set to 0 in Example 34-1. Otherwise, these features occupy some of the canvas viewable area. If you want a raised border for your canvas, either use another frame, or remember to offset your positions to avoid having objects clipped by the borders.

      Previous section   Next section