在 Python Tkinter 文本小部件中删除或 "Hidden" 文本

Elided or "Hidden" Text in a Python Tkinter Text Widget

根据 http://www.tkdocs.com/tutorial/text.html#more,在 Tk/Tcl 中可以在文本小部件中嵌入 "elided" 文本,该文本不会显示。这听起来很有用。此功能在 Python 中可用吗?如果是这样,API是什么?

下面的示例使用 tags:

生成了一个 Text 小部件,其中删除了文本
import tkinter as tk

root = tk.Tk()

text = tk.Text(root)
text.pack()

text.tag_config('mytag', elide=True)
text.insert('end', "This text is non-elided.")
text.tag_add('mytag', '1.13', '1.17')

def toggle_elision():
    # cget returns string "1" or "0"
    if int(text.tag_cget('mytag', 'elide')):
        text.tag_config('mytag', elide=False)

    else:
        text.tag_config('mytag', elide=True)


tk.Button(root, text="Toggle", command=toggle_elision).pack()

root.mainloop()

Furas 说得很对...解决方案很简单,只需将 elide=True 关键字参数传递给 tag_config() 方法即可。奇怪的是 elide 关键字没有记录在我能找到的任何 Tkinter 文档中。但是,最简单的方案是创建一个标签配置如下:

textWidget.tag_config('hidden', elide=True) # or elide=1

这将导致文本小部件中的标记文本为 "invisible" 或 "hidden"。您将无法在文本小部件中看到文本,但它仍然存在。如果您调用 textWidget.get('1.0', 'end - 1c'),您将看到该方法返回的文本中的隐藏字符。您还可以从 textWidget 中删除隐藏的字符,而无需查看它们。当您删除省略的字符时,您不会看到 INSERT 光标移动。有点奇怪...

请注意,标记的文本可以跨越多行,因此所有行都折叠在文本小部件中。测试时我首先想到的是,如果我正在实现源代码编辑器并想添加 "collapsing" 部分代码的功能(比如,在 if 块中),则省略文本将是我想要用来执行此操作的功能。

谢谢,弗拉斯!