使用foreach循环创建按钮,然后将参数传递到一个按钮单击的过程中

发布于 2025-02-10 09:01:34 字数 496 浏览 2 评论 0原文

我正在尝试在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如此安好 2025-02-17 09:01:34

问题之所以在行中,

button $a.$x -text $but_name -command {print $arg1 $arg2}

是因为print命令在{}中包含arg1arg2仅的值当命令运行时,被替换。您想要的是当命令定义时,将其替换。为了实现这一目标,您应该做

button $a.$x -text $but_name -command [list print $arg1 $arg2]

(实际上在这种情况下,您可以使用-command“打印$ arg1 $ arg2”,但是如果arg1或arg2包含空格或其他特殊字符,那将失败。

The problem is in the line

button $a.$x -text $but_name -command {print $arg1 $arg2}

Because the print command is enclosed in {} the values of arg1 and arg2 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

button $a.$x -text $but_name -command [list print $arg1 $arg2]

(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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文