[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Sizes are given as configuration options. To specify a view area size, use canvas width
and height options. To specify an overall canvas size, give the (X,Y) coordinates of the
upper-left and lower-right corners of the canvas in a four-item tuple passed to the
scrollregion option. If no view area size is given, a default size is used. If no
scrollregion is given, it defaults to the view area size; this makes the scroll bar useless,
since the view is assumed to hold the entire canvas.


Mapping coordinates is a bit subtler. If the scrollable view area associated with a canvas
is smaller than the canvas at large, the (X,Y) coordinates returned in event objects are
view area coordinates, not overall canvas coordinates. You’ll generally want to scale
the event coordinates to canvas coordinates, by passing them to the canvasx and
canvasy canvas methods before using them to process objects.


For example, if you run the scrolled canvas script and watch the messages printed on
mouse double-clicks, you’ll notice that the event coordinates are always relative to the
displayed view window, not to the overall canvas:


C:\...\PP4E\Gui\Tour> python scrolledcanvas.py
2 0 event x,y when scrolled to top of canvas
2.0 0.0 canvas x,y -same, as long as no border pixels
150 106
150.0 106.0
299 197
299.0 197.0
3 2 event x,y when scrolled to bottom of canvas
3.0 802.0 canvas x,y -y differs radically
296 192
296.0 992.0
152 97 when scrolled to a midpoint in the canvas
152.0 599.0
16 187
16.0 689.0

Here, the mapped canvas X is always the same as the canvas X because the display area
and canvas are both set at 300 pixels wide (it would be off by 2 pixels due to automatic
borders if not for the script’s highlightthickness setting). But notice that the mapped
Y is wildly different from the event Y if you click after a vertical scroll. Without scaling,
the event’s Y incorrectly points to a spot much higher in the canvas.


Many of this book’s canvas examples need no such scaling—(0,0) always maps to the
upper-left corner of the canvas display in which a mouse click occurs—but just because
canvases are not scrolled. See the next section for a canvas with both horizontal and
vertical scrolls; the PyTree program later in this book is similar, but it also uses dy-
namically changed scrollable region sizes when new trees are viewed.


As a rule of thumb, if your canvases scroll, be sure to scale event coordinates to true
canvas coordinates in callback handlers that care about positions. Some handlers might
not care whether events are bound to individual drawn objects or embedded widgets
instead of the canvas at large, but we need to move on to the next two sections to see
how.


556 | Chapter 9: A tkinter Tour, Part 2

Free download pdf