首页 > 解决方案 > 如何存储按钮按下的值?

问题描述

例如,我想将一个按钮按下的值存储到一个变量中,这样我就可以为所有三个按钮使用一个 proc,并执行特定于每个变量值的操作,而无需重复代码。

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

标签: tcltk

解决方案


让您的处理程序命令带一个参数:

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"

正好等于这个

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]
...

或者

foreach color {Red Blue Green} {
    button .button$color -text $color -command [list popUpColor $color]
}

即使在此示例中没有区别。


推荐阅读