简体   繁体   English

为什么我不能将 ctrl + v 与虚拟事件一起使用 tkinter 文本小部件 python

[英]why can i not use ctrl + v with a virtual event tkinter text widget python

i use a tkinter text widget and i have copied the script in this answer to bind a event for every change the text widget.我使用一个 tkinter 文本小部件,我已经复制了这个答案中的脚本来为每次更改文本小部件绑定一个事件。

the code for the text widget:文本小部件的代码:

"""I found this script here: https://stackoverflow.com/questions/40617515/python-tkinter-text-modified-callback"""
import tkinter as tk


class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        """A text widget that report on internal widget commands"""
        tk.Text.__init__(self, *args, **kwargs)

        # create a proxy for the underlying widget
        self._orig = self._w + "_orig"
        self.tk.call("rename", self._w, self._orig)
        self.tk.createcommand(self._w, self._proxy)

    def _proxy(self, command, *args):
        cmd = (self._orig, command) + args
        result = self.tk.call(cmd)

        if command in ("insert", "delete", "replace"):
            self.event_generate("<<TextModified>>")

        return result

now the problem is that when a paste some text in the text widget i get this error:现在的问题是,当在文本小部件中粘贴一些文本时,出现此错误:

Traceback (most recent call last):
  File "C:\Users\Gebruiker\PycharmProjects\mylanguage\main.py", line 91, in <module>
    app.mainloop()
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1429, in mainloop
    self.tk.mainloop(n)
  File "C:\Users\Gebruiker\PycharmProjects\mylanguage\customtext.py", line 17, in _proxy
    result = self.tk.call(cmd)
_tkinter.TclError: text doesn't contain any characters tagged with "sel"

Process finished with exit code 1

so i want i can paste some text without getting this error.所以我希望我可以粘贴一些文本而不会出现此错误。 can someone help?有人可以帮忙吗?

_tkinter.TclError: text doesn't contain any characters tagged with "sel"

You are getting an error when you do either delete or copy.当您删除或复制时,您会收到错误消息。 To solve problem.解决问题。 just add two tags one for get and one for delete .只需添加两个标签,一个用于获取,一个用于删除

Snippet code:片段代码:

def _proxy(self, command, *args):
    # avoid error when copying
    if command == 'get' and (args[0] == 'sel.first' and args[1] == 'sel.last'): return

    # avoid error when deleting
    if command == 'delete' and (args[0] == 'sel.first' and args[1] == 'sel.last'): return

    cmd = (self._orig, command) + args
    result = self.tk.call(cmd)

    if command in ('insert', 'delete', 'replace'):
                self.event_generate('<<TextModified>>')

    return result

Screenshot before:之前的截图:

在此处输入图像描述

Screenshot after ctrl+v: ctrl+v后截图:

在此处输入图像描述

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

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