Path: news1.ucsd.edu!ihnp4.ucsd.edu!swrinde!nntp.primenet.com!news.mathworks.com!bloom-beacon.mit.edu!senator-bedfellow.mit.edu!faqserv
From: tja@cpu.com (Thomas J. Accardo)
Newsgroups: comp.lang.tcl,comp.answers,news.answers
Subject: FAQ: comp.lang.tcl Tk Toolkit Usage Questions And Answers (1/1)
Supersedes: <tcl-faq/tk/part1_842859583@rtfm.mit.edu>
Followup-To: comp.lang.tcl
Date: 16 Oct 1996 16:37:09 GMT
Organization: none
Lines: 1741
Sender: tja@cpu.com
Approved: news-answers-request@MIT.EDU
Expires: 29 Nov 1996 16:25:18 GMT
Message-ID: <tcl-faq/tk/part1_845483118@rtfm.mit.edu>
Reply-To: tja@cpu.com (Thomas J. Accardo)
NNTP-Posting-Host: bloom-picayune.mit.edu
Summary: A regular posting of the comp.lang.tcl Tk Toolkit usage
        questions and answers.
Keywords: tk, tcl, wish
X-Last-Updated: 1995/11/10
Originator: tja@cpu.com
Originator: faqserv@bloom-picayune.MIT.EDU
Xref: news1.ucsd.edu comp.lang.tcl:45106 comp.answers:16647 news.answers:66664

Archive-name: tcl-faq/tk/part1
Posting-Frequency: monthly
Version: 1.6
Last-modified: Nov 2, 1995

This FAQ will address commonly asked questions about usage of the Tk
Toolkit.  By providing answers to commonly asked questions in this
document, it is hoped that new users of Tk may suffer less frustration
getting started with Tk, and that readers of comp.lang.tcl may suffer
less frustration reading/answering these questions repeatedly.

This FAQ is posted monthly to comp.lang.tcl, comp.answers, and
news.answers and can also be obtained from the Tcl archive at
ftp.aud.alcatel.com (198.64.191.10) in the /tcl/docs directory.

For additional information on Tcl as well as pointers to other
documentation and code, see the FAQ maintained by Larry Virden
(lvirden@cas.org):
       "FAQ: comp.lang.tcl Frequently Asked Questions"
which resides on ftp.aud.alcatel.com as /tcl/docs/tcl-faq.part0*.gz.

For information on usage of the Tcl programming language, see the
posting by Joe Moss (joe@morton.rain.com):
       "FAQ: comp.lang.tcl Tcl Language Usage Questions And Answers"
which resides on ftp.aud.alcatel.com as /tcl/docs/tcl-faq-usage.gz.

Comments, suggestions, and contributions to this FAQ are welcomed
by tja@cpu.com.
___________________________________________________________________________


Index of questions:

I. Questions on building Tcl and friends on your system:
        Q1A. Is there anywhere I can find help with the details of getting 
                Tcl to work on my machine?
        Q1B. Why does the link step says that some of the functions Tcl,
                needs are missing when I am trying to build it?
        Q1C. Has anyone gotten Tcl to compile under HP-UX?
        Q1D. What does it take to get Tcl to compile under SCO Unix?
        Q1E. Why do I get format and scan errors when I run tclTest
                (NeXT, AIX, etc.)?
        Q1F. Why do I get lots of errors under Irix 4.0.1 when I run
                tclTest?
        Q1G. Does anyone else have problems with Tcl on a Cray?
        Q1H. Does anyone know how to get Tk to run on a SparcBook or other
                laptop with a limited number of colors?
        Q1I. What does it take to get Tcl/Tk to compile on 386bsd/Linux 
                or other POSIX/ANSI C systems not already supported?
        Q1J. Why do I get a parse error in tkInit.c when I try to compile
                Tk on my Irix machine?
        Q1K. Why am I getting errors on my SGI Indigo workstation?
        Q1L. How do I add BLT to a TclX/Tk ?
        Q1M. How do I port Tcl and Tk to a Sequent?
        Q1N. Why do I get invalid command name when I start wish?
        Q1O. How do I get around the symbol table full msg in A/UX?
        Q1P. Why doesn't the Makefile generated from xmkmf work on my
                SunOS system?

II.  Tk Questions and Answers - How can I:

        A. Question on starting Tk applications

        Q2.A.1. get my wish application to execute (I just get a wish prompt!)?
        Q2.A.2. ,using a machine with less than 8 bit color, run?
        Q2.A.3. set X11 resources for a wish application in an 
                app-defaults file?
        Q2.A.4. specify bitmap patterns on the command line instead of 
                as a file name?
        Q2.A.5. get a Motif user interface?
        Q2.A.6. get an OpenLook user interface?
        Q2.A.7. get Tk 3.3 (or later) to even start (I get security error messages)?
        Q2.A.8. call Tk scripts from a C program?
        Q2.A.9. get the geometry of my window (I get 1x1+0+0)?

        B. Questions on Tk applications and the keyboard

        Q2.B.1. change the default class bindings?
        Q2.B.2. delete a binding?
        Q2.B.3. bind the arrow key on my Sun keyboard?
        Q2.B.4. get root's mouse bindings to work in my Tk application?
        Q2.B.5. add new actions to an existing binding?

        C. Questions on Tk and X11 interactions

        Q2.C.1. get an application to also use libXt?
        Q2.C.2. change the X11 cursor?
        Q2.C.3. raise or lower a window?
        Q2.C.4. re-map a withdrawn window id?
        Q2.C.5. use Tk in a subwindow of a non-Tk X11 application?
        Q2.C.6. bind <Enter> and <Leave> to a frame containing other widgets?
        Q2.C.7. mix interactions between Xt and Tk/Tcl?
        Q2.C.8. bind the ResizeRequest event?
        Q2.C.9. avoid that 'bad geometry "+0+0": expected widthxheight'
                error message?
        Q2.C.10. ignore "send"s from other applications?
        Q2.C.11. tell the difference between 'wm' and 'winfo'?

        D. Questions on Tk listboxes

        Q2.D.1. resize a listbox?
        Q2.D.2. select two items that are not adjacent in the listbox at 
                one time?
        Q2.D.3. select items in more than one Tk listbox at a time?
        Q2.D.4. avoid fractional white space at the end of a resizable listbox?
        Q2.D.5. scroll two listboxes with one scrollbar?
        Q2.D.6. have a listbox only allow the selection of a single item
                at a time

        E. Questions on Tk canvases

        Q2.E.1. get output from a Tk canvas?
        Q2.E.2. fill a canvas which is bounded by lines as opposed to a
                shape like a polygon, oval, etc.?
        Q2.E.3. raise/lower canvas window objects or draw graphics onto a 
                window object inside a canvas?
        Q2.E.4. detect when the canvas has been resized?
        Q2.E.5. scroll a canvas an a listbox at the same time with 
                one scrollbar?
        Q2.E.6. use a list of coordinates in a variable to create a
                polygon (or any other item)?

        F. Other questions

        Q2.F.1. get the name of my own interpreter?
        Q2.F.2. get -relief to work on my text widgets?
        Q2.F.3. create a scrollable window of buttons?
        Q2.F.4. pack a text widget so that it can be resized interactively?
        Q2.F.5. create a widget with an upper case name?
        Q2.F.6. create equal sized buttons?
        Q2.F.7. vertically stack radio buttons aligning regardless of font?
        Q2.F.8. initialize an entry widget with some text?
        Q2.F.9. change the default colors in Tk?
        Q2.F.10. find my invisible windows when using the packer?
        Q2.F.11. destroy every window except '.'?
        Q2.F.12. group a set of radiobuttons together?

