tcltcltk

Add label text with different color in tcl/tk


label .f -text "Serial Number" -textvariable lbl -font {bold} -background #808080 
pack .f

Here, I want Serial with different color than Number with different color. How to do that?

Also, when I do :

set lbl "Stack Overflow is great"

I want all words in different colors.


Solution

  • The label widget can't do this on its own; by design it is extremely simple, and will only use one font and one colour for its text (at a time).

    The usual way of dealing with this is to use a text widget instead (with all scrolling disabled). That can do much more complicated things.

    text .t
    .t insert end "Serial " -tag word1
    .t insert end "Number: " -tag word2
    .t tag configure word1 -foreground "#660000"
    .t tag configure word2 -foreground cyan
    

    The downside is that making text widgets respond to a variable as in your second example is a lot more work. For example, you'll need