4

I've been working on text widget using tkinter. My requirement is to restrict the functionality of Copy(ctrl+c), Paste(ctrl+v) and backspace. It's like once entered into the text widget there is no editing like clearing, and adding from somewhere. The user has to type and cannot backspace.

self.inputfeild = tk.Text(self, bg="White")
self.inputfeild.pack(fill="both", expand=True)

This is my Text widget which was declared inside a class.

flaxel
  • 4,173
  • 4
  • 17
  • 30
Poojitha
  • 43
  • 1
  • 5

2 Answers2

5

You can use event_delete method to delete virtual event associated with it.

eg:

inputfield.event_delete('<<Paste>>', '<Control-v>')
inputfield.event_delete('<<Copy>>', '<Control-c>')

Check out more Here

Or you can simply bind that event to an event handler and return 'break' like this:

from tkinter import *


root = Tk()

inputfield = Text(root, bg="White")
inputfield.pack(fill="both", expand=True)

inputfield.bind('<Control-v>', lambda _: 'break')
inputfield.bind('<Control-c>', lambda _: 'break')
inputfield.bind('<BackSpace>', lambda _: 'break')


root.mainloop()
JacksonPro
  • 3,135
  • 2
  • 6
  • 29
  • This is exactly like how I wanted, thanks so much! – Poojitha Dec 28 '20 at 05:55
  • I discovered that event_delete deletes the virtual event EVERYWHERE, not just on the inputfield. (It resolves to the tcl command, "event delete," which is not attached to a specific widget path.) The "break" technique, however, worked for me. – LionKimbro May 27 '22 at 10:56
0

In addition to @JacksonPro 's answer, you could also try this approach,

from tkinter import *

def backspace(event):
    if text.tag_ranges(SEL):
        text.insert(SEL_FIRST,text.get(SEL_FIRST, SEL_LAST))
    else:
        last_char=text.get('1.0','end-1c')[-1]
        text.insert(END,last_char)

root=Tk()
text=Text(root)
text.pack()

text.bind('<KeyRelease>', lambda event=None:root.clipboard_clear())
text.bind('<KeyPress>', lambda event=None:root.clipboard_clear())
text.bind('<BackSpace>', backspace)

root.mainloop()

This basically will clear your clipboard everytime you perform a KeyPress or a KeyRelease and hence copying/pasting will not be possible. The backspace() function obtains the last character and re-inserts it at the last position wherever backspace is used and indirectly restrics it's function. My previous appreach to backspace() wasn't right since it didn't take selection into account, but now it should work in all the cases, if there is something selected, it will obtain the selected text and insert it at the beginning of the selection (SEL_FIRST) else it will just obtain and reinsert the last charecter.

astqx
  • 2,058
  • 1
  • 10
  • 21