Set cursor position in a Text widget

风格不统一 提交于 2019-11-29 19:46:32

问题


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.


回答1:


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

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




回答2:


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)



回答3:


This property is just for Text Widget, because for Entry Widget we could use:

entry_widget_name.icursor("position")

For Text Widget will be:

text_widget_name.mark_set("insert", "%d.%d" % (x,y))

where x = row position y = column position

(using integer numbers with dots like 1.0 or 3.0 for example)



来源:https://stackoverflow.com/questions/3215549/set-cursor-position-in-a-text-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!