Note that there are some explanatory texts on larger screens.

plurals
  1. POtkinter prevent deletion of selected text with return key
    primarykey
    data
    text
    <p>I am implementing a tkinter text widget based console application and as a part of auto complete feature, I am observing one problem that on pressing return key results in the deletion of the selected text. Below example shows the similar problem :</p> <pre><code>from Tkinter import * def getCommand(*args): global text text.insert(END, "\n") text.insert(END, "command&gt;") x = text.get("1.0",END) print "command is %s" %(x) return 'break' def handle_keyrelease(event): global text if event.keysym == "Return": text.tag_remove(SEL,"1.9",END) text.mark_set("insert",END) getCommand() return 'break' root = Tk() text = Text(root) text.pack() text.insert(END,"command&gt;") text.focus() text.bind("&lt;KeyRelease&gt;", handle_keyrelease) text.insert(END,"sometext") text.tag_add(SEL,"1.9",END) text.mark_set("insert","1.9") root.mainloop() </code></pre> <p>In this code, when I hit the return key, I want to get the complete command <code>sometext</code>, however with the current code only <code>s</code> is retrieved. I have tried setting the cursor position to end and deletion of selection tag when the return key event is recieved. </p> <p><em><strong>EDIT</em></strong></p> <p>Problem with <code>KeyPress</code> event handler :</p> <pre><code>from Tkinter import * def getCommand(*args): global text text.insert(END, "\n") text.insert(END, "command&gt;") x = text.get("1.0",END) print x 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 == "Return": text.tag_remove(SEL,"1.9",END) text.mark_set("insert",END) getCommand() return 'break' if event.keysym in validkeysymchars: for x in ['testcommand']: strtocmp = text.get("MARK","end") strtocmp = strtocmp.encode('ascii','ignore') strtocmp = strtocmp.strip() print strtocmp 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&gt;") text.mark_set("MARK",INSERT) text.mark_gravity("MARK",LEFT) text.focus() text.bind("&lt;KeyPress&gt;", handle_keyrelease) root.mainloop() </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload