How can I dynamically populate the TK combobox values?

I am new to tcl / tk programming. Here is a small snippet of code in a combo box. How can I dynamically add and remove values ​​from a 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} {

}

      

Hooray!

+2


source to share


1 answer


There are several errors (*) in your example code and it's not entirely clear what you want to do. Do you want to add the current dropdown value to the dropdown, or the value you want to add from somewhere else?

Here is a solution that adds the current combobox value to the list. It uses inline versions of the combobox, label and button widgets. Regardless of which combobox widget you use, it probably works in a similar way, although perhaps not quite.

(*) Button, Label and ComboBox are not 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 combobox and label, and your procs expect arguments, but you don't pass them).



This solution works with tcl / tk 8.5 and the ttk :: combobox built-in 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
    }    
}

      

+4


source







All Articles