End of FAQ Index

----------------------------------------------------------------------

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1A- Is there anywhere I can find help with the details of 
                getting Tcl to work on my machine?

A1A. Glad you asked!  Look in the Tcl distribution for the file called
"porting.notes".  This will contain a collection of notes that various people
have provided about porting Tcl to various machines and operating systems.
There are also a file called "README" which should be read FIRST - before
doing anything else with the code (this should always be one's first
step with any package).  Finally, there is a "changes" file which details
what has changed since the last release - be sure to read this to see
what might need to change in your programs.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1B- Why does the link step says that some of the functions Tcl,
                needs are missing when I am trying to build it?

A1B. Did you run the "config" program first, by doing a "csh ./config" or
equivalent?  Without doing this, things such as strtoul or strerror
are sometimes mentioned as missing.

Tcl includes equivalents for at least the following functions and include files
which may not be found on some systems:

dirent.h       limits.h       stdlib.h       string.h

opendir.c      strerror.c     strstr.c       strtol.c       strtoul.c

strtod.c

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1C- Has anyone gotten Tcl to compile under HP-UX?

A1C. See the porting notes.  Also, be aware that there have been
some reports of Configure assuming that you should use the compatibility
version of opendir() and that you have no dirent.h .  This causes 
glob-ing to fail, as well as TclX's readdir, etc.

Changing tcl7.3 to remove the opendir compatibility file
and removing the -DNO_DIRENT, -DUSE_DIRENT2 fixed it all up.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1D- What does it take to get Tcl to compile under SCO Unix?

A1D. Add a "#undef select" to tkEvent.c, and remove the reference to 
TK_EXCEPTION around line 460 of main.c.

Tk uses its own scheme for allocating the border colors for its 3D
widgets, which causes problems when running TK on a system with
"PseudoColor" display class, and a 16-cell colormap.

If you can't go to eight bitplanes, you can instead start the server
with a "-static" (Xsco) or "-analog" (Xsight) option, making the
display class become "StaticColor".  This makes the entire colormap
read-only, and it will return the color that most closely maps to the
desired color as possible.

This information is from Keith Amann <Keith_Amann@stortek.com>

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1E- Why do I get format and scan errors when I run tclTest
                (NeXT, AIX, etc.)?

A1E. That's a problem (scanf/printf) many systems seem to have.  Don't
worry too much about it - just don't use these 'advanced' features.  If
you're hacking C, you'll have the same problems.

