tcltk-toolkit

Why do all Tk buttons in my script have the same command?


I am on Fedora, using Tcl9 and Tk.

Installed packages
tk.x86_64 1:9.0.0-4.fc42 fedora
tcl.x86_64 1:9.0.0-7.fc42 624cbc92582d4ecfae4c58749abde4f8

I want to create buttons that each do something different, but they all somehow end up doing the same thing.

My script:

package require Tk

wm title . "Button Command Test"
wm minsize . 350 300

set names {Anne Beth Clark Dave}

foreach name $names {
    grid [ttk::button .b$name -text $name -command {puts "My name is $name."}]
}

When pressing the buttons, I expect each button to output a different name. Instead, they all output "My name is Dave."

What am I missing here? How can I make the buttons work as expected without hardcoding them?


Solution

  • You have broken a quoting rule. { and } prevent variable substitution. To fix it, you need to construct the puts command list manually:

    grid [ttk::button .b$name -text $name -command [list puts "My name is $name."]]