[Tutor] Coordinates TK and Turtle
eryksun
eryksun at gmail.com
Tue Jan 28 15:17:59 CET 2014
On Tue, Jan 28, 2014 at 4:48 AM, Ian D <duxbuz at hotmail.com> wrote:
>
> I have some weird results when I run my code which is meant to display a
> canvas and a turtle and some text with the turtles coordinates.
>
> Basically the turtle coordinates do not seem to correspond with the TK
> create_text coordinates.
>
> t1.goto(100,100)
>
> canvas_id = cv1.create_text(t1.xcor(), t1.ycor(),
> font=("Purisa",12),anchor="nw")
>
> cv1.insert(canvas_id, 0, t1.pos())
A turtle has a `write` method:
http://docs.python.org/2/library/turtle#turtle.write
It sets up for undoing the operation, and then it has the screen write
on the Tk canvas. Here's the screen's `_write` method:
>>> print inspect.getsource(turtle.TurtleScreen._write)
def _write(self, pos, txt, align, font, pencolor):
"""Write txt at pos in canvas with specified font
and color.
Return text item and x-coord of right bottom corner
of text's bounding box."""
x, y = pos
x = x * self.xscale
y = y * self.yscale
anchor = {"left":"sw", "center":"s", "right":"se" }
item = self.cv.create_text(x-1, -y, text = txt,
anchor = anchor[align],
fill = pencolor, font = font)
x0, y0, x1, y1 = self.cv.bbox(item)
self.cv.update()
return item, x1-1
xscale and yscale should be 1.0, but maybe not if you've called
`setworldcoordinates`. The y coordinate has to be negated, since it
increases from top to bottom in the canvas. I don't know about the -1
offset for the x coordinate. Scanning over the source, I don't see a
similar offset used for drawing lines, polygons, and images. So I
guess it's something to do with how `create_text` works. But I'm far
from being an expert with Tk widgets.
More information about the Tutor
mailing list