For instance, printf("%Ng, double_value) and strtod("+",&terminal) produce
incorrect results.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1F- Why do I get lots of errors under Irix 4.0.1 when I run
                tclTest?

A1F. There's a bug in the 4.0.1 optimizer that's fixed in 4.0.2.
Compile tclVar.c using -O0 (no optimization).

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1G- Does anyone else have problems with Tcl on a Cray?

A1G. See the porting notes for a set of changes mentioned.  Also,
Booker C. Bense <benseb@grumpy.sdsc.edu> reports that version 3.0.1.6
has some real problems with char pointers, causing Tcl to crash.  Using
version 3.0.2.1, things are much better, except for a minor formatting
problem and serious problems with scan.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1H- Does anyone know how to get Tk to run on a SparcBook or other
                laptop with a limited number of colors?

A1H. On a SparcBook, if you start openwin (the OpenWindows server starting
command) as:

openwin -dev "/dev/fb staticvis"

you get a static visual color model that Tk copes with better than the
default.  Some things are ugly, but not as ugly as monochrome.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1I- What does it take to get Tcl/Tk to compile on 386bsd/Linux 
                or other Posix/ANSI C systems not already supported?

A1I. Patches for 386BSD were posted to comp.lang.tcl back in Nov. 1992 to
alt.sources.  See one of the ftp archive sites for this group for them.
Basically, there were some setting of defines and a few places where 
const char * had to be used in place of char *.  

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1J- Why do I get a parse error in tkInit.c when I try to compile
                Tk on my Irix machine?

A1J. Jon Knight <J.P.Knight@loughborough.ac.uk> reports that the version of
Irix that he is using doesn't define a uid_t.  One needs to define one 
somewhere (or comment out the lines causing the problems) to get the compile
to continue.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1K- Why am I getting errors on my SGI Indigo workstation?

A1L. From Gordon Lack <gml4410@ggr.co.uk> we are told that
the SGI c compiler has some bugs with variable arguments.

tclVar.c must be compiled with -O0 at IRIX C 4.0.1 because of a
compiler bug with varargs.
 
   Done by placing specific rule into Makefile.
 
> # GGR SG needs -O0 for varargs at 4.0.1
>
> CC_SWITCHES0 =  -O0 -I. -I${SRC_DIR} ${AC_FLAGS} ${MATH_FLAGS} \
> ${GENERIC_FLAGS} ${PROTO_FLAGS} ${MEM_DEBUG_FLAGS} \
> -DTCL_LIBRARY=\"${TCL_LIBRARY}\"
>
> tclVar.o: tclVar.c
>         $(CC) -c $(CC_SWITCHES0) $<

Peter NEELIN <neelin@pet.mni.mcgill.ca> also noted that:

I get tclX 7.3a to compile on an SGI (irix 4.0.5) with the following
changes to the Config.mk file:
 
71c71
< CFLAGS=-cckr -D__GNU_LIBRARY__
---
> #CFLAGS=
106,107c106,107
< TCL_PLUS_BUILD=TCL_PLUS
< CCPLUS=g++
---
> #TCL_PLUS_BUILD=TCL_PLUS
> CCPLUS=CC
191,193c191
< MAN_DIR_SEPARATOR=
< 
< LIBOBJS=strftime.o
---
> #MAN_DIR_SEPARATOR=.
 
The -D__GNU_LIBRARY solves the srandom problem and I think that the -cckr gets
around the prototype error with waitpid (it's crude, but it works).
I've forgotten why I needed the strftime.
 
If you want the version of Config.mk that worked for me, send me mail.
 
------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1L- How do I add BLT to a TclX/Tk ?

A1M. From gah@grenache.mhcnet.att.com (George A. Howlett) we get
the answer:

Instead of adding TclX to blt_wish, try it the other way.  Add
BLT to wishx.  It's pretty simple.
 
In the file ./tksrc/tkXAppInit.c, add the a call to the BLT
initialization routine right after line 116.
 
    if (TkX_Init(interp) == TCL_ERROR) {
        return TCL_ERROR;
    }
    if (Blt_Init(interp) != TCL_OK)) {
        return TCL_ERROR;
    }
 
Link wishx with libBLT.a and that's it.
 
Others recommend the tkmkmf or make-a-wish packages.
 
------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1M- How do I port Tcl and Tk to a Sequent?
 
A1N.  From Andrew Swan <aswan@soda.berkeley.edu> we find:

> For both Tcl and Tk, I used gcc rather than the Sequent cc which is
> not ansi.
> 
> For Tcl, there were a couple of problems with the math library.  First,
> the Sequent math library doesn't include the 'fmod' function.  I got
> the source for fmod from ftp.uu.net, put it in the compat subdirectory,
> and added it to the Makefile.  fmod also wanted functions 'isnan' and
> 'finite' but I just commented those out since I don't believe tcl
> supports infinity and nan.
> 
> The other problem with the math library was that it has two copies
> of the 'tanh' function in it.  This is easy to fix by using "ar"
> to separate the library in to object files and then reconstruct
> it, leaving one of the copies of tanh out.
> 
> With those changes, Tcl compiled cleanly and passed all the tests
> except the scanning tests.  Apparently, the *scanf functions are
> broken in Dynix.  The problem is with recognizing the end of octal
> numbers, and I just let this problem go.  Fixing it would probably
> involve finding source to the *scanf functions and including it.
> 
> To compile Tk, I had to make a new version of stddef.h including
> things like wchar_t.  I just copied it in to another include directory
> and put that directory first and then tweaked the copy.  Tk also had
> the math library problem (tanh).  Other than those, however, everything
> compiled cleanly and passed all the tests.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1N- Why do I get invalid command name when I start wish?

A1O. Often when folks trying to build a new version of wish get done
and try to start it up, they get errors such as:

>$ /projects/xopsrc/wishx3.6a            
>Error: invalid command name "tk_bindForTraversal"
>invalid command name "tk_bindForTraversal"
>    while executing
>"tk_bindForTraversal Entry"
>    (file "/projects/xopsrc/Tclsrc/v7/lib/3.6a/tk.tcl" line 98)
>    invoked from within
>"source $tk_library/tk.tcl"
>    invoked from within
>"if [file exists $tk_library/tk.tcl] {
>            source $tk_library/tk.tcl
>        } else {
>            set msg "can't find $tk_library/tk.tcl; perhaps you "
>            append  ..."
>

The _real_ problem is, in all likelihood, that they do not have
something either configured or installed properly.  If the command name
is really valid, then auto_path isn't set right, an external variable
pointing to the directories is overriding the default location, or things
didn't install.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1O- How do I get around the symbol table full msg in AU/X 3.0?

A1P. After getting things compiled on AU/X, you have to be sure
to do the links with the -A {factor} arguments which expand the default
table allocations.  {factor} is the amount by which the compiler multiplies
the default allocation.  Try -A 2.  Contact
wkulecz@medics.jsc.nasa.gov (Walter B. Kulecz, PhD.) for more details
of his port.

------------------------------

From: -I- Questions on building Tcl and friends on your system
Subject: -Q1P- Why doesn't the Makefile generated from xmkmf work on my
                SunOS system?

A1Q. There are numerous problems users have reported when trying to use the
imake / xmkmf setup under OpenWindows.  Try asking over on comp.sys.sun.*
for more assistance on resolving this problem.  Note also that the problem
_might_ be someone expecting X11R6 imake rules to be present - if after
fixing all the known bugs in the imake templates, etc. you still have
problems, investigate that!

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.1- get my wish application to execute - I just get a
                wish prompt!  Or I just get error msgs about permission
                denied, not found, etc.

A2.A.1. Most systems require a full pathname to the interpreter.  
So you cannot start a wish script out as 

#! wish -f

Likewise, many Unix systems have a maximum length of characters that you can
put on a #! line.  If you exceed this, you do not get the behaviour you
expect.  So do not try to put something like:

#! /projects/somethingbig/bin/sun4/wish -f

followed by your wish code.  Keep the lines short - under 32 characters is
recommended.

kennykb@carla.crd.ge.com (Kevin B. Kenny) suggests starting your
scripts with the following:
  #!/bin/sh
  # This line makes the next one a comment in Tcl \
  exec /path/to/wish "$0" ${1+"$@"}

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.2- ,using a machine with less than 8 bit color, run?

A2.A.2. Tk doesn't behave very well with less than 8-bit color screens.  To
try to use it, find all the places in the Tk/wish source where 
DefaultDepthOfScreen is invoked to test the number of bit-planes.  Change all
of these to pretend there is just 1 bit-plane, or call a procedure which
monitors a Tcl variable so that it is configurable, and you should be okay.

Another alternative is to see if the server you are using has alternative
visual / color models, such as static visual, etc.  One of the alternatives
may allow Tk to work better.

Thanks to "Nathaniel Borenstein" <nsb@thumper.bellcore.com> for this info!

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.3- set X11 resources for a wish application in an 
                app-defaults file?

A2.A.3. Read the documentation for the option command.
Then you should consider something like the following - assume the program
name is xwf.

The following are two general purpose functions to put into a library:

# envVal envValName
#   Looks up the envValName environment variable and returns its
#   value, or {} if it does not exists
proc envVal {envValName} {
  global env
  if [info exists env($envValName)] {return $env($envValName)} {return {}}
}

# loadAppDefaults classNameList ?priority?
#   Searches for the app-default files corresponding to classNames in
#   the order specified by X Toolkit Intrinsics, and loads them with
#   the priority specified (default: startupFile).
proc loadAppDefaults {classNameList {priority startupFile}} {
  set filepath "[split [envVal XUSERFILESEARCHPATH] :] \
                [envVal XAPPLRESDIR] \
                [split [envVal XFILESEARCHPATH] :] \
                /usr/lib/X11"
  foreach i $classNameList {
    foreach j $filepath {
      if {[file exists $j/$i]} {
        option readfile $j/$i $priority; break
      }
    }
  }
}

# Now, here is what you would put into xwf:

option add Tk.BoldFont "*-lucida sans-Bold-R-Normal-*-100-*" widgetDefault
loadAppDefaults {xwf XWF} userDefault

This sets a program default, then load any defaults specified in the user's
default resources and finally any site or general app-defaults resource.  
Of course, you would want to add some xwf command line handling to allow 
the user to override things at execution time.

Chris Milam (address unknown) contributes the following modification
of loadAppDefaults which follows the X11R5 method of merging
app-default files from several sources.

# loadAppDefaults classNameList ?priority?
#   Searches for the app-default files corresponding to classNames in
#   the order specified by X Toolkit Intrinsics (R5), and loads them with
#   the priority specified (default: startupFile).
proc loadAppDefaults {classNameList {priority startupFile}} {
  set lang [envVal LANG]
  if {[string length $lang] > 0} { set lang /$lang }
  set filepath "\
                /usr/lib/X11${lang}/app-defaults \
                [split [envVal XFILESEARCHPATH] :] \
                [envVal XAPPLRESDIR]${lang} \
                [split [envVal XUSERFILESEARCHPATH] :] \
                "
  foreach i $classNameList {
    foreach j $filepath {
      if {[file exists $j/$i]} {
        option readfile $j/$i $priority;
      }
    }
  }
}

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.4- specify bitmap patterns on the command line instead of 
                just as a file name?

A2.A.4. You can not, using unextended Tk, at least as of June, 1992,
provide a pattern as an internal set of hex codes.  You must point to
an external file.  On the other hand, there are extensions which provide
the capability (BLT for one)>

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.5- get a Motif user interface?

A2.A.5. Tk does not currently use the Xt toolkit, so a strict adherence
to Motif via the libXm.a routines is not possible.  However, the authors
of Tk prefer the Motif style of user interface, so you will find that Tk
makes quite an attempt to implement a Motif-like interface.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.6- get an OpenLook user interface?

A2.A.6. Unfortunately, Tk does not currently use either XView or Xt based
widgets in its user interface, so an OpenLook compliant (or even
similar) interface is probably not easily achievable in the near future.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.7- get Tk 3.3 (or later) to even start - I get security
                  error messages.

A2.A.7.  Alternate forms of this question often mention that Tk 3.3 send
is broken, or ask how to use xauth.

Since Tk 3.3, the X11 xauth security mechanism is used.  While this
provides more security, it does require the user to do a bit more
setup.  The user needs to create an Xauthority file (typically
$HOME/.Xauthority) and then restart the X server with the
-auth argument, along with the name of the Xauthority file created.
Read the X11 documentation for your system for the details on how to
use xauth or comparable software to create the authority files needed.
An intro to xauth is available as
ftp://ftp.aud.alcatel.com/tcl/docs/Xauthority .

Also note that you can configure Tk to not depend on xauth by modifying
Makefile.in to comment out the following:

# To turn off the security checks that disallow incoming sends when
# the X server appears to be insecure, reverse the comments on the
# following lines:
#SECURITY_FLAGS =
SECURITY_FLAGS = -DTK_NO_SECURITY

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.8- call Tk scripts from a C program?

A2.A.8.   Several simple examples have been posted to comp.lang.tcl
recently.  Eric Bleeker <ericbl@paramount.nikhefk.nikhef.nl> was 
gracious enough to package his up and place it at
ftp://ftp.aud.alcatel.com/tcl/code/tkHelloWorld* .  This
program assumes that you have installed the Tcl and Tk libraries , 
header files, etc.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.A.9- get the geometry of my window (I get 1x1+0+0)?

A2.A.9.   If you start wish interactively and type:

    puts [wm geometry .]

you will get something like:

    200x200+90+90

The actual numbers may vary depending on X11 defaults, window managers, etc.
If you put the same thing in a script, though:

    #!/usr/local/bin/wish -f
    puts [wm geometry .]

You will instead get this:

    1x1+0+0

This will happen because you are requesting geometry information before the
window has actually been drawn.  In general, before you start asking about
window sizes, use the 'update' command so that the geometries of the windows
can be resolved.  Changing the above script to this will give the expected
results:

    #!/usr/local/bin/wish -f
    update
    puts [wm geometry .]

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.B.1- change the default class bindings?

A2.B.1. All default class bindings for Tk widgets are initialized in
$tk_library/tk.tcl.  Use this file as a guide to implement new
bindings.  For instance, the following code duplicates Button 1's
drag-select facility in Button 3 for all listboxes:

bind Listbox <3> {%W select from [%W nearest %y]}
bind Listbox <B3-Motion> {%W select to [%W nearest %y]}

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.B.2- delete a binding?

A2.B.2. Give an empty-string command to the "bind" invocation.  For
example, to disable the Delete key in all entry fields:

        bind Entry <Delete> {}

Also, see the documentation for the bind and bindtags commands.  There
are several ways to disable or modify which types of bindings (instance,
class, etc.) occur and the order in which they are processed.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.B.3- bind the arrow key on my Sun keyboard?

A2.B.3. You have to call it <Left> rather than <R10>.  Under X11, keys are
referred to by their keysym.  One can use either xmodmap -pk or the xev
program to determine what the keysym a particular key on a keyboard is
currently generating.

If the keysym that is being used is not known by Tk, you may have to edit
its ks_names.h file.  There is a note in this file that indicates that
one should not edit it - but this is where the keysym must be for it to
be recognized.

Thanks to Wayne Christopher <faustus@CS.Berkeley.EDU> for this
note.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.B.4- get root's mouse bindings to work in my Tk application?

A2.B.4. Some window managers, such as mwm, define mouse button bindings
which cause Tk some problems.  Try saving off the window manager's startup
file (something like /.mwmrc for instance) and then copy in a startup
file from a login id that works.  Thanks to brad@NeoSoft.com (Brad Morrison)
for this invaluable tip!

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.B.5- add new actions to an existing binding?

A2.B.5. The question was actually:
>I want to bind a text window so that any keypress in that window
   >updates the window's title bar.  This is what I used:
   >    
   >    text .textWin ...
   >    bind .textWin <Any-KeyPress> {+wm title . "Nextedit - edited"}
   >
   >This is supposed to let the user know that the text in the window
   >has been edited.  The problem is the "+".  Where does it go?  Ive
   >tried a bunch of things and it always ends up with either parse 
   >errors or the wm command completely overrides the binding and does
   >not allow any text entry.  I need to add the new binding to the
   >current ones so that a keypress enters the text *and* updates the
   >titlebar.  How?
   >

gwl@cpu.com (Gerald W. Lester) replied:

   You need to move the class specific binding down to the widget specific
   binding.  Try this:

           bind .textWin <Any-KeyPress> Text
           bind .textWin <Any-KeyPress> {+wm title . "Nextedit - edited"}

Also, in Tk4.0, see the documentation for bind and bindtags.  Now it is
possible to add instance bindings without overriding the class bindings.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.1- get an application to also use libXt?

A2.C.1. Tk2.1 and Xt have different X connections, and XtAppNextEvent will
block is there is nothing coming from the X connection.  One way
of fixing this is get the connection number of Tk using

   ConnectionNumber(Tk_Display(tk_window));

and using XtAddInput to register this with the Xt event handler.  The
callback procedure for XtAddInput wrapper procedure that runs
Tk_OneEvent(1).  There might be problems with Tk file sources which
aren't registered with Xt.

Thanks to joe@astro.as.utexas.edu (Joe Wang) for this information.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.2- change the X11 cursor?

A2.C.2. Here is a tip from mgc@cray.com (M. G. Christenson).

Look at /usr/include/X11/cursorfont.h for a list of available cursors.
You can use the names in there by removing the 'XC_'.  

Here's a little proc I use to make my entire application go 'busy'
while it's doing something. Just call it with the commands you want to
execute, and the watch cursor will be displayed for the time it takes
the commands to complete.  Note that any new windows will have their
normal cursor.

proc busy {cmds} {
    global errorInfo

    set busy {.app .root}
    set list [winfo children .]
    while {$list != ""} {
        set next {}
        foreach w $list {
            set class [winfo class $w]
            set cursor [lindex [$w config -cursor] 4]
            if {[winfo toplevel $w] == $w || $cursor != ""} {
                lappend busy [list $w $cursor]
            }
            set next [concat $next [winfo children $w]]
        }
        set list $next
    }

    foreach w $busy {
        catch {[lindex $w 0] config -cursor watch}
    }

    update idletasks

    set error [catch {uplevel eval [list $cmds]} result]
    set ei $errorInfo

    foreach w $busy {
        catch {[lindex $w 0] config -cursor [lindex $w 1]}
    }

    if $error {
        error $result $ei
    } else {
        return $result
    }
}

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.3- raise or lower a window?

A2.C.3. This is on the (semi-infinite) list of things to be done in the future.
If you have the time, please go ahead and add it and submit the code and all
will be grateful.

In Tk4.0, the commands 'raise' and 'lower' are now available.  They can be
used to change a window's position in the stacking order.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.4- re-map a withdrawn window id?

A2.C.4. Use wm deiconify <windowid>.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.5- use Tk in a subwindow of a non-Tk X11 application?

A2.C.5. From faustus@CS.Berkeley.EDU (Wayne A. Christopher):

[C]reate the Tk toplevel window but don't map it (wm withdraw).  Then
re-parent the window to be a subwindow of your other one and then map
it.  I have done this when the Tk application is a separate process,
but if it's the same process I think you will get into trouble with the
event loop, since each toolkit wants control.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.6- bind <Enter> and <Leave> to a frame containing 
        other widgets?

A2.C.6. From John Ousterhout, ouster@cs.Berkeley.EDU):

