简体   繁体   中英

Copying and pasting text displayed on tkinter text widget

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()

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
    elif event.state == 4 and event.keysym == 'v':
        readOnlyText.insert('end', root.selection_get(selection='CLIPBOARD'))
    else:
        return


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

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM