Using Tk as a loadable package

DGP

  package require Tcl 8.4
  package require Tk 8.4

Read on if you want the older history.


by Reinhard Max

Starting with version 8.3.4, Tk can be loaded dynamically from a tclsh and it will automatically enter the event loop. The plain Tk8.3.4 build is still missing a pkgIndex.tcl file, so for now one has to load tk by hand:

 load libtk8.3.so

This works for Linux. Please add the correct commands for other platforms.

 load tk83.dll ;# works for Windows (MPJ)

Mac OS X:

 load libTk8.3.a

where .../Tk.framework/Versions/8.3/ is in the path. (Note that this doesn't work really - OS X Tclers know the "SetFrontProcess failed,-606" error.)

Philipp Roessler


DGP All one needs to do to be able to load Tk with the more familiar [package require Tk] idiom is to add an appropriate pkgIndex.tcl file to their Tk installation.

One way to do that (for Unix and Windows) is to apply Tk Patch 521356 http://sf.net/tracker/?func=detail&aid=521356&group_id=12997&atid=312997 before compiling and installing Tk.


The possibility to load Tk on the fly opens up some interesting possibilities. For example one can start a tclsh outide of an X session and later load Tk into it to connect to an X server.

 # start a tclsh that doesn't know anything about X
 $ DISPLAY="" tclsh
 couldn't connect to display ""
 # prove that the display really isn't availible
 % package require Tk

 # now tell it about the display and try loading Tk again.
 % set argv {-display :0}
 -display :0
 % package require Tk
 8.3
 # A window pops up - we have succeeded.

By using slave interpreters, it is even possible to have multiple Tk sessions at the same time while having no Tk at all in the master interpreter. These multiple Tk sessions can -but don't need to- go to different displays.

 # begin as before...
 $ DISPLAY="" tclsh
 % package require Tk
 couldn't connect to display "" 

 # now create the slaves and load Tk into them

 % interp create a
 a
 % a eval {set argv {-display :0}; package require Tk}
 8.3
 # A window pops up on display :0

 % interp create b
 b
 % b eval {set argv {-display :1}; package require Tk}
 8.3
 # A window pops up on display :1

Caution !!! Although the windows disappear when the slave interpreters get deleted, the connections to the X server don't get closed properly as of [October 24, 2001]. That means that the shutdown of any X server that has ever been connected from a process will kill this process.


The above did not work for me to load Tk into a slave interpreter in wish. Don Porter suggested:

    interp create slave
    load {} Tk slave

which worked. -- Chris Nelson