[Tkinter-discuss] tag insertion while writing

Michael Lange klappnase at web.de
Wed Oct 5 18:33:07 CEST 2011


Hi again,

Thus spoketh Michael Lange <klappnase at web.de> 
unto us on Wed, 5 Oct 2011 16:48:13 +0200:

(...)
> The following appears to work here:
> 
(...)

I found a much better implementation here:

http://wiki.tcl.tk/4018

"Translated" into python this might look like:

####################
root = Tk()
t = Text(root, font='courier -14')
t.pack(fill='both', expand=1)
t.tag_configure('b', font='courier -14 bold')

def modTextInsert(event):
    if event.char == '' or event.widget['state'] == 'disabled':
        return
    try:
        if event.widget.compare('sel.first', '<=', 'insert') and \
                        event.widget.compare('sel.last', '>=', 'insert'):
            event.widget.delete('sel.first', 'sel.last')
    except TclError:
        pass
    event.widget.insert('insert', event.char,
                        event.widget.tag_names('insert-1c'))
    event.widget.see('insert')

for seq in root.bind_class('Text'):
    root.bind_class('modText', seq, root.bind_class('Text', seq))
root.bind_class('modText', '<Key>', modTextInsert)
t.bindtags((t, 'modText', t.winfo_toplevel(), 'all'))

def bold(event):
    t.tag_add('b', 'insert-1c')
def normal(event):
    t.tag_remove('b', 'insert-1c')
t.bind('<F1>', bold)
t.bind('<F2>', normal)

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

This seems to work quite well, except that the changed tag still
applies to the character left to the cursor and that still the handling of
<<Paste>> events is missing ;)

Regards

Michael


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

Lots of people drink from the wrong bottle sometimes.
		-- Edith Keeler, "The City on the Edge of Forever",
		   stardate unknown


More information about the Tkinter-discuss mailing list