I am trying to abstract my menu buttons and functions associated with it to a single proc call (addMenus function below). The following code builds the menu buttons correctly but on pressing the buttons (say Open) it errors out as:
Error: invalid command name “myputs Open”
- I think I am not using the quotes properly. Any pointers on fixing this?
- Also any suggestions on improving the code especially if I want to pass arguments to
menubuttonormenucommand?
proc myputs { label } {
puts $label
}
proc addMenus { mbar myargs } {
foreach { arg } $myargs {
foreach { button options } $arg {
set x ${mbar}.[string tolower ${button}]
set y ${x}.menu
menubutton $x -text $button -menu $y
pack $x -side left
set mdropoff [menu $y -tearoff 0]
foreach { label command } $options {
$mdropoff add command -label $label -command $command
}
}
}
}
#----------------------------------------
# main script
#----------------------------------------
wm title . "My Gui"
# build the frame which contains menu options
set mbar .mbar
frame $mbar -relief raised -bd 2
pack $mbar -side top -fill x
# text box as a filler
text .myout -width 40 -height 20
pack .myout -side top -fill both -expand true
# file menu
set myargs {
{
File {
"Open ..." { [list myputs "Open"] }
"New ..." { [list myputs "New"] }
"Save ..." { [list myputs "Save"] }
"Save As ..." { [list myputs "Save As"] }
}
}
{
Edit {
"Cut" { [list myputs "Cut"] }
"Copy" { [list myputs "Copy"] }
"Paste" { [list myputs "Paste"] }
}
}
}
addMenus $mbar $myargs
The issue is exactly that Tcl doesn’t do any expansion of scripts nested inside data structures like that (it can’t; it doesn’t know what they are until you tell it). There are a few possibilities for dealing with it:
myputs "Open"instead of[list myputs "Open"]in your data).Construct your data with
listthroughout:OK, it’s going to give you backslashitis (or very long lines).
Use a bit of trickery with
uplevelandsubst. From insideaddMenus…That’ll make your code otherwise look like what you expect (and expand any embedded variables in the calling context, which is usually what you want; if you never use variables in the menu description – or complex namespace handling – you can use a simpler
set command [subst $command]). But it is significantly trickier than anything you had before as you’re moving from simple calls to something more template-based.And if you’re wanting some substitutions to happen at one time and others at another, it’s time to use helper procedures: your brain (and anyone maintaining the code) will thank you.