如何存储按钮的值按?

时间:2018-06-12 20:03:00

标签: tcl tk

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

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

3 个答案:

答案 0 :(得分:1)

让你的处理程序命令采用参数:

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"
如果$bar123,那么

就可以,但如果是{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]
}

尽管在这个例子中没有任何区别。

答案 1 :(得分:0)

找到另一种方式:

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
}

答案 2 :(得分:0)

正如答案所指出的那样,在命令字符串中添加参数是获得所需结果的方法,但您可能需要考虑使用单选按钮。如果你只想让一个选项可用,那么这是一个更好的控制,并且它有一个-textvariable选项,可以将结果存储在一个变量中,而无需编写辅助函数。

相关问题