views:

120

answers:

2

Hi

Is it possible to set the cursor position in a Tkinter Text widget? I'm not finding anything terribly useful yet.

The best I've been able to do is emit a <Button-1> and <ButtonRelease-1> event at a certain x-y coordinate, but that is a pixel amount, not a letter amount.

Any help would be welcome, Thanks

+2  A: 

If "text", "line", "column" are your text object, desired text line and desired column variables:

text.mark_set("insert", "%d.%d" % (line + 1, column + 1)

If you would not like to care about the line number...well, you have to.

Complete documentation at: http://effbot.org/tkinterbook/text.htm

jsbueno
Perfect! I thought it might be somewhere along those lines but I couldn't figure it out. Is there a related method for getting the current cursor position?
Wayne Werner
@Wayne Werner: the "index" method will return the index of any position including the insertion cursor: `text.index("insert")`
Bryan Oakley
+2  A: 

To set the cursor position, you can use the text_widget.mark_set method, with "insert" (or Tkinter.INSERT for a “constant”) first argument and, for the second argument, one of many forms, the most useful being:

  • "%d,%d" % (line, column), where line is 1-based and column is 0-based
  • "1.0+%d chars" % index, where index is 0-based just like a string/unicode index in Python

To get the index of a mark, you can use the text_widget.index method:

text_widget.index(Tkinter.INSERT)
ΤΖΩΤΖΙΟΥ