[Tkinter-discuss] Text editing and tags...

Michael Lange klappnase at web.de
Tue Dec 11 14:54:48 EST 2018


Hi Vasilis,

On Tue, 11 Dec 2018 13:45:10 +0000
Vasilis Vlachoudis <Vasilis.Vlachoudis at cern.ch> wrote:

> Hi all,
> 
> Considering the following code, it creates a Text() and adds the word
> "Red" with tag "red" and "Normal" without  afterwords without any tag.
> If you click the cursor in between the two letters d|N from (Red"d" and
> "N"ormal) and you start typing, the newly inserted text will be black
> without out any tag associated. Is there a way to change this behavior
> like the word processing editor where the end of a tag is inclusive
> that if you start typing at the end of the tag it will assume that is
> inside the tag-range and not outside?

so far as I can see there is no built-in way to achieve this. Maybe you
can try to override the default Tk event handlers of the Text widget.
For starters I set up a very basic example of a modified KeyPress event
handler:

##################################
import tkinter as tk
root=tk.Tk()
txt = tk.Text(root)
txt.pack(fill='both', expand=1)
txt.tag_configure("red", foreground="Red")
txt.insert('end',"Red", 'red')
txt.insert('end',"Normal")

def on_key_press(event):
    ins = txt.index('insert')
    if event.char and not ('\n' in event.char or '\r' in event.char or '\b' in event.char):
        txt.tk.call('tk::TextInsert', txt._w, event.char)# borrowed from text.tcl
        l, i = str(ins).split('.')
        if int(i) > 0 and 'red' in txt.tag_names('%s.%d' %(l, int(i)-1)):
            txt.tag_add('red', ins)
        return('break')

txt.bind('<KeyPress>', on_key_press)

root.mainloop()
##################################

I guess this is not perfect though, and you will probably also want
handlers for copy-and-paste'ing text.

Best regards

Michael


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

It is a human characteristic to love little animals, especially if
they're attractive in some way.
		-- McCoy, "The Trouble with Tribbles", stardate 4525.6


More information about the Tkinter-discuss mailing list