3

I'm trying to find a reliable way of getting the current cursor position in a tkinter text widget.

What I have so far is:

import tkinter as tk

def check_pos(event):
    print(t.index(tk.INSERT))

root = tk.Tk()

t = tk.Text(root)
t.pack()

t.bind("<Key>", check_pos)
t.bind("<Button-1>", check_pos)

root.mainloop()

However, this prints the previous cursor position and not the current one. Anyone have any ideas what is going on?

Thanks in advance.

Artemis
  • 2,553
  • 7
  • 21
  • 36
Neil
  • 706
  • 8
  • 23
  • See https://stackoverflow.com/a/3513906/7432 and https://stackoverflow.com/a/11542200/7432. Even though they are about getting inserted characters, getting the insertion point is handled in the same way. – Bryan Oakley May 30 '18 at 01:40
  • Thanks Bryan. That all makes sense, but when I try value = event.widget.get() it says I'm missing a positional argument 'index 1' – Neil May 30 '18 at 02:10
  • yes, those answers are related to the `Entry` widget and you're using a `Text` widget. The point is to understand how events are processed, and that's the same for all widgets. – Bryan Oakley May 30 '18 at 02:32

1 Answers1

3

Thanks to Bryan Oakley for pointing me in the right direction with the links he posted in the comments. I chose the third choice which introduces an additional binding. The working code is below. Now the binding happens after the class is bound so that the change of position in the Text widget is visible to the function.

import tkinter as tk

def check_pos(event):
    print(t.index(tk.INSERT))

root = tk.Tk()

t = tk.Text(root)
t.pack()
t.bindtags(('Text','post-class-bindings', '.', 'all'))

t.bind_class("post-class-bindings", "<KeyPress>", check_pos)
t.bind_class("post-class-bindings", "<Button-1>", check_pos)


root.mainloop()
Neil
  • 706
  • 8
  • 23