tcl/tk 编程中的算术命令

arithmetic commands in tcl/tk programming

我正在 tcl\tk 编程。 代码显示以下错误:

"missing operand at _@_
in expression "+_@_""
entry .e1 -textvar a
entry .e2 -textvar b
message .m -textvar c
button .b -text "press here" -command "set c [expr $a+$b]"

错误显示在最后一行。我在 tclsh 中 运行 它并显示相同的错误。我也试过在函数 proc 中使用它,但弹出同样的错误。 我正在尝试使用 tk 进行算术运算。

当解释器评估第 4 行时,它会扩展引用部分的内容,并将执行 expr 命令并扩展 ab 的内容。但是,这些变量在那个时间点没有价值。您打算在用户单击按钮时评估该命令,但在创建按钮时正在评估它。

您需要快速修复:

button .b -text "press here" -command {set c [expr {$a + $b}]}

假设 ab 是全局的,因为单击按钮时将在全局命名空间中评估命令。

较长的修复方法是您需要非常仔细地阅读 Tcl man page 并注意 Tcl 中引用 "" 和分组 {} 表达式之间差异的描述。