Each <Enter> or <Leave> event has a "detail" field, which you can access
from bindings with "%d".  If the detail is "NotifyInferior" it means the
pointer has moved into or out of a child window (so it's really still in
the area of the window receiving the event).  You should be able to check
the detail in your scripts and ignore events with a detail of NotifyInferior.
Check the Xlib documentation for Enter/Leave events for complete
information on the detail field.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.7- mix interactions between Xt and Tk/Tcl?

A2.C.7.

[From YIP Chi Lap [Beta] <h9118101@hkuxa.hku.hk> ]
        I have come up with a CPU hogging polling loop that
works (till now) for my application which not much
direct interaction between a Tk window and an Xt window is made.
(e.g., it won't draw something on a Tk window by a Xt-dispatched routine)

  XEvent xevent;
  for (;;)
  {
    if (XtAppPending(appcontext))
    {
      XtAppNextEvent(appcontext,&xevent);
      XtDispatchEvent(&xevent);
    }
    Tk_DoOneEvent(TK_DONT_WAIT);
  }

[ From David C Mudie <mudie@radon.eecs.berkeley.edu> ]
        We use the main event loop below.  The basic idea
is to watch for events arriving from either the Xt server
connection or the Tk server connection and then call
the library dispatchers.

        The code fragment below will need to be cleaned up for
your usage; there are some missing include statements
and global declarations buried elsewhere in the file.

/* Allow Tcl/Tk and Xt to work at the same time. */
void tkGo(void)
{
  extern Widget topLevel;
  int width = ulimit(4, -1);
  fd_set readfds;
  struct timeval timeout;
  int nfds;
  int tkfd = ConnectionNumber(Tk_Display(mainWindow));
  int xtfd = ConnectionNumber(XtDisplay(topLevel));

  Tcl_VarEval(interp, "update", NULL);
  while (1) {

    /* Select on X server connections to wait for event. */
    /* Timeout every half second to allow processing of non-X events */

    FD_ZERO(&readfds);
    FD_SET(tkfd, &readfds);
    FD_SET(xtfd, &readfds);
    timeout.tv_sec = 0;
    timeout.tv_usec = 500000;

    nfds = select(width, &readfds, NULL, NULL, &timeout);
    if (nfds < 0 && errno != EINTR) {
      perror("select");
    } else if (nfds == 0) {
      /* printf("timeout\n"); */
    }

    while (XtPending()) {
      XtProcessEvent(XtIMAll);
    }

    while (Tk_DoOneEvent(1)) {
      /* do nothing */
    }
  
    if (mainWindow == NULL) {
//      Tcl_DeleteInterp(interp);
//      Tcl_DStringFree(&command);
      Tcl_Eval(interp, "exit");
      return;
    }
  }
}

[ From Davide Frisoni <frisoni@faw.uni-ulm.de> ]
        One may use Xt properties to communicate between different
applications.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.8- bind the ResizeRequest event?

A2.C.8.  huffi@dutncp8.tn.tudelft.nl (Martijn Figee Huffi Marcel Huefken)
says:

: I'm having trouble with...
:    bind .frame <ResizeRequest> {puts stdout "resise\n"}
: that is I can resize .frame and NEVER see "resize" at stdout.
 
Try 
        bind .frame <Configure> {puts...}
 
It'll work.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.9- avoid that 'bad geometry "+0+0": expected widthxheight'
                error message?

A2.C.9.  This usually means that you have an X11 resource set that looks
like:
        *geometry: +0+0
or
        Tk*geometry: +0+0

Tk doesn't like this, so either remove it or fully specify the resource
in the form:
        widthxheight{+-}xoffset{+-}yoffset
such as
        Tk*geometry: 200x200+0+0


------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.10- ignore "send"s from other applications?

A2.C.10.  Tom Poindexter (tpoindex@nyx.cs.du.edu) writes:

Delete the "send" command.  This removes the interpreter's name from the
X11 property (won't show up in another wish's "winfo interps") and disables
incoming "send" processing.  You can delete the send command with:

        rename send ""

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.C.11- tell the difference between 'wm' and 'winfo'?

A2.C.11.  fms@cam-orl.co.uk (Frank Stajano) responds to:
> When I do the following from wish, the window moves down about 20 pixels.
> % wm geomtry . [winfo geometry .]

"wm geometry" tells you the geometry according to what the window
manager thinks. "winfo geometry" tells you what Tk thinks.

Because of this, "winfo geometry" works for all the widgets, while "wm
geometry" works only on toplevels. And, if you use both commands on
toplevels, the "wm" one includes the title bar (your extra 20 pixels)
whereas the other one doesn't.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.D.1- resize a listbox?

A2.D.1. Use wm min/maxsize - in a uniform manner.  Here is a resizable listbox:

        #!/usr/local/bin/wish -f
        wm minsize . 20 20
        wm maxsize . 1152 900
        pack append . [listbox .l -borderwidth 2 -relief raised] {expand fill}

Doing the same with the text widget brings its resizing under control too.

Thanks to "John C Ellson" <ellson@ontap.att.com).

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.D.2- select two items that are not adjacent in the listbox at 
                one time?

