[Tutor] Fwd: Re: GUI for ANSI colors

Alan Gauld alan.gauld at yahoo.co.uk
Mon Feb 13 20:26:45 EST 2017


On 14/02/17 00:58, Alan Gauld forwarded:

> red = '\033[91m'
> yel = '\033[93m'
> blu = '\033[34m'
> grn = '\033[32m'

These are indeed the ANSI codes for the colours but ANSI
codes only work in an ANSI terminal and GUIs are not
ANSI terminals. Instead they have their own ideas on
colours and you need to use those. They all support
the standard 16 colours used in ANSI however, so in
your case (for Tkinter at least) just use the names
'red', 'yellow', 'blue' and 'green'

> colors = [red, yel, blu, grn]

colors = ['red', 'yellow', 'blue', 'green']


> final_word = ''.join(choice(colors) + char for char in word)

But again that won't work in a GUI, you need to use the GUIs
way of colouring. In Tkinter that's via tags as per my
previous post, reproduced here).

>     ###############################
>     from Tkinter import *
> 
>     n = 0
>     top = Tk()
>     t = Text(top, width=25, height=2)
>     t.pack()
> 
>     # set up tags for the colors
>     colors = ['red','blue','green']
>     for col in colors:
>         t.tag_config(col, foreground=col)
> 
>     def addWords():
>         n = 0
>         for word in "Hello ", "bright ", "world ":
>             t.insert(END,word,colors[n])  #use the color tags
>             n +=1
>

You need to change the loop to iterate over the letters
instead of words and choose the tags at random. But that
should be fairly straightforward.

>     Button(top,text="Add words",command=addWords).pack()
> 
>     top.mainloop()
>     ######################


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list