TCL/TK How do I pass multiple arguments to a button call back function? - tcl

I have a code like this
proc press2 {v sbit} {
puts $v
puts $sbit
}
:
:
button .t.ok2 -text "OKI" -command "press2 $v $sbit"
with this I get the error wrong # args: should be "press2 v sbit"
if I change it to button .t.ok2 -text "OKI" -command {press2 $v $sbit} I get can't read "v": no such variable and finally I tried button .t.ok2 -text "OKI" -command [press2 $v $sbit] which doesn't give any errors but doesn't work also. Just asking is there any good documentation available for TCL/TK ? The usual man pages and googling isnt helping me much. I am doing much by trial and error.

Passing multiple arguments to a procedure is easy, but the "correct" way depends on what you want:
Early Binding: If you want to pass the current values later (e.g. if you create the widgets in a loop) you need to use list:
button .t.ok2 -text OKI -command [list press2 $v $sbit]
list creates a command that is free from any further substitution*.
Late Binding: If you want pass the value when this command is executed, simply brace it with {}
button .t.ok2 -text OKI -command {press2 $v $sbit}
The variables v and sbit are subsituted when the button is pressed. You only have access to global variables (or variables in a namespace, but not local variables).
* Tk's bind replaces % and a following character with something special. This is done using string substitution, not Tcl substitution, so list does not guard against this.

Related

How to use loop index variable inside command that will be invoked later

Let's consider the following code:
package require Tk
proc test {} {
foreach n {
1 2 3 4 5 6 7 8 9
} {
pack [button ._$n -text $n -command {puts $n}]
}
}
test
When one of the buttons invoked, "n" is unknown.
I found a away to address this by changing {puts $n} to "puts $n", but not sure this is a correct approach.
The callback for the button command is executed in the global scope, and there's no n variable there.
If you add global n command into that proc, then the error message won't appear, but each button will print the same value of n.
As you intent is to associate the value of n for each button, you need to pick a different quoting mechanism: braces prevent variable expansion. See https://www.tcl-lang.org/man/tcl8.6/TclCmd/Tcl.htm -- Shawn's comment gave you the answer.
You have to bind the current value of $n to the callback at the time you set it; your code as it stands uses whatever happens to be in the global n variable at the time that the callback is invoked (i.e., it is either the same for all the buttons or an error).
The list command is designed to be perfect for doing that binding; it generates a list, yes, but it also guarantees to generate a substitution-free command that has the words that are its arguments. That is, the script/command call:
eval [list $a $b $c]
is guaranteed to be the same as:
$a $b $c
for any values at all. This is an exceptionally useful property for almost any kind of code generation since it lets you make a script — that can be a call to a procedure for anything complicated — and pass any values over, entirely safely. In your case, this means that you should change change:
pack [button ._$n -text $n -command {puts $n}]
to:
pack [button ._$n -text $n -command [list puts $n]]
Thanks for your answers!
I ended up with the following possible ways:
"puts $n" - good for simple cases, but a bit non-intuitive
[list puts $n] - good, especially for lists
[subst {puts $n}] - good, straightforward substitution

How to keep display up to date to monitor options' values of a tk widget