A2.D.2.  See Marc R. Ewing's Listbox.patch for a way to modify Tk to allow
selection of non-contiguous entries:
       ftp://ftp.aud.alcatel.com/tcl/extensions/Listbox.patch.gz

In Tk4.0, this functionality is now included.  Use the -selectmode of the
listbox to specify what type of selection you desire.  The mode 'multiple'
will allow you to select multiple non-contiguous entries.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.D.3- select items in more than one Tk listbox at a time?

A2.D.3. The default for Tk's listbox widget exports its selection as the
X selection.  There can only be one of these at a time.

To turn off this behavior in Tk, use the -exportselection false when
you create the listbox.  Or, use the

option add *Listbox.exportselection false

command in the beginning of your script.

Thanks to David Herron <david@davids.mmdf.com> for this tip.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.D.4- avoid fractional white space at the end of a resizable
                listbox?

A2.D.4. First, let's state the problem more clearly. I want to make a
resizable listbox and I don't want to constrain it by setting a
minimum size. So I pack it with fill expand, I use it to set the grid
(so that resizing the window always gives me whole lines) and I set an
initial geometry of 1x1 to override the default. However what I get
is... (run the code below for a demo and try to resize)

listbox .l -geom 1x1 -setgrid 1 -yscrollcommand ".s set" -relief sunken -bd 2
scrollbar .s -command ".l yview"
pack .s -side right -fill y
pack .l -side top -fill both -expand 1
.l insert end one two three four five six seven eight nine ten "THE END"

