[Tkinter-discuss] Cursor coordinates

Michael O'Donnell michael.odonnell at uam.es
Fri Dec 4 23:39:08 CET 2009


Ok,

The following code demonstrates:

a) finding the char index  of the insertion cursor in a text item in a Canvas
b) translating that char position into pixel position
c) drawing a box around the insertion cursor.

Did I miss something?


from Tkinter import *
from tkFont import Font

root=Tk()

canvas=Canvas(root)
canvas.pack()
myFont=Font(family="Times", size=14)

myText="blahblah"
txt = canvas.create_text(10,10,text=myText, anchor=NW, font=myFont)

# place the cursor on the fifth character
canvas.focus_set()
canvas.focus(txt)
canvas.icursor(txt, 5)

# get the position
print "cursor character position=",canvas.index(txt, INSERT)

# Find the pixel bounds of the insertion cursor
#  (assume 1 pixel width of the cursor)

text=myText[0:canvas.index(txt, INSERT)]
width=myFont.measure(text)
bbox=canvas.bbox(txt)
x1=bbox[0]+width-1
y1=bbox[1]
x2=x1+3
y2=bbox[3]
canvas.create_rectangle(x1,y1,x2,y2, outline="red")

root.mainloop()


More information about the Tkinter-discuss mailing list