I want to create labels that the text in them can be selected for copy/paste. To do this I tried to use entries that are read-only. But I can’t seem to initialize the text value in them. The labels are generated inside a loop and the number of labels and their content is unknown. The code to produce the labels is:
proc test_labels {} {
toplevel .labels
# Main Frame
frame .labels.main_frame -relief "groove" -bd 2
pack .labels.main_frame
set r 1
foreach t [list banana apple grapes orange lemon peach] {
set lbl [label .labels.main_frame.lbl_$r -text "fruit $r:"]
set lbl2 [label .labels.main_frame.val_$r -text $t]
grid $lbl -row $r -column 1 -sticky nse
grid $lbl2 -row $r -column 2 -sticky nsw
incr r
}
set ok_btn [button .labels.main_frame.ok_b -text "OK" -command {prop_menu_ok_button}]
grid $ok_btn -row [expr $r+2] -column 1 -columnspan 2 -sticky nsew
grab release .
grab set .labels
center_the_toplevel .labels
bind .labels <Key-Return> {test_labels_ok_button}
}
And it creates the fallowing window:

Then I try to replace the line set lbl2 [label .labels.main_frame.val_$r -text $t] with the lines:
eval "set text_val_$r $t"
eval "set lbl2 [entry .labels.main_frame.val_$r -relief flat -state readonly -textvar text_val_$r]"
But this only creates empty lines:

How can I put default values to entry widgets?
Related to the question How to make the text in a Tk label selectable?
These lines are almost certainly not what you want! (If you’re using
eval, you should always ask whether it’s really necessary; from 8.5 onwards, the likely answer is “it’s not necessary”.)The key problem — apart from the use of
eval— is that the-textvariableoption takes the name of a variable. Let’s fix that by using an array to hold the values:Also, be aware that the
text_valarray needs to be global (or in a namespace, if you fully qualify the name when giving it to the-textvariableoption). This is because it is accessed from places which are outside the scope of any procedure.Of course, it turns out that if we are keeping values constant then we can avoid using a variable at all and just insert the value manually.
If you’re never changing the value, that will work fine.