...a situation where the partially filled listbox has a blank
half-line at the bottom even if there are more items in the list. This
is very confusing because it fools the user into thinking that there
is nothing else beyond what's visible. Why does it happen?

Now for the answer.
        Look at the window as it is created, before the resizing. See that
poor, tiny little scrollbar squeezed in that microscopic window? It,
too, requests a minimum size, and it so happens that the starting
geometry for the listbox (i.e. the situation referred to as "1x1")
receives some free fractional space at the bottom. And you never get
rid of it, since the resizing is constrained to be in whole
characters.

The thing to do is to define the initial layout in such a way that the
widget that has -setgrid actually displays an integer number of lines
and columns. In the above example, setting -geom 1x2 does the trick.

Thanks to Frank Stajano <fms@cam-orl.co.uk> for this tip.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.D.5- scroll two listboxes with one scrollbar?

A2.D.5. Scrollbars have a '-command' option which is used to tell
scrollable widgets (e.g. listbox, text, entry) how to position
themselves when the scrollbar is moved.  This command typically
looks like:
    scrollbar .scroll -command {.scrollable_widget yview}
or
    scrollbar .scroll -command {.scrollable_widget xview}

Before the command is executed, however, it will have a space and
a number appended to it.  The number is a logical position index
which indicates how the scrollable widget should position itself.
Thus, to have a single scrollbar control two (or more) widgets,
simply use a procedure as the scroll command, and have that
procedure scroll as many widgets as you would like.  The procedure
should take a single argument (i.e. the logical position index).
For example:

    proc ScrollCommand {args} {
        eval .lb1 yview $args
        eval .lb2 yview $args
        eval .lb3 yview $args
    }

    scrollbar .scroll -command ScrollCommand

    listbox .lb1 -yscrollcommand {.scroll set}
    listbox .lb2 -yscrollcommand {.scroll set}
    listbox .lb3 -yscrollcommand {.scroll set}
    pack .scroll .lb1 .lb2 .lb3 -side left -fill y

    .lb1 insert 0 a b c d e f g h i j
    .lb2 insert 0 0 1 2 3 4 5 6 7 8 9
    .lb3 insert 0 A B C D E F G H I J


------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.D.6- have a listbox only allow the selection of a single item
at a time?

A2.D.6. See the man page for the tk command "tk_listboxSingleSelect".  An
invocation such as the following:

    listbox .l
    tk_listboxSingleSelect .l

will modify the bindings of the widget .l so that only a single item of
the listbox can be selected at a time.

In Tk4.0, you should specify the configuration option '-selectmode single'
to get this behavior.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.E.1- get output from a Tk canvas?

A2.E.1. Tk 3.6 has a 'postscript' suboption on canvas which allows one
to create an Encapsulated Postscript file describing the canvas.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.E.2- fill a canvas which is bounded by lines as opposed to a
                shape like a polygon, oval, etc.?

A2.E.2. No, you have to at least use a polygon if you want to fill an area
bounded by some lines.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.E.3- raise/lower canvas window objects or draw graphics onto a 
                window object inside a canvas?

A2.E.3. You can't yet. 

"Jesper Blommaskog" <d9jesper@dtek.chalmers.se>.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.E.4- detect when the canvas has been resized?

A2.E.4. From Nathaniel Pryce <np@hpl.hp.co.uk>:

> I have a window with a canvas containing some stuff that logically
> fills the canvas (say, a chess board or a map of the world). I want
> this toplevel window to be resizable and of course, when the win is
> resized, I want the stuff inside the canvas to be scaled
> accordingly. Now, I can manage the scaling of the stuff, but what
> I'm having trouble with is DETECTING that I should do it. How can I
> be notified that the window has been resized?

Nat's answer is:

You need to bind a command to the Configure event, like this:

        proc config {w h} {
           puts stdout ".canvas - width = $w, height = $h"
        }

        bind .canvas <Configure> "config %w %h"


.canvas - width = 224, height = 251
.canvas - width = 224, height = 151
.canvas - width = 224, height = 243
# and so forth

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.E.5- scroll a canvas and a listbox at the same time with 
                one scrollbar?

A2.E.5. From "David Herron" <david@twg.com>:

You need to write different code to handle the scrollcommand's.  Look at the
man page for `scrollbar' (and `listbox') and you see that it appends some
numbers to the scrollcommand such that your scrollbar command is executed as:

        .f.c yview; .f.lb yview <offset>

What I ended up doing is appended.  This code has an advantage in that
scrolling is constrained to "look right".

        listbox .l1     -relief sunken -yscrollcommand {
                        scrollMultiple_y { .l1 .l2 .l3 } .vs
                }
        listbox .l2     -relief sunken -yscrollcommand {
                        scrollMultiple_y { .l1 .l2 .l3 } .vs
                }
        listbox .l3     -relief sunken -yscrollcommand {
                        scrollMultiple_y { .l1 .l2 .l3 } .vs
                }
        scrollbar .vs   -relief sunken -orient vertical \
                        -command {setMultiple_y {.l1 .l2 .l3}}

        bind .l1 <1> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l1 <B1-Motion> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l1 <Shift-1> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l1 <Shift-B1-Motion> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }

        bind .l2 <1> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l2 <B1-Motion> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l2 <Shift-1> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l2 <Shift-B1-Motion> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }

        bind .l3 <1> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l3 <B1-Motion> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l3 <Shift-1> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }
        bind .l3 <Shift-B1-Motion> {
                selectMultiple {.l1 .l2 .l3} [%W nearest %y]
        }

