views:

172

answers:

2

Hello:

I feel that this question has a simple answer; but, for the life of me, I could not figure it out. I am trying to convert a listbox selection to its string element so I can enter it into a database.

I understand that I can use .listbox curselection to get its index; however, I need to convert it into its string. Can anyone help me with this?

Thank you,

DFM

+2  A: 

You should pickup a copy of Practical Programming in tcl and tk. I tis the "Camel Book" (to steal a perl idiom) of tcl/tk.

As to your question, what you want is:

set selectedText [list]
foreach selectedLine [$listbox curselection] {
     lappend selectedText [$listbox get $selectedLine ]
}
Byron Whitlock
Thanks Byron - I tried the code, but could not get it to work. I have not set i as a variable, so I cannot use $i. Cursorselection is unrecognized; albeit, I could probably use curselection. Lastly, the foreach statement has the wrong amount of args. Shouldn't it be: foreach {var...} $var {statement...}. If possible, could you elaborate. I tried a slew of alternatives with your suggestion, but with no luck.
DFM
It looks like the curselection and brace typos have been fixed above, but there's another issue. The "$i" in the last line should be "$selectedLine"
Jeff Godfrey
+2  A: 

Here's a simple, working example...

proc selectionMade {w} {
    # --- loop through each selected element
    foreach index [$w curselection] {
        puts "Index --> $index"
        puts "Text  --> [$w get $index]"
    }
}

catch {console show}
listbox .lb
bind .lb <<ListboxSelect>> {selectionMade %W}

pack .lb -fill both
.lb insert end "Line 1"
.lb insert end "Line 2"

So, [.lb curselection] returns a list of the indices of the selected elements. To turn an index into the actual text of the item, you just need to use it with the [.lb get $index] subcommand, as shown above.

Jeff Godfrey
Thanks Jeff - Your example worked perfectly. I only needed to use two lines.
DFM