Search code examples
python-3.xtkinterselectiontkinter-entry

How to get the start and end index of the selection in a Tkinter entry widget?


This question asks about getting the text selected but I was wondering how you can get the indexes of the start and end of the selection. Effbot mentions ANCHOR here but not the method in which you would use it. get and selection_get don't take any additional arguments so I don't know how to use it. I can't use the position of the cursor and length of selection because it could be on either side of the cursor and I can't use the index method since there could be multiple instances. Any suggestions?


Solution

  • You can use the index method to return the index of the beginning and end of the selection with the index "sel.first" and "sel.last".

    entry=tk.Entry(...)
    ...
    selection = (entry.index("sel.first"), entry.index("sel.last"))
    

    Note: "sel.last" refers to the character just after the selection. Also, these indexes will cause an error to be thrown if used when there is nothing selected.