Search code examples
pythontkintertextevent-handlingmouseevent

Preventing middle-clicking on selected text from copying and pasting in tkinter


I've noticed a "feature" of the Entry and Text widgets wherein any selected text will be duplicated (essentially copied and pasted) when middle-clicked. I'm trying to prevent this behavior, since I don't want or need it for my use case.

import tkinter as tk
from tkinter import ttk


root = tk.Tk()
root.geometry('240x60')
entry = ttk.Entry(root)
entry.insert(0, 'Select me, then middle click!')
entry.pack(expand=True, fill='x', padx=20, pady=20)


if __name__ == '__main__':
    root.mainloop()

I attempted to override the middle-click with an event binding, but that doesn't appear to prevent this behavior:

entry.bind('<Button-2'>, 'break')  # consume the middle-click event and bail

Solution

  • What I ended up doing was using the '<Button-2>' binding to clear the text selection, which seems to prevent the copy/paste

    entry.bind('<Button-2>', lambda _e: entry.selection_clear())
    

    I hope this helps anyone else who runs into this!


    Addendum: this behavior is also present on the ttk.Spinbox widget, and I suspect all widgets with editable text. I was able to avoid this problem globally with a similar binding on my root window

    root = tk.Tk()
    
    root.bind_all('<Button-2>', lambda e: e.widget.selection_clear())
    

    This way, any widgets with editable text won't exhibit this problem and you don't have to create separate event bindings for each.