0

I am writing an app of a Python editor of my own. I am using a Text widget and want to highlight words as the words are typed in like Python editor. As soon as the character # is typed in, I want to begin highlighting all characters followed from the character # with color of red.

Below is the partial code for the purpose. When the character # was identified as it was typed in to the Text widget, I added a tag of "CM" from the typed-in-character to the end of the line (I thought this would do the job for me).

import tkinter as tk

def onModification(event=None):
    c=event.char
    if not c: return
    pos=hT0.index(tk.INSERT)

    if c=='#':
        hT0.tag_add('CM',pos,f'{int(pos.split(".")[0])}.end')
        return

hW=tk.Tk()
hT0=tk.Text(hW,wrap='none',font=('Times New Roman'12))
hT0.insert('end','')
hT0.place(x=27, y=0, height=515,width=460)
hT0.bind('<Key>', onModification)
hT0.tag_config('CM', foreground='#DD0000')

But the output highlights only characters already existed even without the just-typed-in-character #. An idea for the job I want? Thank you so much in advance.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
S. Lee
  • 33
  • 4

1 Answers1

0

I obtained an idea from the Get position in tkinter Text widget

def onModification(event=None):
    ...
    pos=hT0.index(tk.INSERT)
    lineN, ColN=[int(c) for c in pos.split('.')]
    if c=='#':
        #hT0.tag_add('CM',pos,f'{int(pos.split(".")[0])}.end')
        hT0.tag_add('CM',f'{lineN}.{ColN-1}',f'{lineN}.end')
        return

...
#hT0.binds('<key>', onModification) needs to be changed to...

hT0.bindtags(('Text','post-class-bindings','.','all'))
hT0.bind_class('post-class-bindings', '<KeyPress>', onModification)
S. Lee
  • 33
  • 4
  • I don't understand what you wrote here. Is this supposed to be an answer to your own question? Do you still need help? – Bryan Oakley Nov 07 '19 at 21:26