Search code examples
pythontkintertext-widget

Formatting text while typing in a Tkinter Text widget


I'm trying to add notes to a given text that's not to be altered. It's pretty much like formatting in common text editors.

I have tried to get the current cursor position via .index('insert'), and then tag the character either forwards with tag_add(current cursor, current cursor '+1c'), or backwards with tag_add(current cursor + '-1c', current cursor). This results in tagging either the character right before or after the character just typed.

Are there any workarounds to live-tag the actually typed character?

import tkinter


main = tkinter.Tk()

def typing(event):
    text.tag_configure('note', background='yellow')
    text.tag_configure('note2', background='blue')
    cur_cursor = text.index("insert")
    text.tag_add('note', cur_cursor + '-1c', cur_cursor)
    text.tag_add('note2', cur_cursor, cur_cursor + '+1c')

text = tkinter.Text(main)
text.grid()
text.bind('<Key>', typing)

for i in ['OX'*20 + '\n' for i in range(10)]:
    text.insert('end', i)

main.mainloop()

Edit: Although Bryan's answer worked for me you might get problems with fast typing as described here: how-to-get-cursor-position


Solution

  • The simplest solution is to bind on <KeyRelease> rather than <Key>. The reason is that the text widget doesn't actually insert the character you typed until its own <Key> binding fires, and that binding always fires after any custom bindings you have on the widget.