proc scrollMultiple_y {lists vs total window first last} {
        if {[expr $first+$window] > $total} {
                set first [expr $total-$window]
                set last  [expr $first+$window]
        }
        setMultiple_y $lists $first
        $vs set $total $window $first $last
}
proc setMultiple_y  {lists index} {
        foreach l $lists { $l yview $index }
}
proc selectMultiple {lists index} {
        foreach l $lists { $l select from $index }
}


------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.E.6- use a list of coordinates in a variable to create a
                  polygon (or any other item)?

A2.E.6. Thomas Accardo (tja@cpu.com) writes:

This is actually a pure Tcl question, but it comes up frequently
in this context, so here we go...

All canvas items require two or more coordinates on creation,
which define the initial position and/or shape of the item.  If you
have each coordinate in a separate variable, or you are using a constant
value, then creating canvas items is simple.  For example:

    .myCanvas create rectangle $x1 $y1 $x2 $y2 -fill blue
    .myCanvas create text 100 250 -text "Hello, world"

Many times, though, the coordinates don't each exist in a separate
variable.  They may be a list in a single variable that was read from
a file, or returned from some calculation routine, or extracted from
some other list of coordinates.  In this case, you need to break the
list of coordinates up _before_ the canvas command is executed.  Use
the 'eval' commands for this.  Here are several examples:

     canvas .myCanvas
     pack .myCanvas

     #
     # Example 1
     #
     # Given a list of two coordinates, create a text item
     #
     set coords {150 50}
     eval .myCanvas create text $coords -text hello


     #
     # Example 2
     #
     # Here's a routine that returns coordinates for a rectangle centered
     # around a point, and some example uses.
     #
     proc CenteredRectangle {centerX centerY width height} {
         return [list [expr $centerX - $width  / 2.0] \
                      [expr $centerY - $height / 2.0] \
                      [expr $centerX + $width  / 2.0] \
                      [expr $centerY + $height / 2.0]]
     }
     eval .myCanvas create rectangle [CenteredRectangle 80 5 10 75]
     eval .myCanvas create rectangle [CenteredRectangle 5 80 75 10]
     eval .myCanvas create oval [CenteredRectangle 140 110 75 50]


     #
     # Example 3
     #
     # Here's a routine which creates a text label surrounded by
     # a rectangle, with both of them centered around a given point.
     #
     proc CenteredBoxLabel {w centerX centerY text} {
         set id [$w create text $centerX $centerY \
                    -text $text \
                    -anchor center]
         eval $w create rectangle [$w bbox $id]
     }
     CenteredBoxLabel .myCanvas 33 42 "Hello, world"


     #
     # Example 4
     #
     # Make a sine-wave line
     #
     set coordList {}
     loop x 0 314 {
         lappend coordList $x [expr sin($x/25.0) * 50 + 100]
     }
     eval .myCanvas create line $coordList

If you have a list of coordinate pairs, e.g. {{25 10} {30 12} {35 14}},
then an extra step is required to make it a flat list.  Try this:

     #
     # Example 5
     #
     # Starting with a list of pairs...
     #
     set coordPairs {{25 10} {30 12} {35 14}}

     #
     # ... flatten out the list into just a list of numbers (as in
     # the above examples).
     #
     set flatList [eval concat $coordPairs]

     #
     # Now, follow the same strategy as in the examples above.
     #
     eval .myCanvas create line $flatList

In summary, carefully read the docs for eval, concat, and list so that
you can combine the coordinate data with the 'canvas create' command
to form a valid Tcl command which can be executed.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.1- get the name of my own interpreter?

A2.F.1. george.howlett@att.com (George A. Howlett) points us to the winfo manual
page - winfo name . gets the name of the current application.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.2- get -relief to work on my text widgets?

A2.F.2. From Owen Rees <rtor@ansa.co.uk>, we find out that we must:

"[m]ake the border width non-zero as in"

   text .t -width 20 -height 20 -relief sunken -borderwidth 4

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.3- create a scrollable window of buttons?

A2.F.3. There are at least two ways to do this.  First, there is a hypertext
widget that one can get from the Tcl User Contributed Code Archive -
(see "tcl-faq/part4") and (see "tcl-faq/part5") for details -
 which provides such a facility.

And here is some sample code from 
"Michael Moore" <mdm@stegosaur.cis.ohio-state.edu> which shows a way to 
do this using just Tk.

#! /bin/wish -f
#
# This demonstrates how to create a scrollable canvas with multiple
# buttons.
#
# Author : Michael Moore
# Date   : November 17, 1992
#

#
# This procedure obtains all the items with the tag "active"
# and prints out their ids.

proc multi_action {} {
    set list [.frame.canvas find withtag "active"]
    puts stdout "Active Item Ids : "
    foreach item $list {
        puts stdout $item
    }
}

# 
# This simulates the toggling of a command button...
# Note that it only works on a color display as is right now
# but the principle is the same for b&w screens.
# 
proc multi_activate {num id} {
    
    set tags [.frame.canvas gettags $id]
    if {[lsearch $tags "active"] != -1} {
        .frame.canvas dtag $id "active"
        .frame.canvas.button$num configure \
            -background "#060" \
            -activebackground "#080" 
    } else {
        .frame.canvas addtag "active" withtag $id
        .frame.canvas.button$num configure \
            -background "#600" \
            -activebackground "#800"
    }
} 

proc setup {} {
     frame .frame

     scrollbar .frame.scroll \
         -command ".frame.canvas yview" \
         -relief raised

     canvas .frame.canvas \
         -yscroll ".frame.scroll set" \
         -scrollregion {0 0 0 650} \
         -relief raised \
         -confine false \
         -scrollincrement 25

     pack append .frame \
         .frame.scroll    {left frame center filly} \
         .frame.canvas    {left frame center fillx filly}

     pack append .\
         .frame   {left frame center fillx filly}

     button .frame.canvas.action  \
         -relief raised \
         -text "Action" \
         -command "multi_action"
     .frame.canvas create window 1 25 \
         -anchor w \
         -window .frame.canvas.action
     for {set i 2} {$i < 26} {incr i} {
         button .frame.canvas.button$i  \
            -relief raised \
            -background "#060" \
            -foreground wheat \
            -activebackground "#080" \
            -activeforeground wheat \
            -text "Button $i" 
         set id [.frame.canvas create window 1 [expr $i*25] \
            -anchor w \
            -window .frame.canvas.button$i]
         .frame.canvas.button$i configure \
            -command "multi_activate $i $id"
    }
}

setup

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.4- pack a text widget so that it can be resized interactively?

A2.F.4. From Spencer W. Thomas <spencer@med.umich.edu> we find that we need to:

wm minsize . 0 0
text .text
pack append . .text {fill expand}

In newer pack syntax, this would be:
pack .text -fill both -expand 1

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.5- create a widget with an upper case name?

A2.F.5. You can't.  During a recent revision of Tk, things were changed so
that names beginning with a capital letter are reserved for class names.
Specific instances of widgets must begin with a lower case letter.  This
enables X11 resource definitions to distinguish between a class and instance.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.6- create equal sized buttons?

