TCL:如何在文件中转储多个唯一列表框选择
TCL: How to dump multiple unique listbox selection in a file
在ListBox
中,我想查看用户选择的项目名称。 ListBox
允许多选。我尝试编写一个代码来跟踪光标选择,但我遇到了以下问题。
- 文件中只打印最后一项,并且
- 查询
puts
语句时,每个新选择都会打印先前的选择。
这是我的代码
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
包含以下项目:
- 美国
- 英国
- 新西兰
- 澳大利亚
- 印度
- ...
感谢您的意见。
问题是您使用 "w" 权限打开文件,这会导致之前的内容被覆盖。
有几个解决方案。首先,您可以使用 "a"(追加)模式打开。或者,您可以在循环之前打开它并在循环中写入它,或者您可以在循环中构建一个字符串,然后在循环结束时写入一次。
例如:
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
}
在ListBox
中,我想查看用户选择的项目名称。 ListBox
允许多选。我尝试编写一个代码来跟踪光标选择,但我遇到了以下问题。
- 文件中只打印最后一项,并且
- 查询
puts
语句时,每个新选择都会打印先前的选择。
这是我的代码
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
包含以下项目:
- 美国
- 英国
- 新西兰
- 澳大利亚
- 印度
- ...
感谢您的意见。
问题是您使用 "w" 权限打开文件,这会导致之前的内容被覆盖。
有几个解决方案。首先,您可以使用 "a"(追加)模式打开。或者,您可以在循环之前打开它并在循环中写入它,或者您可以在循环中构建一个字符串,然后在循环结束时写入一次。
例如:
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
}