Tkinter Text Widget Ctrl+A + DEL 删除标签

Tkinter Text Widget Ctrl+A + DEL deletes tag

在文本小部件中,当我使用 Ctrl + A + DEL 删除所有文本时,标签已删除。

如何解决?

这是标记代码:

def _ingrandisci(self,event=None):
    BloccoNote._c+=1
    self._testo.tag_config("i", font=("Consolas", BloccoNote._c))
    self._testo.tag_add("i", "1.0", "end")
    self._testo.tag_raise("i")

您的观察有误。如果您配置一个标签然后删除所有文本,该标签仍然存在。您可以在其他文本上使用该标签,而无需重新创建标签。

如果您手动插入文本,它不会自动获取标签,因为 tkinter 无法知道要使用什么标签。 Tkinter 只会添加字符上插入点前后的标签。由于插入点之前或之后没有字符,因此新文本不会获得任何标记。

当您手动编辑文本小部件时,所有文本都会通过基础 insert 方法。 insert 消息的文档包括:

If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text.

注意:当您在文本小部件中按下某个键时,它会调用没有 tagList 的 insert 方法。例如,按键盘上的 "a" 键会导致 insert("insert", "a") (即:没有 tagList 参数)

Question: Text Widget Ctrl+A + DEL - Reset Formating

  1. 初始化您的 Text 对象。
    <Delete> 键绑定到一个函数。 我假设你已经完成了这一切。

    class Text(tk.Text):
        def __init__(self, parent):
            super().__init__(parent)
    
            # Binding Shortcuts
            self.master.bind("<Delete>", self.Delete_func)
    
  2. 删除所有时,将任何键盘输入绑定到set_default_tag函数。
    此函数在第一个 event.char.

    处未绑定
        def Delete_func(self, event):
            def set_default_tag(event):
                if event.char:
                    self.master.unbind('<Key>', self.Key_funcid)
    
                self.text.tag_add("i", "1.0", "end")
    
            self.text.delete('1.0', 'end')
            self.Key_funcid = self.master.bind('<Key>', set_default_tag)
    

测试 Python:3.5