A2.F.6. Recently, Micael Salmon <etxmesa@eos.ericsson.se> posted:

In article <1993Jun23.065417.4302@ericsson.se>, I write:
|> I am currently working on yet another tn3270 emulator and I have run
|> into a problem with creating equal sized buttons. I have created an
|> array of buttons for PF and cursor keys and I would now like to make
|> them all the same size. Arranging them into columns was not
|> a problem but when I add bitmaps the buttons lose their horizontal
|> alignment. What I tried was to read the height and width of the buttons
|> using winfo, determine the largest and then use pads to force them to
|> be the same size, this doesn't seem to work. The technique of using
|> pre-set height and width doesn't seem applicable when using a mixture
|> of bitmaps and text as the size in pixels of a text button is font
|> dependent. All suggestions welcome.

Jim Wight <J.K.Wight@newcastle.ac.uk> suggested using reqheight and reqwidth
and then specifying padx and pady in the pack command for each button.
Jim says:
I think it only fair to point out that it was Tuomas J Lukka
<lukka@klaava.Helsinki.FI> who suggested the use of reqwidth and reqheight when I asked how to get over the deficiencies in my first attempt at a solution
that I posted to this group.

Since you're all agog I might as well post the final solution (more or less)
that I mailed to Michael.

frame .frame1
frame .frame2
button .frame1.a -text "pretty long button text"
button .frame1.b -text "short one"
button .frame2.c -bitmap "@/usr/include/X11/bitmaps/xlogo32"
button .frame2.d -text "tiny"

set long [winfo reqwidth .frame1.a]
set short [winfo reqwidth .frame1.b]
set medium [winfo reqwidth .frame2.c]
set tiny [winfo reqwidth .frame2.d]
set pady [expr [winfo reqheight .frame2.c]-[winfo reqheight .frame2.d]]

pack append .frame1 .frame1.a "filly pady $pady"
pack append .frame1 .frame1.b "fillx padx [expr $long-$short] filly pady $pady"
pack append .frame2 .frame2.c "fillx padx [expr $long-$medium] filly"
pack append .frame2 .frame2.d "fillx padx [expr $long-$tiny] filly pady $pady"
pack append . .frame1 {left} .frame2 {left}

# In newer pack syntax, this would be something like:
pack .frame1 .frame2 -side left
pack .frame1.a -fill y -ipady [expr $pady/2]
pack .frame1.b -fill x -ipady [expr $pady/2]
pack .frame2.c -fill both
pack .frame2.d -fill both -ipadx [expr ($long-$tiny)/2] -ipady [expr $pady/2]

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.7- vertically stack radio buttons aligning regardless of font?

A2.F.7.  Till Brychcy <brychcy@informatik.tu-muenchen.de> provides
the following example:

        radiobutton .times -text Times -anchor w
        radiobutton .helvetica -text Helvetica -anchor w
        radiobutton .courier -text Courier -anchor w
        pack .times .helvetica .courier -side top -fill x

Note that you are using anchor west in the widgets themselves, and not in
the packer.  This lets the packer produce full width buttons.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.8- initialize an entry widget with some text?

A2.F.8.  kesch@kappco.kapp-coburg.de (Peter Kesch) provides us with
one example:

set default "foobar"
entry .foo -width 25 -state disabled -textvariable default

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.9- change the default colors in Tk?

A2.F.9.  To change the default colors in Tk you must modify your X
resource database.  You can do this using whatever method you ususally
use to add/modify X resources (X default file, etc.), or you can use
the Tk "option" command to change the option database from within a Tk
application.  rpeck@java.nas.nasa.gov (Rodney C. Peck) lists the set
of resources which must be set along with a possible color scheme:

     Tk*activeBackground:                    #efefef
     Tk*activeForeground:                    black
     Tk*selector:                            black
     Tk*background:                          #dfdfdf
     Tk*foreground:                          black
     Tk*selectBackground:                    #bfdfff
     Tk*Scale.activeForeground:              #efefef
     Tk*Scale.sliderForeground:              #dfdfdf
     Tk*Scrollbar.foreground:                #dfdfdf
     Tk*Scrollbar.activeForeground:          #efefef
     Tk*Button.disabledForeground:           #7f7f7f
     Tk*Checkbutton.disabledForeground:      #7f7f7f
     Tk*Radiobutton.disabledForeground:      #7f7f7f
     Tk*Menu.disabledForeground:             #7f7f7f

For more information, see your system's documentation for loading
X resources, and/or the Tk man page for the "option" command.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.10- find my invisible windows when using the packer?

A2.F.10.  The situation:
  A window is created, say .w1, followed by another window, say .w2.
  The command "pack .w1 -in -.w2" is used to pack .w1 inside of .w2.
  The pack command completes successfully, and "pack newinfo .w1"
  indicates that things are as expected.  However, .w1 isn't visible!
  Where is it?
            button .w1 -text button;   # create .w1
            frame .w2;                 # create .w2
            pack .w1 -in .w2;          # pack .w1 inside .w2 
            pack .w2;                  # pack .w1 in main window
                                       # where's the button?

  The explanation:
  (based on a posting by js@aelfric.bu.edu (Jay Sekora))

  The short answer is "raise .w1".  In the example .w1 is positioned
  properly inside .w2, and all the sizing glue that lets .w1 and .w2
  adjust their sizes based on each other will work, but .w1 is
  _underneath_ .w2, because windows are stacked in the order they're
  created in, by default.  You can change the stacking order
  explicitly with the "raise" command, in this case "raise .w1".

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.11- destroy every window except '.'?

A2.F.11.  Based on a posting by tromey@klab.caltech.edu (Tom Tromey):
To destroy every  window in the application just use the
'destroy' command.  In previous versions of Tk, destroy accepted only
a single argument, but now it accepts a variable number of window names
to destroy.  Thus, to get rid of everything, use the command

     eval destroy [winfo children .]

The 'eval' is necessary so that the list of children windows can be
separated into individual arguments.  Destroy will get individual
window names instead of one big string.

------------------------------

From: -II-  Tk Questions and Answers - How can I:
Subject: -Q2.F.12- group a set of radiobuttons together?

A2.F.12.  This solution was provided by Michael Salmon:

To group radiobuttons, simply give all the buttons in a group the same
-variable name.  Since the default variable name is selectedButton for
ALL radiobuttons, if no -variable is used, then ALL belong to the same
"group".

Ex:

radiobutton .left.button1 -text "Left button 1"  -variable leftChoice
radiobutton .left.button2 -text "Left button 2"  -variable leftChoice
radiobutton .left.button3 -text "Left button 3"  -variable leftChoice

radiobutton .right.button1 -text "Right button 1" -variable rightChoice
radiobutton .right.button2 -text "Right button 2" -variable rightChoice
radiobutton .right.button3 -text "Right button 3" -variable rightChoice

------------------------------
        
End of comp.lang.tcl Tk Toolkit Usage Questions and Answers (1/1)
*****************************************************