tags:

views:

523

answers:

1

I am new to tcl/tk programming. Here is a small code snippet on combo box. How can I dynamically add and remove values from the combo box?

set ff [ frame f]
set label [Label $ff.label -text "Name:" ]

set name [ComboBox $ff.name \
        -editable yes \
        -textvariable name]

set addButton [Button $ff.addButton -text "+" -width 1 -command {addNameToComboBox}]

set removeButton [Button $ff.removeButton -text "-" -width 1  -command removeNameFromComboBox}]    

grid $ff.addButton  -row 0 -column 2 -sticky w
grid $ff.removeButton  -row 0 -column 3 -sticky sw -padx 5

proc addNameToComboBox {name} {

}

proc removeNameFromComboBox {name} {

}

Cheers!

+3  A: 

Your example code has a few bugs (*), and it's not entirely clear what you want to do. Are you wanting to add the current value of the combobox to the dropdown list, or is the value you want to add coming from somewhere else?

Here's a solution that adds the current value of the combobox to the list. It uses the built-in versions of the combobox, label and button widgets. Whatever combobox widget you are using probably works similarly, though maybe not exactly.

(*) Button, Label and ComboBox aren't standard widgets -- did you mean "button", "label" and "ttk::combobox" or are you using some custom widgets?. Also, you forgot to use grid to manage the combobox and label, and your procs are expecting arguments but you aren't passing any in).

This solution works with tcl/tk 8.5 and the built-in ttk::combobox widget:

package require Tk 8.5

set ff [frame .f]
set label [label $ff.label -text "Name:" ]
set name [ttk::combobox $ff.name -textvariable name]
set addButton [button $ff.addButton -text "+" -width 1 \
    -command [list addNameToComboBox $name]]
set removeButton [button $ff.removeButton -text "-" -width 1 \
    -command [list removeNameFromComboBox $name]]
grid $label $name
grid $ff.addButton -row 0 -column 2 -sticky w 
grid $ff.removeButton -row 0 -column 3 -sticky sw -padx 5
pack $ff -side top -fill both -expand true

proc addNameToComboBox {name} {
    set values [$name cget -values]
    set current_value [$name get]
    if {$current_value ni $values} {
        lappend values $current_value
        $name configure -values $values
    }
}

proc removeNameFromComboBox {name} {
    set values [$name cget -values]
    set current_value [$name get]
    if {$current_value in $values} {
        set i [lsearch -exact $values $current_value]
        set values [lreplace $values $i $i]
        $name configure -values $values
    }    
}
Bryan Oakley