Tkinter自定义Text组件Ctrl+V粘贴报错问题求助
Fix for Paste Error in CustomText Widget
The error occurs because when pasting text without an active selection, the widget attempts to delete the non-existent 'sel' (selection) range, which throws an unhandled TclError. The default Text widget's paste binding normally ignores this error, but the proxy intercepts the command and propagates the error instead.
Here's the corrected CustomText class that handles this case gracefully:
import tkinter as tk class CustomText(tk.Text): def __init__(self, *args, **kwargs): """A text widget that reports internal modification events""" 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): # Handle delete of non-existent selection to avoid paste errors if command == 'delete' and args == ('sel.first', 'sel.last'): # Check if there's an active selection if not self.tag_ranges('sel'): # No selection to delete, skip this command return None # Execute the original widget command cmd = (self._orig, command) + args result = self.tk.call(cmd) # Trigger modification event for text-changing commands if command in ("insert", "delete", "replace"): self.event_generate("<<TextModified>>") return result
What changed:
- Added a check before executing a
deletecommand targeting the selection range (sel.firsttosel.last) - If no selection exists (verified via
self.tag_ranges('sel')returning an empty tuple), we skip the delete command entirely - This matches the default Text widget's behavior of ignoring attempts to delete a non-existent selection during paste
This modification allows normal paste operations (both with and without an active selection) to work without throwing errors, while still maintaining the <<TextModified>> event generation for tracking text changes.
内容的提问来源于stack exchange,提问作者Jasper Bart
相关产品推荐
相关产品推荐

