Tcl 如何存储按钮按下的值?

Tcl 如何存储按钮按下的值?,tcl,tk,Tcl,Tk,例如,我想将一个按钮按下的值存储到一个变量中,这样我就可以对所有三个按钮都有一个单独的过程,并执行特定于每个变量值的操作,而无需代码重复 button .buttonRed -text "Red" -command "popUpColor" button .buttonBlue -text "Blue" -command "popUpColor" button .buttonGreen -text "green" -command "popUpColor" 让处理程序命令获取一个参数: bu

例如,我想将一个按钮按下的值存储到一个变量中,这样我就可以对所有三个按钮都有一个单独的过程,并执行特定于每个变量值的操作,而无需代码重复

button .buttonRed -text "Red" -command "popUpColor"
button .buttonBlue -text "Blue" -command "popUpColor" 
button .buttonGreen -text "green" -command "popUpColor"

让处理程序命令获取一个参数:

button .buttonRed -text "Red" -command "popUpColor red"
button .buttonBlue -text "Blue" -command "popUpColor blue" 
button .buttonGreen -text "green" -command "popUpColor green"

proc popUpColor color {
    ...
}

请注意,引号不是字符串的语法,它们只是用于分组(一些引号:例如,
只是双引号中的文本字符)。那么这个

正好等于这个

button .buttonRed -text Red -command "popUpColor red"
您可以使用此选项稍微简化代码:

foreach color {Red Blue Green} {
    button .button$color -text $color -command "popUpColor $color"
}
但请注意,如果插入列表值,则将
-command
选项的值构造为简单字符串可能会有问题。比如说,

... -command "foo $bar"
如果
$bar
是,比如说,
123
,则可以,但如果它是
{1 2 3}
,则命令选项值将是
foo 1 2 3

因此,最好始终将调用值构造为列表:

... -command [list foo $bar]
变成
foo{1 2 3}

所以你应该使用

button .buttonRed -text "Red" -command [list popUpColor red]
...


尽管在本例中没有区别。

找到了另一种方法:

button .buttonRed -text "Red" -command "popUpColor .buttonRed"
button .buttonBlue -text "Blue" -command "popUpColor .buttonBlue" 
button .buttonGreen -text "green" -command "popUpColor .buttonGreen"

proc whatcolor { color } {
#some code here
}

在命令字符串中添加参数,正如答案所指出的,是获得请求结果的方式,但您可能需要考虑使用ReloButt。如果您只想从多个选项中选择一个选项,并且它有一个-textvariable选项来将结果存储在变量中,而不必编写帮助函数,那么它是一个更好的控件。

使用
list
构建命令。防止在传递复杂字符串时出现棘手的部分。请注意,命令脚本中的硬编码小部件路径将使维护代码变得更加困难。如果改为传递颜色名称,则更改后的代码更有可能仍然使用该名称。
foreach color {Red Blue Green} {
    button .button$color -text $color -command [list popUpColor $color]
}
button .buttonRed -text "Red" -command "popUpColor .buttonRed"
button .buttonBlue -text "Blue" -command "popUpColor .buttonBlue" 
button .buttonGreen -text "green" -command "popUpColor .buttonGreen"

proc whatcolor { color } {
#some code here
}