我建议一种更简单的方法。您可以为窗口小部件设置代理,并在该代理内可以检测到何时插入或删除了任何内容。您可以使用该信息来生成虚拟事件,该虚拟事件可以绑定到任何其他事件。
让我们从创建一个自定义文本窗口小部件类开始,您将像其他任何文本窗口小部件一样使用它:
import Tkinter as tkclass 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本示例中的代理执行三件事:
- 首先,它调用实际的小部件命令,并传入它收到的所有参数。
- 接下来,它将为每个插入和每个删除生成一个事件
- 然后,它会生成一个虚拟事件
- 最后,它返回实际小部件命令的结果
您可以像使用任何其他Text小部件一样使用此小部件,并具有可以绑定到的附加优点
<<TextModified>>。
例如,如果要在文本小部件中显示字符数,可以执行以下操作:
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()


