You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 delete command targeting the selection range (sel.first to sel.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:01:28