Home > Software engineering >  Copying and pasting text displayed on tkinter text widget
Copying and pasting text displayed on tkinter text widget

Time:07-21

I have a tkinter interface with a text widget that displays, "ABCDEF". I would like to be able to copy and paste this text using ctrl c and ctrl v, respectively. I would also like to prevent any other key from altering the text (backspace, spacebar, basically any key besides ctrl c and ctrl v).

To accomplish this task, I tried an approach found here (the very last block of code): https://www.delftstack.com/howto/python-tkinter/how-to-make-tkinter-text-widget-read-only/

This code did not allow to copy and paste via the shortcuts. It is shown below. I would like to know how to copy and paste the text displayed by the text widget using the shortcuts, while also not allowing other keys to alter the text. Any help would be appreciated.

import tkinter as tk


def ctrlEvent(event):
    if 12 == event.state and event.keysym == 'C':
        return
    else:
        return "break"


root = tk.Tk()
readOnlyText = tk.Text(root)
readOnlyText.insert(1.0, "ABCDEF")
readOnlyText.bind("<Key>", lambda e: ctrlEvent(e))
readOnlyText.pack()

root.mainloop()

CodePudding user response:

The way you have the code it already does not allow other keys to edit the text box. Below has the detection for <ctrl-c> and added a detection for <ctrl-v>. It also has the functionality for each.

Use the method selection_get() on a text box to get highlighted text from a text box.

Then clear the clipboard and append the desired contents from the text box with root.clipboard_clear() and root.clipboard_append(content).

Then retrieve items from the clipboard with root.selection_get(selection='CLIPBOARD').

import tkinter as tk


def ctrlEvent(event):
    if event.state == 4 and event.keysym == 'c':
        content = readOnlyText.selection_get()
        root.clipboard_clear()
        root.clipboard_append(content)
        return "break"
    elif event.state == 4 and event.keysym == 'v':
        readOnlyText.insert('end', root.selection_get(selection='CLIPBOARD'))
        return "break"
    else:
        return "break"


root = tk.Tk()
readOnlyText = tk.Text(root)
readOnlyText.insert(1.0, "ABCDEF")
readOnlyText.bind("<Key>", lambda e: ctrlEvent(e))
readOnlyText.pack()

root.mainloop()
  • Related