Saturday, 16 May 2015

Changing The Colour Of Selected Text In Tkinter Text Wiget In Python

I am working on a simple chatbot program using Tkinter in Python 3 and have finished all the back end.
I'm now working on making the front end look pretty.

The Problem
One of the things I wanted to do was change the colour of the chatbot's title in the text widget to make it easier to read. I thought it would be pretty easy.
My guess was that I could modify the colour from the .insert method. A little like this:

text.insert(END,'Bottity Bottity Bot Bot: '+ BotInput + '\n',foreground='red')
Fail!!!
Life isn't that easy.

The Solution
It turns out that it is quite a task to add a colour to words in a text widget in Tkinter. The best hack I could find was to modify a search and highlight function I found in Python in a Nutshell by Alex Martelli.


I had to make some changes which basically removed the search function and replaced it with a key word of the name of my chatbot, in this case: Bottity Bottity Bot Bot

Here are the results in a simple example:

As you can see, the find() function searches for my chatbot name and then changes it's foreground color in the text.tag_config('found', foreground='red') section. in tag_config you can also modify the font styles and the background.

P.S. I really like the lastidx = '%s+%dc' % (idx, len(s)) variable. This was such a clever bit of code that I spent an hour down the rabbit hole on String Formatting Operations.

No comments:

Post a Comment