简体   繁体   English

如何在 tkinter 的文本小部件中停止复制、粘贴和退格?

[英]How to stop copy, paste, and backspace in text widget in tkinter?

I've been working on text widget using tkinter.我一直在使用 tkinter 处理文本小部件。 My requirement is to restrict the functionality of Copy(ctrl+c), Paste(ctrl+v) and backspace.我的要求是限制 Copy(ctrl+c)、Paste(ctrl+v) 和退格的功能。 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.这是我在 class 中声明的文本小部件。

You can use event_delete method to delete virtual event associated with it.您可以使用event_delete方法删除与其关联的虚拟事件。

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:或者你可以简单地将该事件绑定到一个事件处理程序并像这样返回'break':

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

In addition to @JacksonPro 's answer, you could also try this approach,除了@JacksonPro 的回答,您还可以尝试这种方法,

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.这基本上会在您每次执行KeyPressKeyRelease时清除剪贴板,因此无法复制/粘贴。 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. backspace() function 获取最后一个字符并将其重新插入到最后一个 position 使用退格并间接限制它的 ZC1C425268E68385D1AB5074C17A94F1。 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.我之前对backspace()的应用是不正确的,因为它没有考虑到选择,但现在它应该适用于所有情况,如果选择了某些内容,它将获取所选文本并将其插入到开头选择( SEL_FIRST )否则它只会获取并重新插入最后一个字符。

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

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