Aman Agrawal
Aman Agrawal

Reputation: 43

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.

Upvotes: 0

Views: 1060

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137707

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

  • a variable write trace so that things actually respond to variable changes,
  • to actually determine where the word boundaries are (in a way that means sense for your application),
  • a concrete strategy for assigning colours to words
  • some way to keep the whole thing under control (this isn't too bad if you're using a finite set of styles), and
  • to control exactly the size of the text widget as its content size changes; this is very much not its normal mode of operation, which is more focused on being a scrollable editable hypertext widget.

Upvotes: 1

Mayank
Mayank

Reputation: 2003

You have to first create a label of each word individually, and then pack them horizontally to get all the words in a different color. Also you can refer to this answer here

Upvotes: 1

Related Questions