【发布时间】:2016-08-05 08:19:25
【问题描述】:
我做了一个简单的程序,接受简短的用户输入并将它们存储在一个文件中。另一个按钮将文件中的每个输入显示为一个按钮。当我单击由字符串生成的按钮时,我正在尝试创建另一个删除按钮以及文件中的字符串的过程。我怎么做?我在保存值的变量上尝试了regsub,但它似乎删除了一次而不是每次都删除它们。
获取当前目录的代码
catch { set abspath [file readlink [info script]]}
if { ![info exists abspath]} { set abspath $argv0 }
if { [regexp {^(\S+)\/\S+} $abspath matched dir]} { set BIN $dir }
file mkdir $BIN/debug
if {[file exists $BIN/debug/debug.txt]} { close [open $BIN/debug/debug.txt "w"]}
界面代码
label .lbl -text "Enter something"
entry .en -justify center
button .sub -text "SUBMIT" -command "submit .en"
button .sho -text "SHOW" -command sho
button .cl -text "CLEAR" -command clear
grid .lbl -columnspan 3
grid .en -columnspan 3
grid .sub .sho .cl
提交程序
proc submit {ent} {
global BIN
if {![file isdirectory $BIN/debug]} { file mkdir $BIN/debug }
set input [$ent get]
if {$input == "" || [string is space -strict $input]} {
$ent delete 0 end
.lbl configure -text "No empty strings"
} else {
set fp [open $BIN/debug/debug.txt a+]
$ent delete 0 end
puts $fp $input
close $fp
}
}
清除程序
proc clear {} {
global BIN
if {[file exists $BIN/debug/debug.txt]} { close[open $BIN/debug/debug.txt "w"] }
}
为文件中的每个项目生成按钮的过程
proc sho {} {
global BIN
global filedat
set w.gui
if {[info exists filedat]} { set filedat "" }
toplevel $w
wm title "values"
wm overrideredirect $w 1
bind $w <Button-3> "destroy $w"
if {[file exists $BIN/debug/debug.txt]} {
set fp [open $BIN/debug/debug.txt r]
while {[gets $fp data] > -1} {
lappend filedat $data
}
close $fp
if {[info exist filedat]} {
set dcount 0
foreach item $filedat {
button $w.bn$dcount -text "$item" -font [list arial 10] -anchor w -fg white -bg black -command "del $item"
grid $w.bn$dcount -sticky w
incr dcount
}
} else {
label $w.nthLabel -text "Nothing in file" -bg black -fg white
grid $w.nthLabel
}
}
}
删除字符串的过程(目前未按预期工作)
proc del {st} {
global filedat
regsub -all $st $filedat "" filedat2
puts $filedat2
}
【问题讨论】:
-
使用
set BIN [file dirname $abspath],您可以更高效、更易读地执行第三行中的操作。