Matt
Matt

Reputation: 836

Formatted tkinter Text box

I'm trying to use the tkinter Text widget to implement some basic text formatting features. Bold, Underline, Italic, and a few font sizes.

I've got each of these things working by itself from this example Add advanced features to a tkinter Text widget but I'm finding that any formatting which uses the font keyword is mutually exclusive from any other that uses the font keyword.

For example: To implement "bold", I pre-create a tag which copies the default font of the text box, changes it to be bold, and then uses that as the font= argument of tag_configure. I do italic the same way, and also different font sizes. I don't see an easy way to have a "bold" button which when clicked will make the selected text bold, but keep all other features of its font (if it was previously made size 18 for example).

Is there any better way than pre-creating all possible combinations of font tags, and having a bunch of logic that decides which one(s) to apply to a selected section of text when a formatting button is clicked?

Upvotes: 2

Views: 2584

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385780

No, there is no way to combine the results of multiple font tags. If you want bold-italic, you'll have to create a bold-italic font in addition to a bold font and an italic font.

As for a better way than pre-creating all possible combinations, I suggest creating them on demand, the first time you need them. There's no reason to create a bunch of fonts that you may never need. This isn't a particularly hard problem to solve, it's just a bit tedious.

I would start with a function that can compute a canonical name for a font based on desired characteristics (eg: "bold-italic-18"). Next, write a function that creates a tag for that particular combination if one doesn't already exist, and then returns that tag name. Then it's just a matter of determining what attributes each character in a range should have, getting the tag, and applying the tag. Again, tedious, but not particularly hard.

While the tkinter text widget is pretty remarkable in what it can do and how easy it is to use, this is one area where it falls a little short.

Upvotes: 2

Related Questions