listbox selection

MGS [2003/08/10] - Setting a listbox's -exportselection option to 0 prevents the listbox selection from being exported (surprise!). It also prevents the selection being cleared when making another selection. Sometimes I like to be able to export the selection, but not have it cleared when selecting something else. Here's how to do it :

 # listsel.tcl --

 # Listbox selection handling.

 # ======================================================================

 proc listbox:select {W} {

   selection clear -displayof $W
   selection own -command {} $W
   selection handle -type UTF8_STRING \
     $W [list [namespace current]::listbox:handle $W]
   selection handle \
     $W [list [namespace current]::listbox:handle $W]

 }

 # ======================================================================

 proc listbox:handle {W offset maxChars} {

 # ----------------------------------------------------------------------

   set list {}
   foreach index [$W curselection] { lappend list [$W get $index] }

   set text [join $list \n]

 # ----------------------------------------------------------------------

   return [string range $text $offset [expr {$offset+$maxChars-1}]]

 }

 # ======================================================================

   # demo code
   listbox .l \
     -exportselection 0 \
     -selectmode extended \
     -yscrollcommand [list .y set]

   scrollbar .y -orient vertical -command [list .l yview]

   pack .l -side left -expand 1 -fill both
   pack .y -side left -expand 0 -fill y

   for {set i 1} {$i <= 20} {incr i} {
     .l insert end "This is listbox item $i"
   }

   bind .l <<ListboxSelect>> [list listbox:select %W]

   text .t
   pack .t -side left -expand 1 -fill both

Make a selection in the listbox, then you should be able to paste the contents of the selected lines into the text widget (for instance) or another application.


This is similar in principle to label selection.


Peter K: In case you looked for something different, here is a link to a different kind of listbox selection: I needed to select parameters for a plot from a list and ended up with a fake listbox, where you can drag entries to different boxes in order to select your plot parameters. See for yourself Sortbox


See also: