Skip to content

tcltk: Difficulties creating menus

3 messages · Dirk Eddelbuettel, Peter Dalgaard

#
I am struggling with adding menus to a tcltk application. The following
example (from the O'Reilly book on Perl/Tk) works fine:

#!/usr/bin/perl -w
use Tk;
my $mw = MainWindow->new;
$menub = $mw->Menubutton(-text => "Color")->pack();
foreach (qw/red yellow green blue grey/) {
  $menub->radiobutton(-label => $_, -command => \&set_bg,
                      -variable => \$background_color, -value => $_);
}
MainLoop;
sub set_bg {
  print "Background value is now: $background_color\n";
  $mw->configure(-background => $background_color);
}

I cannot get anything similar to work under R. Adding a tkmenubutton is
easy, but I fail to get it to "connect" to an actual menu composed of 
check or radiobuttons:

library(tcltk)
color<-"blue"
tt <- tktoplevel()
tkpack(mb <- tkmenubutton(tt, text="Color"))
## does nothing
## tkradiobutton(mb, variable=color, text="blue", value="blue",
##              command=set.bg)
##
## Error: Error in .Tcl(.Tcl.args(...)) :
##  		[tcl] bad option "add": must be cget or configure.
## tkadd(mb, tkcheckbutton, label="blue", variable=color)
##
## Dito
## tkcmd("add", tkcheckbutton, label="blue", variable=color)
tkpack(tkbutton(tt, text="Quit", command=function()tkdestroy(tt)))

Any pointers or examples would be greatly appreciated.

Thanks,  Dirk
#
Dirk Eddelbuettel <edd at debian.org> writes:
Variables need special handling. You cannot just link to an R variable
(because they tend to move around in memory when you assign them) as
you can in Tcl or Perl/Tk. The convention is (for now anyway)

tkxxx(...., variable="color",....)
tclvar$color <- "blue"
-etc-

Also note that Perl/Tk does its own sneaky things with the control
language, in particular it bypasses the creation of a menu widget, to
make everything more object oriented.

The R interface would be closer to the Tcl:

library(tcltk)
tclvar$color<-"blue"
tt <- tktoplevel()
tkpack(mb <- tkmenubutton(tt, text="Color"))
m <- tkmenu(mb)
tkconfigure(mb,menu=m)
for ( i in c("red", "blue", "green"))
   tkadd(m, "radio", label=i, variable="color", value=i)

(And I was just getting to this bit for the Rnews paper that Kurt has
been nagging me for. Thanks...)
#
On Wed, Sep 19, 2001 at 11:44:22PM +0200, Peter Dalgaard BSA wrote:
[...]
Ah, yes, I modified / extended the tkttest example, but forgot that here.
Excellent. I had looked at tkmenu and tkadd but not figured out the
tkconfigure piece in between. Many thanks.
So there will be more documentation and examples? Even better :)

Thanks, Dirk