GaryMBloom
GaryMBloom

Reputation: 5682

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

According to http://www.tkdocs.com/tutorial/text.html#more, in Tk/Tcl it is possible to embed "elided" text in a Text widget, text that is not displayed. This sounds useful. Is this functionality available in Python? If so, what is the API?

Upvotes: 1

Views: 2487

Answers (2)

GaryMBloom
GaryMBloom

Reputation: 5682

Furas is quite right... The solution is as simple as the elide=True keyword arg passed to the tag_config() method. It's strange that the elide keyword is not documented in any Tkinter docs I can find. But, the simplest scenario is to create a tag config as follows:

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

This will cause the tagged text to be "invisible" or "hidden" in the text widget. You will not be able to see the text in the Text widget, but it is still there. If you call textWidget.get('1.0', 'end - 1c'), you'll see the hidden characters in the text returned by the method. You can also delete the hidden characters from textWidget without needing to see them. As you're deleting the elided characters, you won't see the INSERT cursor move. It's a bit odd...

Note that the tagged text can span multiple lines, so all lines are collapsed in the Text widget. The first thing I thought of while testing this was that, if I were implementing a source code editor and wanted to add the feature of "collapsing" part of the code (say, in an if block), elided text would be the feature I would want to be using to do that.

Thanks, Furas!

Upvotes: 2

Nae
Nae

Reputation: 15335

Below example produces a Text widget that has elided text in it, using tags:

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()

Upvotes: 3

Related Questions