sarbjit
sarbjit

Reputation: 3894

Text widget data getting cleared off while implementing auto complete feature

I am trying to implement auto complete feature using Python Tkinter. I am facing a very strange problem - when I get the auto complete text and while trying to input the same text, whole contents of the window disappears.

from Tkinter import *

def getCommand(*args):
    global text
    x = text.get("MARK",END)
    text.insert(END,"\n")
    text.insert(END,"command>")
    text.mark_set("insert",END)
    text.mark_set("MARK",INSERT)
    text.mark_gravity("MARK",LEFT)
    text.see(END)
    return 'break'

validkeysymchars = []
validkeysymchars = validkeysymchars + map(chr, range(65,91))
validkeysymchars = validkeysymchars + map(chr, range(97,123))

def handle_keyrelease(event):
    global text
    if event.keysym in validkeysymchars:
        for x in ['testcommand']:
            strtocmp = text.get("MARK","end")
            strtocmp = strtocmp.encode('ascii','ignore')
            strtocmp = strtocmp.strip()
            if x.startswith(strtocmp):
                currpos = text.index(INSERT)
                text.insert(END,x[len(strtocmp):])
                text.tag_add(SEL,currpos,"%s+%dc"%(currpos,len(x)-len(strtocmp)))
                text.mark_set("insert",currpos)  

root = Tk()
text = Text(root)
text.pack()
text.insert(END,"command>")
text.mark_set("MARK",INSERT)
text.mark_gravity("MARK",LEFT)
text.focus()
text.bind("<Return>",getCommand)
text.bind("<KeyRelease>",handle_keyrelease)
root.mainloop()

So in this code if you type t, widget will show testcommand as auto completed command, on hitting return key, if you type t, it will again show the same command but now on pressing any other character will cause the command from the previous step to be disappeared from widget. Can some one please explain why I am observing this kind of behavior.

Upvotes: 0

Views: 75

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

The default behavior of the text widget is to replace the selected text with the inserted text. What is happening is that you keep changing the selected text without first deselecting any other text, so when you type a letter, it deletes everything from the first character that has the SEL tag to the last character that has the SEL tag.

A simple solution is to clear the SEL tag before adding it to a new range of text:

...
text.tag_remove(SEL, "1.0", "end")
text.tag_add(SEL,currpos,"%s+%dc"%(currpos,len(x)-len(strtocmp)))
...

You might also want to remove it when the user presses the return key.

Upvotes: 1

Related Questions