Tcl 如何将textvariable传递到文件中

Tcl 如何将textvariable传递到文件中,tcl,tk,Tcl,Tk,我正在使用TCL/TK,有人能告诉我如何将文本变量传递到文件中吗 我尝试使用命令将textvariable直接传递到文件中 puts $fo myvariable 它只将my变量保存到文件中。如果您希望在文件为源文件时全局变量中存在一个值,只需在执行源文件之前设置变量即可: set myvariable "abc 123 xyz" source thefile.tcl 如果从程序内部执行此操作,则需要更加小心: proc example {variableValue fileName} {

我正在使用TCL/TK,有人能告诉我如何将文本变量传递到文件中吗

我尝试使用命令将textvariable直接传递到文件中

puts $fo myvariable

它只将my变量保存到文件中。

如果您希望在文件为
源文件时全局变量中存在一个值,只需在执行
源文件之前设置变量即可:

set myvariable "abc 123 xyz"
source thefile.tcl
如果从程序内部执行此操作,则需要更加小心:

proc example {variableValue fileName} {
    global myvariable
    set myvariable $variableValue
    uplevel "#0" [list source $fileName]
}
# Call like this: example "abc 123 xyz" thefile.tcl
如果要替换文件中的变量,可以使用:

proc substituteInFile {variableValue fileName} {
    # Read
    set f [open $fileName]
    set data [read $f]
    close $f

    # Do substitution(s) in memory
    set myvariable $variableValue
    set data [subst $data]

    # Write
    set f [open $fileName "w"]
    puts -nonewline $f $data
    close $f
}

我可以让你的代码工作,但我不喜欢

global myvariable
grid [label .myLabel -text "Label Widget" -textvariable labelText]
grid [text .myText -width 20 -height 5]
.myText insert 0.0 "Text\nWidget\n"
grid [entry .myEntry -background red -textvariable myvariable -foreground white]
grid [message .myMessage -background red -foreground white -text value]
grid [button .myButton1 -text "Button" -command "click"]
proc click {} {
  variable myvariable
  set fo [open "testo.txt" "w+"]
  toplevel .lvl2
  entry .lvl2.entry1 -textvariable myvariable
  puts -nonewline $fo $myvariable
  pack .lvl2.entry1
  close $fo
  exit
}
您的toplevel.lvl2无效,因为您的应用程序将在单击按钮时退出。

也许是时候阅读更多关于tcl的基础知识了。

我的代码如下所示。全局myvariable网格[label.myLabel-text“label Widget”-textvariable labelText]网格[text.myText-width 20-height 5]。myText插入0.0“text\nWidget\n”网格[entry.myEntry-背景红色-textvariable myvariable-前景白色]网格[message.myMessage-背景红-前景白-文本值]网格[button.myButton1-文本“button”-命令“click”]proc click{}{set fo[open“testo.txt”“w+”]toplevel.lvl2 entry.lvl2.entry1-文本变量myvariable put-nonewline$fo pack.lvl2.entry1 close$fo exit}在本例中,使用测试变量存储到输入表单中的值将存储到文件.global myvariable grid[label.myLabel-text“label Widget”-textvariable labelText]grid[text.myText-宽度20-高度5].myText insert 0.0“text\nWidget\n”grid中[entry.myEntry-background red-textvariable-myvariable-foreground white]grid[message.myMessage-background red-foreground white-text value]grid[button.myButton1-text“button”-command“click”]proc click{}{set of[open testo.txt”“w+]toplevel.lvl2 entry.lvl2.entry1-textvariable myvariable puts-nonewline$fo myvariable pack.lvl2.entry1 close$fo exit}