I'm developing a tk window to monitor the value of certain options of a widget.
I know I can monitor the latest value of a scalar variable (please allow me to use the term 'scalar' in perl) simply by specifying the variable name as the value of label's -textvariable switch. However, when it comes to monitoring widget options, if I use this form, say .button1 cget -bg to refer to the background option of a button, I don't know how to update the display of this option's value automatically.
label .label1 -textvariable ____ # <-- what should I put here?
or should I use another command?
To track when a widget option is changed, the easiest way is probably to rename the widget command and put your own proc in its place. That proc just forwards the calls to the original command and then updates the label as necessary:
button .button1
rename .button1 __.button1
proc .button1 {method args} {
set rc [__.button1 $method {*}$args]
if {$method eq "configure"} {
.label1 configure -text [__.button1 cget -bg]
}
return $rc
}
You may need to add some cleanup code to delete your .button1 proc when the widget is destroyed (bind to the event).
This can also be made prettier when errors occur. But this is the basic method.
When the -textvariable option is set to something other than the empty string, it contains the name of a global variable that the label will display instead of the value of the -text option. To update the displayed value, you just write to the global variable; Tk's built-in machinery handles the rest.
In theory, you could use a variable trace to emulate the -textvariable option using the -text option:
# Emulating: label .lbl -textvariable foo
label .lbl
trace add variable foo write {apply {{name1 name2 op} {
# We ignore name2 and op
upvar 1 $name1 var
.lbl configure -text $var
}}}
However, this is a pain to keep on typing; much more convenient to use the short form!
(Yes, Tk widgets use traces to implement things like -textvariable, but they're the C API version of traces so you can't see them from Tcl code. There's a lot of complexity beneath the surface.)
If you want to watch something that is part of a composite value (as opposed to a simple variable or array element) then the easiest method is to use a trace.
trace add variable foo write {apply {args {
global foo displayed_foo_element
set displayed_foo_element [lindex $foo 1]
}}}
label .lbl -textvariable displayed_foo_element
Like this, every time the container of the thing that you care about (foo in the above code) is updated, the trace ensures that the displayed_foo_element variable is updated to follow, and the label can just watch that.
You can use much more complex ways of preparing the value for displayed_foo_element if you want. Perhaps like this:
set displayed_foo_element "foo\[1\] = '[lindex $foo 1]'"
Also, instead of writing to an intermediate variable you can instead update the -text option on the widget directly. This option is particularly useful if you also want to adjust other features of the widget at the same time:
if {[lindex $foo 0] >= $CRITICAL_VALUE} {
set color red
} else {
set color black
}
.lbl configure -text "foo\[1\] = '[lindex $foo 1]'" -foreground $color

Different methods to access value of an entry field in Tk

I am using following simple code to change label text:
#! /usr/bin/wish8.6
label .a_lab -text "Enter text: "
entry .ent -textvariable tt
button .a_button -text "Change" -command changer
pack .a_lab -fill both -expand 1
pack .ent -fill both -expand 1
pack .a_button -fill both -expand 1
proc changer {} {
.a_lab config -text $::tt ;# How can I access 'tt' using pathname '.ent'?
}
wm geometry . 300x200+300+300
Are there any other methods to access the value of 'tt' apart from '$::tt'?
You want .ent get.
The configure and cget subcommands to a widget are used to access a widget's own traits. The text content in an entry widget isn't intrinsic and shouldn't be accessed that way, but widgets often have a specific subcommand for any reasonable task one would want it to perform.
Note also that you can set both the label and the entry to use the same content variable, which gives you instant and automatic updates.
ETA: updating the label with processed content from the entry
Some widgets signal changes through a virtual event (listbox generates a <<ListboxSelect>> event, for instance). The entry widget doesn’t. To setup update triggers for the entry widget, you can:
bind the <Return> event to the entry widget: bind .ent <Return> +mycallback. This lets the Enter key trigger the update. The + can be omitted as there is no standard action for this event.
bind the <Key> event to the Entry class*: bind Entry <Key> +mycallback: any key will trigger an update, including editing keys. Note that if the event is bound to the widget, it fires before the keystroke edits the content of the entry. If you bind it to Entry but omit the +, the callback will be run instead of the usual action to edit the entry.
add a watching trace to the variable: trace add variable tt write {apply {args mycallback}}, or
hijack the validation mechanism: .ent config -validate key -validatecommand {.a_lab config -text [string toupper %P];expr 1}
The mycallback callback can be either
proc mycallback {} {
.a_lab config -text [string toupper [.ent get]]
}
or
proc mycallback {} {
.a_lab config -text [string toupper $::tt]
}
If you set the parameter list of the callback to args, you don't need to wrap it in apply when tracing. If you use the validation mechanism, read the docs so you know how it works (you should always do that, but it's really easy to get it wrong in confusing ways in this case).
Documentation:
apply,
bind,
entry,
trace
*) i.e. X Window class, not OOP class.

arithmetic commands in tcl/tk programming

I am programming in tcl\tk.
The code is showing following error:
"missing operand at _#_
in expression "+_#_""
entry .e1 -textvar a
entry .e2 -textvar b
message .m -textvar c
button .b -text "press here" -command "set c [expr $a+$b]"
The error is showing in the last line. I am running it in tclsh and showing the same error. I have also tried using it in function proc but the same error is popping up.
I am trying to do arithmetic operations using tk.
When the 4th line is evaluated by the interpreter it expands the contents of the quoted part and will execute the expr command with the contents of a and b expanded. However, these variables have no value at that point in time. You meant to evaluate that command when the user clicks the button but it is being evaluated when the button is created.
The quick fix is you need:
button .b -text "press here" -command {set c [expr {$a + $b}]}
provided a and b are global as the command will be evaluated in the global namespace when the button is clicked.
The longer fix is you need to read the Tcl man page quite carefully with attention to the description of the differences between quoted "" and grouped {} expressions in Tcl.

