【问题标题】:Delete string in file based on entry input TCL根据条目输入TCL删除文件中的字符串
【发布时间】: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],您可以更高效、更易读地执行第三行中的操作。

标签: tcl tk


【解决方案1】:

当您使用 dep 过程删除字符串时,您将新字符串保存在变量 filedat2 中。

全局变量filedat永远不会改变。

如果您想从全局变量中删除字符串,您必须将此变量传递给 regsub,而不是 filedat2

regsub -all $st $filedat "" filedat

或者,如果您希望将其保存在时间变量中以执行一些测试,您可以使用 filedat2 然后再次分配该变量:

regsub -all $st $filedat "" filedat2
# ... the tests
if {[isOk]} {
    # update the variable
    set filedat $filedat2
} else {
    # leave the previous value
    puts "some error here"
}

【讨论】:

  • 要获得匹配 Tcl 中任意文字的正则表达式,prefix it by ***=
  • @DonalFellows 非常感谢,我不知道这个。实际上,我总是将 reg exp 与 regexp 和 regsub 一起使用。
猜你喜欢
  • 2016-11-17
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多