tcl - 如何存储按钮按下的值?
问题描述
例如,我想将一个按钮按下的值存储到一个变量中,这样我就可以为所有三个按钮使用一个 proc,并执行特定于每个变量值的操作,而无需重复代码。
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"
正好等于这个
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]
}
即使在此示例中没有区别。
推荐阅读
- javascript - 获取 JavaScript 类构造函数的源代码
- operating-system - 从给定页表的逻辑地址中查找物理地址
- http - 如何在 http 中使用 VLC 将视频流式传输到其他计算机
- reactjs - 如何使用 React 创建响应式搜索过滤器
- python - 使用来自 Tensorflow 数据集的 load() 方法加载数据集的一部分
- docker - containerd 中 docker 卷的等价物是多少?
- php - MongoDB\Driver\Manager' 未使用 php 找到
- c# - 在 C# 中过度使用 Sql Connections 是一个问题吗?
- sql - 如何排除具有相似列的行?
- excel - 从具有过滤行的单个源书中填写另一个工作簿中的特定单元格