TCL:如何在文件中转储多个唯一列表框选择

时间:2016-06-01 12:10:42

标签: tcl tk

ListBox中,我想检查用户选择的项目的名称。 ListBox允许多项选择。我尝试编写用于跟踪光标选择的代码,但是我遇到了以下问题。

  1. 只有最后一项打印在文件中,
  2. 查询puts语句时,每个新选择都会打印上一个选择。
  3. 这是我的代码

            package require Tk
            proc selectionMade {w} {
            ##     --- loop through each selected element
                     foreach index [$w curselection] {
                           #  puts "Index --> $index"
                                     set filename selected_list.list
                                     set fileId [open $filename "w"]
                                     puts "[$w get $index]"
                                     puts $fileId "[$w get $index]"
                                     close $fileId
                                         }
                                         }
    
              catch {console show}
              listbox .lb -selectmode multiple
              bind .lb <<ListboxSelect>> {selectionMade %W}
    
              pack .lb -fill both
              set filename fsp.txt
              set fp [open $filename "r"]
              set stuff [read $fp]
              foreach item $stuff {
              .lb insert end $item
            }
    
     close $fp
    

    假设我的输入文件fsp.txt包含以下内容:

    • 新西兰
    • 澳大利亚
    • 印度
    • ...

    感谢您的投入。

1 个答案:

答案 0 :(得分:1)

问题是您使用&#34; w&#34;打开文件。权限,导致以前的任何内容被覆盖。

有几种解决方案。首先,您可以打开&#34; a&#34; (追加)模式。或者,你可以在循环之前打开它并在循环中写入它,或者你可以在循环中构建一个字符串,然后在循环结束时写一次。

例如:

proc selectionMade {w} {
    set filename selected_list.list
    set fileId [open $filename "w"]

    foreach index [$w curselection] {
        puts $fileId "[$w get $index]\n"
    }

    close $fileId
}
相关问题