使用foreach循环创建按钮,然后将参数传递到一个按钮单击的过程中
我正在尝试在TCL中创建一些按钮。根据单击的按钮,我想将不同的参数传递给一个过程。
set cord_y 25
foreach {x but_name arg1 arg2} {1 button-1 val1 val2 2 button-2 val3 val4 3 button-3 val4 val5 4 button-4 val6 val7 5 button-5 val8 val9} {
button $a.$x -text $but_name -command {print $arg1 $arg2}
place $a.$x -x 20 -y $cord_y -width 80 -height 25
set cord_y [expr $cord_y+35]
}
proc print {i j} {
puts "$i--$j"
}
输出始终是Val8-val9,无论单击的按钮如何。 如何通过每个按钮调用来传递不同的参数。
谢谢你!
I am trying to create some buttons in tcl. Based on the button clicked I would like to pass different arguments to a procedure.
set cord_y 25
foreach {x but_name arg1 arg2} {1 button-1 val1 val2 2 button-2 val3 val4 3 button-3 val4 val5 4 button-4 val6 val7 5 button-5 val8 val9} {
button $a.$x -text $but_name -command {print $arg1 $arg2}
place $a.$x -x 20 -y $cord_y -width 80 -height 25
set cord_y [expr $cord_y+35]
}
proc print {i j} {
puts "$i--$j"
}
the output is always val8--val9 irrespective of the buttons clicked.
How do i pass different argument from each button calls.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题之所以在行中,
是因为
print
命令在{}
中包含arg1
和arg2
仅的值当命令运行时,被替换。您想要的是当命令定义时,将其替换。为了实现这一目标,您应该做(实际上在这种情况下,您可以使用
-command“打印$ arg1 $ arg2”
,但是如果arg1或arg2包含空格或其他特殊字符,那将失败。The problem is in the line
Because the
print
command is enclosed in{}
the values ofarg1
andarg2
only get substituted when the command is run. What you want is for them to be substituted when the command is defined. To achieve this you should do(Actually in this case you could just use
-command "print $arg1 $arg2"
but that would fail if arg1 or arg2 contained spaces or other special characters.)