Rakesh Lyf Iz Jrny
Rakesh Lyf Iz Jrny

Reputation: 21

Drop down textbox in Tcl/Tk

  1. Here is a Database :

    apple     20
    mango     45
    banana    30
    

    I want to get these fruits name in a drop down text box.


  2. I have a text field to add fruits name into the Database.

    label .l1 -text "Fruits :" 
    entry .e1
    pack .l1 .e1
    label .l2 -text "Store :"
    entry .e2
    pack .l2 .e2
    button .b1 -text "OK" -command save
    pack .b1
    
    proc save {} {
        set fpR [read [open "abcd.txt"]]
        set fp [open "abcd.txt" w]
        puts $fp "$fpR\n[.e1 get]   [.e2 get]"
    }
    

    After adding new data without closing the GUI:

    apple     20
    mango     45
    banana    30
    guava     10
    

Now, after adding a fruit without closing the GUI, how can I get it in that drop down box ?

Upvotes: 0

Views: 1724

Answers (1)

Jerry
Jerry

Reputation: 71538

Here's a snippet (with your code changed as little as possible) which uses a combobox and adds fruits to it:

package require Tk

ttk::combobox .combo
pack .combo

# Set up proc to populate combobox
proc refresh_combo {} {
  # Set up channel to read file
  set fin [open abcd.txt r]
  # Get all fruit names in a single list
  set fruitList [lmap x [split [read $fin] "\n"] {if {$x != ""} {lindex $x 0} else {continue}}]
  close $fin
  .combo configure -values $fruitList
}

refresh_combo

label .l1 -text "Fruits :" 
entry .e1
pack .l1 .e1
label .l2 -text "Store :"
entry .e2
pack .l2 .e2
button .b1 -text "OK" -command add_fruits
pack .b1

proc add_fruits {} {
    # Open file to append new fruits
    set fp [open "abcd.txt" a]
    puts $fp "[.e1 get]   [.e2 get]"
    close $fp
    refresh_combo
}

Though it would probably be better to have your values tab delimited (or some other appropriate delimiter) in your text file. If you really want a database, you might look into sqlite which makes retrieval and updates easier.

Upvotes: 1

Related Questions