繁体   English   中英

如何使用不会在复制/粘贴时崩溃的代理来跟踪是否已修改tkinter文本窗口小部件?

[英]How do I track whether a tkinter text widget has been modified using a proxy that doesn't crash on copy/paste?

我使用了前面这个问题的以下解决方案来跟踪是否修改了tkinter文本小部件:

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


root = tk.Tk()
label = tk.Label(root, anchor="w")
text = CustomText(root, width=40, height=4)

label.pack(side="bottom", fill="x")
text.pack(side="top", fill="both", expand=True)


def onModification(event):
    chars = len(event.widget.get("1.0", "end-1c"))
    label.configure(text="%s chars" % chars)


text.bind("<<TextModified>>", onModification)

root.mainloop()

但是,在将它集成到我自己的代码中之后,我发现我的代码和上面的裸解决方案都存在问题。 如果您尝试粘贴到文本小部件中,整个程序将崩溃。 终端出现以下错误:

Traceback (most recent call last):
  File "Test.py", line 39, in <module>
    root.mainloop()
  File "AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1277, in mainloop
    self.tk.mainloop(n)
  File "Test.py", line 16, in _proxy
    result = self.tk.call(cmd)
_tkinter.TclError: text doesn't contain any characters tagged with "sel"

(我删除了上面文件路径中的识别信息,但是直接从控制台复制了这些信息。)

经过一些测试后,只要您在粘贴时选择/突出显示了一些文本,就可以粘贴而不会崩溃程序。

未修改的文本小部件中不会发生此行为; 您可以正常粘贴而不预先选择文本,不会崩溃。

所以,我的问题是,如何修改上面的解决方案,使粘贴不会崩溃呢? 我不熟悉Tcl / Tk,所以我不知道如何开始调查这个。 这是在Python 3.6.3中。

(我也会直接联系这段代码的原作者,但事实证明这里没有私人消息功能,我不能以新用户身份发表评论。)

编辑:我现在有工作代码,虽然解决方案感觉它与胶带一起保存,而不是实际解决潜在的问题。 我修改了CustomText类,如下所示:

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)
        self.bind("<<Paste>>", self.Paste)

    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

    def Paste(self, event):
        tagranges = self.tag_ranges("sel")
        if tagranges:
            selectionstart = self.index(tk.SEL_FIRST)
            selectionend = self.index(tk.SEL_LAST)
            self.delete(selectionstart, selectionend)
            self.mark_set(tk.INSERT, selectionstart)
        self.insert(tk.INSERT, root.clipboard_get())
        self.see(tk.INSERT)
        return "break"

通过将"<<Paste>>"绑定到以return "break"结尾的函数,我可以阻止小部件将事件传递给导致崩溃的任何内容,并且修改事件仍然按预期触发。 有趣的是,我可以编写自己的粘贴函数,它在return "break"行之前,并且它起到我认为应该从一开始就具有的作用。

仍然不知道是什么导致这个问题,除了它显然是一个Windows问题(感谢检查出来,布莱恩奥克利)。

您可以绑定事件"<Control-v>""<Control-c>"

这意味着如果用户使用其中任何一个,您可以设置一个特殊条件来以不同方式处理它。

from tkinter import *

root = Tk()

text = Text(root)
text.pack()

def callback(*args):
    print(True)

text.bind("<Control-v>", callback)

root.mainloop()

这更像是一种解决方法而不是解决方案,因为这会让您对我们不了解的其他键盘组合的潜在崩溃开放。

除非有人知道更好的解决方案,否则我会在此留下答案。

暂无
暂无

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

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