Skip to content Skip to sidebar Skip to footer

Tkinter Copy-pasting To Entry Doesn't Remove Selected Text

When I copy some text and paste (crtl + v) it in a tkinter Entry , if there is selected text, it won't remove it from the entry. I'm on Linux (Mint) 64-bit. Here I copy 'd' with (c

Solution 1:

It's not a bug. If it were a bug, somebody would have noticed it and fixed it a decade ago. Tkinter has been around a long time, and fundamental things like this don't go unnoticed.

The implementation of paste on X11-based systems will not delete the selected text before pasting. The following is the actual underlying Tcl code as of the time I write this:

bind Entry <<Paste>> {
    global tcl_platform
    catch {
        if {[tk windowingsystem] ne"x11"} {
            catch {
                %W delete sel.first sel.last
            }
        }
        %W insert insert [::tk::GetSelection %W CLIPBOARD]
        tk::EntrySeeInsert %W
    }
}

Using the validation feature is definitely the wrong way to solve this. Validation is specifically for what the name implies: validation. The right solution is to create your own binding to the <<Paste>> event.

Now is there a way to get the index of selection in the entry? or another way to workaround this problem?

Yes, the entry widget has the special index sel.first which represents the first character in the selection, and sel.last represents the character just after the selection.

A fairly literal translation of the above code into python (minus the check for x11) would look something like this:

def custom_paste(event):
    try:
        event.widget.delete("sel.first", "sel.last")
    except:
        pass
    event.widget.insert("insert", event.widget.clipboard_get())
    return "break"

To have this apply to a specific widget, bind to the <<Paste>> event for that widget:

entry = tk.Entry(...)
entry.bind("<<Paste>>", custom_paste)

If you want to do a single binding that applies for every Entry widget, use bind_class:

root = tk.Tk()
...
root.bind_class("Entry", "<<Paste>>", custom_paste)

Post a Comment for "Tkinter Copy-pasting To Entry Doesn't Remove Selected Text"