简体   繁体   English

复制和粘贴 tkinter 文本小部件上显示的文本

[英]Copying and pasting text displayed on tkinter text widget

I have a tkinter interface with a text widget that displays, "ABCDEF".我有一个带有显示“ABCDEF”的文本小部件的 tkinter 界面。 I would like to be able to copy and paste this text using ctrl+c and ctrl+v, respectively.我希望能够分别使用 ctrl+c 和 ctrl+v 复制和粘贴此文本。 I would also like to prevent any other key from altering the text (backspace, spacebar, basically any key besides ctrl+c and ctrl+v).我还想防止任何其他键更改文本(退格键、空格键,基本上除了 ctrl+c 和 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/为了完成这项任务,我尝试了一种在此处找到的方法(最后一段代码): https ://www.delftstack.com/howto/python-tkinter/how-to-make-tkinter-text-widget-read- 只要/

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> .下面有对<ctrl-c>的检测并添加了对<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.在文本框中使用方法selection_get()从文本框中获取突出显示的文本。

Then clear the clipboard and append the desired contents from the text box with root.clipboard_clear() and root.clipboard_append(content) .然后清除剪贴板并使用root.clipboard_clear()root.clipboard_append(content)从文本框中附加所需的内容。

Then retrieve items from the clipboard with root.selection_get(selection='CLIPBOARD') .然后使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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