How to pass a variable value as an argument to -command option in tcl [duplicate]

button .mltext.button -text "Apply" -command {set top_tlbl [update_text $top_tlbl $spc ] }
I get an error :
can't read "spc": no such variable
while executing
"update_text $top_tlbl $spc "
invoked from within
".mltext.button invoke"
How can I pass the values of the variables to the update_text function?
Maybe I can start by understanding this :
(System32) 3 % expr 2 + 2
4
(System32) 4 % list expr 2 + 2
expr 2 + 2
(System32) 5 % [list expr 2 + 2]
invalid command name "expr 2 + 2"
(System32) 6 %
According to me, the last one should generate expr 2 + 2, which is the same as the first command - so, why does TCL have a problem?
Thanks..
In your examples with expr, we start by counting the words.
expr 2 + 2 has four words: expr, 2, + and 2. The first one is the command name, expr, and the others are passed as arguments; the documentation for expr says that it concatenates its arguments and evaluates the resulting expression.
list expr 2 + 2 has five words: list, expr, 2, + and 2. The first one is the command name, list, and the others are passed as arguments; the documentation for list say that it returns the list that has its arguments as elements. Though we don't see it here explicitly, what this does is introduce exactly the quoting needed to make a single substitution-free command. Good Tcl code uses list quite a lot when generating code.
[list expr 2 + 2] has one word, which is the result of calling list expr 2 + 2. If you just feed that into Tcl directly, it has a weird but legal command name, and you probably don't have a command called that. Hence you get an error.
Now let's consider:
button .mltext.button -text "Apply" -command {set top_tlbl [update_text $top_tlbl $spc]}
From your comments, you're calling this inside a procedure. This means that you need to bind the variables inside the callback (which is evaluated inside uplevel #0, and probably long after your current procedure has returned) without doing the callback immediately. Curiously, it looks like you're changing top_tlbl at runtime too.
Let's start by thinking about the innermost part. We can generate it with list just fine (ignoring the different lifetime bindings):
list update_text $top_tlbl $spc
Now we've just got to make the other parts work as well. That's where it gets fiddly and you end up with something like this:
… -command "set top_tlbl \[[list update_text $top_tlbl $spc]\]"
Now let's fix the lifetime stuff:
… -command "set top_tlbl \[update_text \$top_tlbl [list $spc]\]"
This sort of thing is more than a bit error-prone in complicated callbacks! At that point, it's much easier (and good practice) to have a little helper procedure:
proc do_update_text {varname value} {
upvar #0 $varname var
set var [update_text $var $value]
}
Then you can do (note: passing the name of top_tlbl, not the value):
… -command [list do_update_text top_tlbl $spc]
The use of global variable names might be considered to be problematic, except you've got to remember that the global namespace is mainly owned by your application. If you want to store variables in globals for your app, do it! You have the complete right.
Library code needs to be a bit more careful of course. The usual techniques there include using variables in other namespaces (Tk does this internally) or in objects. The code doesn't really get that much more complicated; it's still building on the practice of using helper procedures listed above. Passing a namespaced variable name is pretty easy though:
… -command [list do_update_text ::mynamespace::top_tlbl $spc]
-command {set top_tlbl [update_text $top_tlbl $spc]} will be invoked in global context when the button is clicked. Is your variable spc accessible in global context? Try to specify the variable's namespace explicitly, for example $::spc.
expr 2 + 2 and "expr 2 + 2" are not the same. Tcl identifiers can contain spaces and "expr 2 + 2" is the whole identifier, which is not found.
You should probably just call update_text and have top_tlbl be a global and set from the called function rather than returned.
Its generally simplest to just try and call a simple function and use list to ensure everything is quoted correctly.
button .mltext.button -text "Apply" \
-command [list update_text $top_tlbl $spc]
This will capture the current values of top_tlbl and spc when you define this button and its command. If you want the values at the time you press the button then you should probably be passing the names of the variables and using the variable or global commands.
Anyway, the rules are that things inside curly braces {} have no substututions performed on them. So {$v} is passed to the callee as exactly that - dollar v. Using list or double quotes lets variable substitution be performed and so you pass the value of the variable. List properly handles quoting for cases where the variable value might contain spaces and so on.