Updated 2015-05-19 11:49:50 by MiHa

How to post on Ask-pages edit

This page is not intended for new questions.

Please post your question on the latest version of Ask, and it shall be given.

Please do not edit this part, it is meant as a guide!

Page contents

Questions edit

tracing a -textvariable

KJN 2004-11-10 - tracing a -textvariable in 8.4.6 for Linux
 entry .e -textvariable varName
 puts $varName
 set varName

When the user alters the text in the entry widget .e, or at the very latest when "puts $varName" or "set varName" is executed, Tk copies the value of the entry field to varName; but this update appears not to trigger the "trace write" action. Should this be considered a bug?

aricb You wrote:
 when "puts $varName" or "set varName" is executed, Tk copies the value of the entry field to varName

This isn't the case. When the user changes the contents of .e, that's when the change to varName occurs, and that's when the write trace ought to fire. But the [puts] and [set] calls above don't change the value of varName in any way and shouldn't (and in fact don't) cause a write trace to fire.

You haven't posted the code that implements your write trace, but I suspect the bug lies there, not in Tcl itself.

Here's an example of a useless but well-behaved write trace. Enter this code into an interactive tclsh or wish session:
 package require Tk
 proc traceProc {args} {
     puts "variable modified"
 entry .e -textvariable varName
 grid .e
 trace add variable varName write traceProc

Does this behave according to your expectations?

KJN Yes it does. But this script does not:
 package require Tk
 proc traceProc {args} {
     puts "variable modified to [lindex $args 0]"
 entry .e -textvariable varName
 grid .e
 trace add variable varName write {traceProc $varName}
 set varName 4

The trace fires when varName is updated by set (and the value of varName is correctly sent to traceProc as the first element of args; and the text in the widget is automatically updated); but if I update varName by typing into the entry field, the trace does not fire.

It seems to be the combination of $varName in the trace command, and the -textvariable, that gives trouble.

learning about Iwidgets, bindings, and childsites

2004/10/27 sheila :

I found childsites to be tricky when first working with Iwidgets. The examples in the book and on the online man pages don't give enough detail for me on when and how to use childsites. Consider the example from Smith's book for the tabnotebook.
 # Create and fill in the page for tab 1. Note the pathname will
 # likely not exist on your system.
 set tab1 [.tb add -label "Itcl Powered"]
 frame $tab1.f -relief ridge -bd 3

and so on. $tab1 is a childsite. At first I was confused because he added a frame to what appeared to be the tab, rather than adding it to the tab's childsite. But, if you look at the childsite method for tabnotebook, you can see that it is associated with the notebook. So, one needs to go look at the reference for notebook to track down what this means (ed's note: and I followed a trail that I'd like to record here, but I need to get back to work, sorry) that the add method returns a handle for a childsite, not a widget, right?

I also found it tricky to add a binding to an Iwidget, and someone directed me to the component method. Smith discusses this in chapter 11, pg. 341.

I made a scrolledcanvas
    set sc [iwidgets::scrolledcanvas $tab1.sc \
            -borderwidth 2 \
            -width $w \
            -height $h \

and couldn't get bindings to properly work on the canvas until I bound them on $sc component canvas. Maybe this seems obvious now, but it wasn't when I first had the question.

Would this be a good topic for a wiki page for the next person who has this problem?

KJN Definitely. Anything you've learned that isn't already here is ideal for the Wiki.

Oracle OEM console

2004/09/03: Wilfredo Duarte asks:

I have the following script that will be used inside the Oracle OEM console for monitoring the detection of the counting of kind of file in the filesystem. (oratclsh) What I want to detect is if there are files with the extension *.Z in the directory
 if {[file exists "/cognos_data/ORADATA/arc/*.Z"] } {
 puts <oramessage>YES</oramessage>
 puts <oraresult>-1</oraresult>
 } else {
 puts <oramessage>NO</oramessage>
 puts <oraresult>2</oraresult>

When in the OS I issue the oratclsh command and then issue the above Solaris script, it gave me the result of NO, when indeed the directory is filled up with files like this:
 arch_mapdev0000006291.arc.Z arch_mapdev0000006471.arc.Z
 arch_mapdev0000006292.arc.Z arch_mapdev0000006472.arc.Z
 arch_mapdev0000006293.arc.Z arch_mapdev0000006473.arc.Z

When I change the script to the following, it gave me the error "child process exited abnormally:"
 oratclsh[20]- if {[ls cognos_data/ORADATA/arc/*.Z | wc -l > 1] } {
 puts <oramessage>YES</oramessage>
 puts <oraresult>-1</oraresult>
 } else {
 puts <oramessage>NO</oramessage>
 puts <oraresult>2</oraresult>
 child process exited abnormally

Also the same result if I change the first line to this:
 if {[ls cognos_data/ORADATA/arc/*.Z | wc -l > 1;] } {

I need help with this

Answer (sm)

Your initial attempt was close. The problem is, file exists doesn't do wildcard expansion, so it's looking for a file named *.Z. The command you want to use is glob. glob returns an error if no files match the given pattern, so you'll either need to wrap your glob call in a catch statement, or else pass glob the -nocomplain flag and check for a non-empty list. Here's examples of the two options:
 if {[llength [glob -nocomplain "/cognos_data/ORADATA/arc/*.Z"]] > 0 } {
 puts <oramessage>YES</oramessage>
 puts <oraresult>-1</oraresult>
 } else {
 puts <oramessage>NO</oramessage>
 puts <oraresult>2</oraresult>

 if {[catch {glob "/cognos_data/ORADATA/arc/*.Z"}] == 0} {
 puts <oramessage>YES</oramessage>
 puts <oraresult>-1</oraresult>
 } else {
 puts <oramessage>NO</oramessage>
 puts <oraresult>2</oraresult>



hi, I've just a single question: Is there a possibility in TCL to set or clear a single line of serial-interface? (that means: DCD,RxD,TxD,DTR,DSR,RTS,CTS) thanks in advance!

slebetman 27 Dec 2004: Since Tcl 8.4 (I think, I may be wrong) you can do this using the fconfigure command. The following options work on both windows and Unix: To set a signal line:
 fconfigure channelId -ttycontrol signal value signal value

for example:
 fconfigure $serialPort -ttycontrol RTS 1

For now only RTS and DTR are supported.

To query a signal line (returns a list of signal,value pairs):
 fconfigure channelId -ttystatus

values for CTS DSR RING and DCD will be returned.

The documentation for this option is not in the fconfigure section but in open.


I am trying to ftp a file using TCL. The file is in a readonly mode in my source directory. but after i do a ftp, the file changes to non readonly mode (something i do not want .. i still want the file to be readonly).. i am using dos ftp .. any pointers will be aqppreciated. Ashish

March 3rd: It sounds like that's a bug in the ftp package. Whether this is the correct/best solution, I'm not sure, but you could cache the readonly value and reset it later with something like...
  set ro [file attributes $filename -readonly]
  <insert FTP code here>
  file attributes $filename -readonly $ro

2004/10/26 - e0richt

I don't believe that FTP is supposed to preserve file modes. I had a similar problem working on a RS/6000 box. you will either have to set the file attributes after transfer or if you had a lot of files you could ftp a .tar file which will preserve file attributes when it is unrolled.

save canvas-content as bitmap


Just two questions: It is possible to save canvas-content as bitmap and if it so how? thanks 4 each hint ... - RS: You get that with the Img extension:
 set im [image create photo -format window -data .my.canvas]
 $im write mycanvas.gif -format GIF

Sorry, but it doesn't work. "-format window" isn't supported and "-data" from canvas-object couldn't be recognized ... RS: Well, my hint above was too subtle - put the line
 package require Img

somewhere early in your program, and make sure you have that extension.

cascade menus


Hi, I've a problem by building cascade menus with menu-command:
 text .txt -background white -wrap none -yscroll {.sbary set} -xscroll {.sbarx set}
 scrollbar .sbary -command {.txt yview} -orient vertical
 scrollbar .sbarx -command {.txt xview} -orient horizontal
 grid .txt .sbary -sticky news
 grid .sbarx -sticky news
 grid columnconfigure . 0 -weight 1
 grid rowconfigure . 0 -weight 1

 menu .mnu -tearoff 0
 .mnu add cascade -label "menu 1" -menu {
        .mnu add command -label "menu 1.1"          ;# isn't displayed
 .mnu add separator
 .mnu add command -label "exit" -command { exit }

 bind .txt <ButtonPress-3> {
        tk_popup .mnu %X %Y

Unfortunately, I could't find any help or example for it... KD

PB: It's easier than you believe...
 menu .mnu1 -tearoff 0
 .mnu1 add command -label "menu 1.1"

 menu .mnu -tearoff 0
 .mnu add cascade -label "menu 1" -menu .mnu1
 .mnu add separator
 .mnu add command -label "exit" -command { exit }

generate a filename automatically


Hello, can somebody tell me how I should generate a filename automatically. I want to use the date of that excact moment and the first three letters of a predefined string.

I hope somebody can help e with this.



NEM Try:
 set filename [string range $predefined 0 2][clock seconds]

where $predefined is the string you mention. If you want the date in a more readable format, then look at [clock format].

variable in child-interp-context


Hi, does someone knows if I can access a variable in child-interp-context?
 proc change_dir { __dir } {
     interp create child
     interp eval child {cd $__dir}

I know, in interp child $__dir does not exists. Is there a way to put a value from invoking interp into child-interp? Perhaps with interp alias? PB - RS: In your case it's even easier, just substitute the variable before calling interp eval:
 interp eval child [list cd $__dir] ;# :-)

01/20/2004 - scrollbars

Hello, I am having trouble with displaying scrollbars after loading a list in windows (98 & XP). I have been using the AutoScroll package [1], however, when I load a list into a listbox, the first time the scrollbars appear, they are disabled, even though my list is longer than the size of the listbox displayed. However, when the window is modified, or the mouse is moved within the listbox, then the scrollbar activates, and remains activated until the window is closed. The problem with deactivated scrollbars only happens once, and once the scrollbars are activated, then the scrollbars begin to function correctly.

Does anyone have any suggestions as to what I may be doing wrong, or what I can do to fix this?

The code below can clearly show what my problem is. If you click on Load once, you will notice inactive scrollbars.

Thanks in advance for your assistance! :0) ~KND
 # remove the following line if autoscroll is on the package path
 source autoscroll.tcl

 package require autoscroll
 namespace import ::autoscroll::autoscroll

  #create a frame for listbox area
  frame .fr

   listbox .fr.list -width 40 -height 10 \
       -yscrollcommand [list .fr.y set] -xscrollcommand [list .fr.x set] \
       -font {Courier 12}
   scrollbar .fr.y -orient vertical -command [list .fr.list yview]
   scrollbar .fr.x -orient horizontal -command [list .fr.list xview]

   grid .fr.list -row 0 -column 1 -sticky nsew
   grid .fr.y -row 0 -sticky ns \
       -column 2; # change to -column 0 for left-handers
   grid .fr.x -row 1 -column 1 -sticky ew

   grid columnconfigure . 1 -weight 1
   grid rowconfigure . 0 -weight 1

   autoscroll .fr.x
   autoscroll .fr.y

  grid .fr -column 0 -row 0

  # create buttons to appear below listbox
  button .button -text "Load List" -command {loadList}
  grid .button -column 0 -row 1 -sticky news

  button .button2 -text "Remove List" -command {.fr.list delete 0 end}
  grid .button2 -column 0 -row 2 -sticky news

  #Procedure to add 25 items to the list.
  proc loadList {} {
   for { set i 1 } { $i < 26 } { incr i } {
     .fr.list insert end "$i This is a long List, isn't it?  Yes, Very Long."

01/20/2004 interp

Hi. With interp-concept I've a small problem in understanding. I hope someone can help me. My claim is to create a parent-application, which creates and controls its children. Each child has a special job. (e.g. checking files in a directory for modifying) The idea is that each child gives regulary an alive-sign to parent (e.g. in a global var). parent checks this sign an set it back. if some child can't renew its state parent kills the prozess and restart it. what I need is a common channel for direct communication, a common access to a global variable. Does someone knows how I can solve that problem?

fw I thinks there are two ways, using "signal" command or pipe communication. Since parent and child are independent processes, they cannot have common(share) memory.

In using "signal", child process sends signal to parent process in period. parent apply event for some signal by using "signal trap ...", and if gets signal, some action performs. You may see "signal", "kill" command and UNIX signals.

On other way, in tclx(tcl extension), "pipe" command can enalble communication for two processes. you may see "pipe", "fork" command in tclx.


I understand. My applications are independent processes and, you are right, they couldn't share their enviroment. But while reading your answer I had another idea: I could use simple network-sockets. So I'm be able to have common pipe for exchanging data ...



Hi, I am nams.

"exec" command cannot return binary data into stdout

In linux, I runs like this :
 set msg [exec tcl read_binary.tcl]

"read_binary.tcl" puts binary data into stdout. "read_binary.tcl" works well by executing "exec tcl read_binary.tcl > temp.dat". But "msg" has only PARTIAL data of whole binary data. I changes stdout into binary using "translation" option of "fconfigure" command, but gets same result.

If "read_binary.tcl" puts not binary but text data into stdout, "exec" command returns whole text data well.

In the result of test, "exec" command cannot return binary data, but return text data well.

What's problem or any solution?

Regards from Nams. Thank you. :)

BR - 2004-01-20 - With exec you can not control the encoding of the data in the calling app, that's your problem. Try open instead like this (untested)
  set pipe [open "|tcl read_binary.tcl" r]
  fconfigure $pipe -encoding binary -translation binary
  set binarydata [read $pipe]
  close $pipe


2004/01/04 I have a question about menus. I have created an icon in the system tray of Windows XP with winico. To create a menu when left clicking the icon, I use the '.topXX.mXX.menXX post x y' command to a withdrawn toplevel. The menu appears but since the toplevel window is withdrawn, the bindings don't seem to work. The selection follows the cursor but the up, down arrows, esc keys do not work and I cannot unpost the menu without activating one of the menu options.

Does anyone know how I could overcome this?

Regards and thanks, Frank H.

write to stdout

MSH 2003/12/12 Does anyone know if it is possible to write to the real stdout from wish under windows ? I have a Tcl/TK program which has a command line fo rbatch control but when called from a batch file I cannot puts to the Msdos window to give user feedback. TCL/TK 8.4.2 with freewrap. PS I added this question to 'Ask, and it shall be given # 2' with no success, does any one read that page ?

BR - 2003-12-14 - wish.exe on Windows doesn't have a stdout, no. That is a consequence of being a Windows GUI app. With 8.4.2, you should be able to use tclsh84 instead. You need to add a "package require Tk" to the top of your script to load Tk as an extension, unless the script already has that. That statement doesn't do any harm if the script is actually executed in wish.exe, so you don't need a separate script for this.

December 9, 2003

Hi, Do anyone know how different between "lsearch" and "info exists" in tcl 8.0?

I has 50,000 fixed-lists and 80,000,000 urls. I test whether url is in fixed-list by using "lsearch".

In other way, I make arrays of fixed-lists and test whether url is in fixed-list by using "info exist"

In result, "info exist" has more faster at least 5 times than "lsearch". What difference?

Regards from Nams. Thanks!

schlenk Basically lists are lists and arrays are arrays. ;-) lsearch operates on a list and has to do a linear search, info exists on an Tcl array is basically a check in a hash table which has more or less O(1), but needs a little bit more memory. For your use case arrays are the better solution.

December 03, 2003

Does anyone know how to disable a listbox? I have searched hi and low and it seems like this scenario is not common. What I need to do with my listbox is to select one item from the listbox, and then, when a start button is pressed, a user should not be able to change the selection on the listbox. I have used the single selectmode when defining my listbox.

Any help is greatly appreciated! Thx.


FW: All you have to do is change the binding for a click to do nothing. To disable the widget, just do:
 bind .a <1> break


I have copied the entire Tcl directory to a new PC and am trying to run the atsh shell(atsh.exe). It gives the following error-"The Procedure entry point _malloc_dbg could not be found in MSVCRTD.dll". I have download various flavors of msvcrtd.dll, but no avail. any help would be greatly appreciated.


01-Dec-2003 - bind / listbox

I have set a bind to a listbox and bind should return the current index of a choosen line (button-1-event). But bind fails at first and returns an empty string. For each further one bind returns the index of the selection before not the current. How I can change this behavior? Thanks for each idea ...
 # Listbox
 scrollbar .sbary -command {.lbox yview}
 scrollbar .sbarx -command {.lbox xview} -orient horizontal
 pack .sbary -side right -fill y
 pack .sbarx -side bottom -fill x
 listbox .lbox -width 30 -height 10 -font {CourierNew 8} -background white \
        -selectmode single -yscroll {.sbary set} -xscroll {.sbarx set}
 grid .lbox -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news
 grid .sbary -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news
 grid .sbarx -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news

 # Filling with real indizes
 .lbox delete 0 end
 for {set i 0} {$i < 4} {incr i} {
        .lbox insert end "Listbox Index: $i"

 # Binding
 bind .lbox <Button-1> {
         set index [.lbox curselection]
         tk_messageBox -message $index

K: Try 'ButtonRelease' instead of 'Button' ...

07-Nov-2003 Tcl_Stat

Tcl_Stat seems crash application when called before any other functions. If Tcl_CreateInterp is called before, Tcl_Stat works fine... Note that Tcl_Stat doesn't need a reference to a Tcl_Interp structure.


#ifndef BUG
  Tcl_Interp *pTcl = Tcl_CreateInterp ();
  Tcl_DeleteInterp (pTcl);

  stat fileStat;
  int retStat = Tcl_Stat ("C:/foo/bar", &fileStat);


Thank you to give me your idea about that.


BM asks How do I alter this code to work in windows? It works fine in linux
    foreach filenm [exec /bin/ls -a [pwd]] {

or better still make it cross platform. I want to process every file (including .. and sub directories) in the current directory.
 1Dec03. Ans: try using [glob *].

Another query... I have just installed ActiveTcl8.4.4.0 in both linux and windows95 and have had to alter all instances of -com ??? to -command ???.

What has happened to the -com command? Thanks

Nov 04, 2003

Newbie asks: I'm trying to create a "yellow stick note" app. I have created a little decoration-less window using wm overrideredirect, and now I need to generate window-moving events so that I can manually place the sticky note. I believe I need to use event generate, but how do I get drag coordinates into a little script, which would (I believe) call wm geometry? Thanks...
 Here's a solution:

 set ::moveable 0
 wm overrideredirect . 1
 bind . <ButtonPress> {set ::moveable 1}
 bind . <;ButtonRelease> {set ::moveable 0}
 bind . <Motion> {if {!$::moveable} {break}; wm geometry %W +[expr %X-10]+[expr %Y-10]}


Newbie responds: Sacrosanct bovine, Batman! You guys sure make it look easy! Just to make myself feel better, I modified your solution so that the frame wouldn't 'jump' to the cursor:
 set ::moveable 0
 set ::X 0
 set ::Y 0
 wm overrideredirect . 1
 bind . <ButtonPress> {set ::moveable 1; set ::X [expr %X-$::X]; set ::Y [expr %Y-$::Y]}
 bind . <ButtonRelease> {set ::moveable 0; set ::X [expr %X-$::X]; set ::Y [expr %Y-$::Y]}
 bind . <Motion> {if {!$::moveable} {break}; wm geometry %W +[expr %X-$::X]+[expr %Y-$::Y]}


I'm using tclkit to run tcl stuff on windows plattforms, but i can't open files under Windows XP. Win 2000 works fine, are there any known issues with Win XP, maybe concerning filepaths? Bernd

Vince -- no, there are no known problems on XP. You'll have to be much more precise about what your doing. Provide a short script (< 10 lines) which works on 2000 but fails on XP. This should be easy if you can't open files.

Well, a single line will do: "set FILE [open test/file.txt r]". This works fine on 2000 but fails to find the requested file on xp. The problem remains when i replace slash by backslash, i'd think both variants should work. There is nothing else in the script i used for my test, the script is wrapped for win using: "sdx wrap tclxp.exe -runtime tclkit-win32.upx.exe". -- Bernd

I'm really surprised now, because i can't even open a file in the same directory ("set FILE [open file.txt r]"). So it's not a slash, backslash problem. -- Bernd

Vince with any bug report, the error message you get is critical. Anyway, I suggest you report this on comp.lang.tcl or on sourceforge, not here.

text widgets

Question on text widgets displaying large files moved to text.

18-Oct-2003 - Winico

I have a question about Winico. I have installed the package and have trouble loading it. After copying the winico03.dll into the working directory, I enter the following: load winico03.dll

I get a cannot find library winico03.dll or one of its dependants. What would cause this and what do I do to overcome it? Thanking you in anticipation.

Tcl Library

I have a question about Tcl Library. I use it for extensions which manipulates lists a lot. The situation is:

#(in Tcl)

set alist $param1

lassign $alist v0 v1

/*(in C)*/ Tcl_Obj *alist, *v0, *v1;

alist = Tcl_GetObjResult(interp);


Tcl_ListObjIndex(interp, alist, &v0);


Tcl_ListObjIndex(interp, alist, &v1);



In other words, I want to get the list first two elements, keep them and then free the list variable for pointer reuse. Do I do this correctly? I obtain some errors in the program.

The above looks correct -- Vince.

Broken Link???

Sep 30 - 2003


I tried the following link that was on the wiki site (ftp://ftp.dcade.de/pub/ml/tcl/packages/tcl_messageBox10.zip) but could not get through. Anyone have any luck as I would like to view this.

Thanks Ep

Tcl Installation/Uninstallation

Sep 30 - 2003

Hi all!

I easily compiled and installed the latest Tcl source code. I was needing it for compiling expect. Now I am done with my tasks, I have successfully uninstalled expect, but I found that there is NO make uninstall available for the Tcl code.

Does anybody know any way to uninstall Tcl source code, apart from searching by date and removing file by file!?

Your help is much appreciated!! Have fun, Oscar

Sep 29 - 2003

How can i use the options(-error,-sockname,-peername) of configure command of socket ? The main problem is, like -sockname option returns three elements so how can i store these values to use further?

Sep 26 - 2003

I want to make a frontend to gcc in tcl.
    if {[catch {exec gcc -c $Compiler_Flags $Filename } Result]} {
      puts $Result
      exit 1

I want to map gcc's output messages to stdout and stderr, while the command runs. I could direct it to a file, but we'll proberbly be running this frontend, several persons at the same time. - RS: Experiment with
 eval exec [list gcc ... > @stdout 2> @ stderr $Compiler_Flags [list $Filename]

Sep 25, 2003 - channel

I have a channel that I have opened as:
 set cid [ socket -server cfg $port ]

From time to time the client times out reading this channel. When that happens the data in the buffer (from a puts command) is no longer valid. I would like to throw it away. NOT flush it, which just sends it to the client the next time the client tries to do a read, but actually empty the buffer and throw the data away. How can I do this? Thank you in advance.

22/09/2003 - control other applications

Does Tcl includes the ability to control other applications, e.g. notepad? Other programming languages provide commands like Sendkey (VB) or Sendmessage (VC). So I can executing notepad, putting text into textbox and saving that in a file. That's all possible because of controlling menuoptions by sending Windows-Messages ... It is possible in Tcl too?

RS: See tcom for COM support, but not sure whether Notepad understands that..

JPT: You could also try cwind (http://wiki.tcl.tk/5019). I've used it once and it did the (simple) job I had to do.

20-Sep-2003 - tk_setPalette

I'm messing around with tk_setPalette I have a problem with the foreground being black on black or more precisely very dark blue this is only a problem with errors which I can't read unless I edit both libs: dialog.tcl and bgerror.tcl. I made the foreground red which is readable. I hate messing with the lib scripts though, is there a way I can do this from within the main script?

16-Sep-2003 - DLL

If I want use binary Library-Code (e.g. from a DLL) in Tcl I need a Library which includes a special Init-Function. Does someone know what functionality that Init-Function have to contain?

RS: See Building Tcl DLL's for Windows for a complete example.

Peter Newman 29 October 2004: See also Ffidl (which allows you to call the functions in foreign DLLs from Tcl scripts).

19-Sep-2003 - makes directory

Question: Is there command or procedure which makes directory?

Since I cannot find it, I have forked 'mkdir' but it's too weight. Like readdir in tclx, is there cammand which makes directory without no fork?

Regards from Nams.

ulis: The command you need is file mkdir. From the file page of the Tcl Manual:

file mkdir dir ?dir ...?

Creates each directory specified. For each pathname dir specified, this command will create all non-existing parent directories as well as dir itself. If an existing directory is specified, then no action is taken and no error is returned. Trying to overwrite an existing file with a directory will result in an error. Arguments are processed in the order specified, halting at the first error, if any.

Older questions that remain unanswered or partially answered edit

go below the following line:

02/09/03 - toplevel-widget

Hi,following piece of code shows the creation of a toplevel-widget (child) inbound a frame of another toplevel-widget (parent). I asked me how I can move the parent-window so that the child-window keep its relative position.
 set xmax [winfo screenwidth .]
 set ymax [winfo screenheight .]
 set xsize 480
 set ysize 360
 set xpos [expr ($xmax/2)-($xsize/2)]
 set ypos [expr ($ymax/2)-($ysize/2)]

 wm title . "parent"
 wm geometry . +$xpos+$ypos
 wm minsize . $xsize $ysize

 frame .main -borderwidth 1 -relief sunken
 pack .main -expand yes -fill both -anchor nw

 toplevel .child -class children
 wm title .child "child"
 wm transient .child .

 bind children <Visibility> {
         raise %W
         after idle {
                 update idletasks
                 set wx [expr [winfo rootx .main]+1]
                 set wy [expr [winfo rooty .main]+1]
                 wm geometry %W +$wx+$wy

I've tried to bind child on parent over motion-event but it doesn't work. Has someone any ideas to solve the problem?

FW: Well, first of all, your code binds for visibility, which will trigger just once when the window becomes visible. To bind for any time the window is redrawn (for example, when it is moved or resized) use the <Configure> event. Your code doesn't have anywhere near all the functionality needed for relative window moving, but I can give you a complete example (I've been meaning to implement this myself as an exercise for a good while too). I just need to know - besides moving relative to the window, do you also want the subwindow to be trapped within it? Or should it be allowed to leave the larger window, but still move relatively?

tje: Does this help at all? Toplevel Geometry Manager includes the <Configure> bindings, etc. needed to make two toplevels "tied" together.

I've cutted out all uninteresting code for that problem. Configure-event I use just to control maximumsize of smaller window, but if I can use it for more ... I'll do it.

Okay, conditions for smaller window are:

* start position should be the upper left corner of frame. It should work like ...
 place .child -x 0 -y 0 -anchor nw

(... but that doesn't work for toplevel-widgets. It would be nice if I could change a toplevel-widget into a frame OR if I could bind a frame onto a toplevel-widget because a frame as container for toplevel is easier to handle than a pure toplevel ...)

* size should be <= frame of larger window

* if larger window have been moving, smaller window have to keep its position.

* and last but not least: smaller window is inbound the frame of larger window at home, that means it's not allowed for it to leave domestic frame.

FW. It would be nice if I could see your example code. I'm just interested in the way how you handle your toplevels.

tje. Do you know how I can two toplevels tied together? Seems to be a way to place toplevels like other widgets with place-command. Do you show me that?

FW: Is the smaller window to be resizable? If so, how should it being resized be handled? Should it snap back to the edge of the frame if you try to resize it beyond the edge?

FW. What's wrong? I thought concept of this formum is: "Ask, and it shall be given", not "Ask, and it shall be asked again". Conditions for smaller window are clearly defined. Sorry, but I only would have an answer of my questions or an idea or hint. My suggestion if you really want to help: read again. it's not so difficult. If you want to talk about programming in tcl, c, pascal or general about developing software send email to: [email protected]

FW: No, it was just a simple addendum question. You didn't specify the case of window resizing, which is rather different. I'm just going to take my best guess, since there seems to be a communication problem here.

FW (again): You're right, I thought you were talking about how to implement the task of constrained windows in general. OK, now that that's all cleared up. Now, you say binding for motion? I assume that means the <Motion> event, for the cursor moving. I realize this is probably getting exhausting by now, but could you describe the problem you're encountering a little more?

FW. So I thought also. I've tried to bind larger window on smaller window with <Button1-Motion>-event, so that if larger window is moved, smaller window is moved too, but no result. How did you solve that problem?

FW: Aha. <Button1-Motion> won't do it, because to move or resize a window (in Windows, for example) you use the title bar or drag the edges of the window. The border and title bar are provided by the window manager, and clicking on them won't trigger any Tk events. As I mentioned earlier, I'd bind to <Configure> to respond when a window is resized or moved. However, you've got to check to make sure the window has actually moved and isn't configuring for other reasons, otherwise needlessly adjusting the geometry will itself trigger a <Configure>, and go into an infinite loop.

[Mth] on Aug-27-2003 - VisualTcl

Hey Guys I have a Tcl/tk application done by a diff developer using VisualTcl. Lateron I have added some Iwidget::dialog boxes to this application. I have blocked/frozen the dialog with "modality=application" parameter. My problem is sometimes these dialog box loses its focus and goes behind the main window & leaving me with only one solution of killing and restarting the application.

- Is there a way to bind a key so that if it goes in the back, by pressing a key (say Ctrl+F5) will bring it to the front.

- Is there a command I could use to keep these dialogs always on top (see that page :)

- Is there any other alternate solutions to it.

Please let me know your suggestions, as I am really desperate to have this issue resolved. Thank you all in advance!

FW: All you need to do is determine the Tk path (ie .dialog1 or however IWidgets names them) of the dialog boxes. Then it becomes pretty easy. Otherwise, it's probably literally impossible. Are you able to do this? I'm not that familiar with IWidgets.


I am trying to write and debug a set of C/C++ extensions. I have complied them to the .so file with the -g flag. I can start my TK application and it loads the extension fine. When I use gdb to connect to the process, it loads the symbol table correctly for the extension, and I can access the names of functions and variables and set breakpoints on the function names. However, I cannot get gdb to access the source code to the extension, which makes setting break points within functions impossible. Does anyone know how to get this to work? I am currently using printf / cout statements, which does not seem very modern!

gtr Answered my own question. Or rather my colleague did - in our Makefile we has a "-s" flag to gcc, that strips all symbol information from the binary file. This appears to override the "-g" option. I have left the original question in case anyone runs into this difficulty.

05/Aug/2003 - C program with included tcl/tk

I want to compile a "C" program in windows/dos environment, which included tcl/tk also in that program. like #include <tclExtend.h> #include <tk.h> etc..

I compiled in linux by giving following options and its succeed.

$(BINDIR)/tcli: tcli.o $(DB_OBJECTS)
        cc -o $@ tcli.o $(DB_OBJECTS) -ltcl -ltclx -lm \
                -L/usr/X11R6/lib -lX11 $${REDHAT4_1:+-ldl}

But in dos version how can I compile from the command prompt, which options I have to mention and how ? I am having the VC++ in my system.

Could you please suggest me !!!

ANSWER: Use an existing VC++ project - and export or generate
        an NMAKE file - study the commands used in the file.

04/August/2003 - hex numbers

(Formerly 31/July/2003, with added details)

I am trying to analyze some hex numbers with odd size bit fields and was trying to write a tool to break up the bit fields. The problem is that I haven't been able to figure out how to enter hex numbers and have them not converted to decimal in the ENTRY field. It's hard to figure out if the rest of the code works when the display keeps changing to decimal on me. Thanks in advance!

Okay. I had vTCL write a GUI where I enter a number at the top which will be HEX in the final version. Then I have fields that allow entry of up to 16 bit-field sizes and a a display area for each field's value. The last element is a "doit" button. The code then figures out how many fields there are and for each field it uses shifts to eliminate all bits outside the current field with the field ending up in the low order bits so it can be displayed. Now that I have the basic GUI, I'll make all the other changes myself. Here's an example:
   Initial number is A5A5, divide it into a 5 bit field, a six bit field and a five bit field:

     15  14  13  12  11  10  9   8   7   6   5   4   3   2   1   0   <-- Bit number
   | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | <-- Bit Value
   | 1   0   1   0   1 | 0   1   0   1   0   1 | 0   1   0   1   0 | <-- Desired fields
           0x15                 0x15                   0xA           <-- Values of desired fields in HEX

The problem is the initial entry of the hex numbers. Here's my current entry command where I've tried to limit the input to hex digits, but it treats the entry as a decimal integer (I currently have to enter decimal to get it to take a number, so I had to increase the field size and chose 8):
     entry $base.ent61 \
         -background white -takefocus {} -textvariable RawHex -width 8 \
         -validate key -vcmd {expr {[string is xdigit %P] && [string length %P] < 8]}

FW: So does it treat the entry as a decimal integer, or actually convert it? You've said both.

Question (12 June 2003) - screen reader Jaws

MAK I recently had a visually-impaired prospective customer, who uses a screen reader program called Jaws [2] evaluating one of my products that uses Tcl/Tk for the GUI. I decided to try it myself to see how the GUI could be improved for such use. Not surprisingly there were some problems, mainly with some custom megawidgets that aren't really conducive to screen reader use, though many would be fairly simple to fix (such as allowing elements to take focus that currently don't). Some basic widgets/elements such as menus and text widgets seem to work okay, others like entry widgets don't, at least the way they're currently used. Some work partly: the text widget speaks when you select text, but for some reason my syntax highlighting causes only parts of the text (the non-highlighted parts) to be spoken.

Perhaps someone has experience writing screen-reader-friendly Tcl/Tk applications and could write a bit of a tutorial or tips page of some sort on developing Tcl/Tk applications that are compatible with screen readers? Thanks.

Note: I did see Speech Synthesis, or Talk to me Tcl but it seems like it might be better to make use of any features inherent in Tcl/Tk widgets to tie into Windows Accessibility features that a screen reader such as Jaws use. Some items work fine, so why not all?

Question (9 jun 2003) - c++ dll library

I'm trying to compile a c++ dll library (under Windows 2000, using Dev-Cpp) that interfaces with tcl scripts. Even if I've linked the tcl83.lib and tk83.lib, and include tcl.h, I get the linking error: "undefined reference to _imp__Tcl_CreateInterp" and other similar. Same error if I try to compile a simple c/c++ program. The strangest thing is that, if I split the tcl functions in a testing procedure in the same file as the main it works. But as I use a different file for the procedure, the compiler gives the same linking error. Could anyone help me? Please write to: [email protected]

Answered Questions  edit

should be moved beneath the following line:


You start two wish-interpreters, wish1 and wish2. In wish1 you create a variable:
  % set x(val1) 0

My question: How can I make x accessable for wish2? Thanks for all solutions or ideas! PB

FW: What OS are you using? Do you mean multiple executions of one interpreter, or a slave interpreter within one application? Are you developing cross-platform?

If you mean multiple applications, you're in luck by using Tcl, which is very strong for inter-application communication. Tk has a built-in send command, and the comm package provides similar functionality via sockets that works cross-platform.

It's even easier with slave interpreters - just look at the interp page to find out how to send commands to a slave interp.

PB: I'm using XP for this project and primarily I try to find an easy concept for an applications conversation and interp is my favorite now. Thank you...

FW: So does that mean you're using slave interpreters or separate applications?

PB: (curios?) I use slave interps althought separate applications would be better. therefore better because if master interp has a problem, slaves will have a problem too. sure, there are possibilities to catch and handle such cases, but that costs a lot of time and time is money. on the other side I have a problem to exchange common data using seperate applications because they run in different enviroments.

FW: Thanks for clarifying. Just use [interp eval] to run commands within the slaves. If and when you start using separate applications, I'd use the comm package (based on the venerable send) for inter-app communication.

14/Aug/2003 - recursive data structure

I am trying to define a data structure recursively and can't get it to work Any suggestions?

The idea is from: http://users.pandora.be/koen.vandamme1/papers/tcl_fileformats/tcl_fileformats.html

I would expect "A=atts" I would expect "B={atta bttb} {cttc dttd}" Then I would expect "A=pins" I would expect "B={pin4 four} {pin5 five}"

I do not get that. I have also tried numerous other things like concat, subst, etc... to no avail.
   proc mycommand { args } {

    foreach { a b } [concat $args] {
        puts "A=$a"
        puts "B=$b"

   mycommand {
    atts {
        { atta bttb }
        { cttc dttd }

    pins {
        { pin4 four }
        { pin5 five }

tje Aug 20 2003 - Try this:
    proc mycommand {in} {foreach {a b} $in { puts "A=$a" ; puts "b=$b" } }

Remember that args is a special argument that wraps multiple arguments into one.

12/Aug/2003 - mouse buttons

Is there a method to emulate a third (middle) button by pressing both buttons together when using a two button mouse?

tje Aug 20 2003 - How about...
    bind Toplevel <ButtonPress-1> {set ::bp1 [clock clicks -milliseconds] ; catch emu2}
    bind Toplevel <ButtonPress-3> {set ::bp3 [clock clicks -milliseconds] ; catch emu2}
    bind Toplevel <ButtonRelease-1> {unset ::bp1}
    bind Toplevel <ButtonRelease-3> {unset ::bp3}
    proc emu2 {} {
        if {[expr abs($::bp1 - $::bp3)] <= 150} {event generate . <2>}

Adjust the '150' to your liking for timing, and populate 'event generate' with stuff you need.

FW: Bear in mind you can often configure your window manager to globally emulate a 3-button mouse.

04/Aug/2003 - for_file

When I am using "for_file" in windows version TCL/TK then I am getting error like invalid command name "for_file" while executing for_file std_msg c:/Tool/iisver {break}

Is for_file command is not exist in windows version, if so, then what's the best way to use in windows instead of for_file ?

lv for_file is a part of tclx. Make certain you have downloaded and installed that extension, and that your application includes a line such as
 package require Tclx

before you use for_file. RS: If you can't get TclX, see the for_file page.

04/Aug/2003 - exec

when I am using below systax executing in tcl/tk, then I am getting error. Syntax is

set dirinfo [exec command.com/c dir]

Error I am getting, when I am executing this is

'invalid command name "command.com/c"'

How can I execute this? Could you please suggest me.

lv does DOS bat magic help? RS Put a space between the filename command.com and the switch /c. DOS shells can do without the space, but Tcl requires whitespace between words.

30/July/2003 - exec

I am facing some problems in tcl/tk windows version I am using tcl/tk version on win 98. When I am using "exec" then I am getting errors. example: set msg [ exec c:\cssplit.exe]; where cssplit is "C" program and cssplit.exe executable file, when executing this, it's giving error "child process exited abnormally while executing exec cssplit". when I am executing batch files then it's givng couldn't execute test-spec.bat no such file or directory, but file is existing, not only this what ever I give with "exec" command all are getting errors. Could you please suggest me to execute this command.

lv I suspect that the problem here is that cssplit is either producing output on stderr or returning a non-zero return code. See catch for a way to account for these two alternatives. Note that it is easier to answer a question when you show us exactly what you type and what the output in return is, than when someone tries to summarize; in cases of errors, more information is likely to be beneficial...

And another question is related to "ctoken". ctoken in windows version tcl/tk not working why? Is there any another method replacing this in windows version tcl/tk?

Could you kindly suggest me.

lv ctoken is a part of tclx, not of tcl. After you do a package require Tclx ; does that help any?

(JULY 30, 2003) - presentations

How does someone make interactive graphics with Tk? I mean, smooth presentations.

Environment of our program is somewhat loaded (many background checks for events), and redrawing of screen leaves it in grey background color for noticeable amount of time. It would be good to at least preserve old picture before draw anything new. What tricks or what methods do you use to achieve smooth Tk graphics performance?


lv by interactive graphics what do you mean? Smooth animation? SZ Yes, smooth change of pictures composed of text and images. When we destroyed previous frame with picture and creating new one we get gray (standard background) regions on a screen for a moment. What technique to use to avoid that? FW: Try reconfiguring the -file for the image, which (I believe) will redraw it without destroying anything.


Hi, does anybody know how I can place console-window on screen? Normally I use this for a toplevel-widget:
 wm geometry . "+$xpos+$ypos"

But for console I doesn't know how to handle it.

Franko - RS: The console runs its own child interpreter. This works for me (Win2k):
 console eval {wm geometry . +0+0}

mille grazie! (ital.)

Question (10 June 2003)

Just to clarify the question below: I am doing a bind as follows (this follows the Russian encoding in TIM):

proc setupIndic {} { foreach {in} { a b bh bhr c th tr dh dhr k kh kr <etc>
                        hr c th tr dh dhr k kh kr <etc>''

} { bind Indic $in "keep_accounts %K; %W delete insert-[del_text $in [get_last]]c insert ; %W insert insert [encode_key $in [get_last]]; break"} }

Now, the proc 'keep_accounts' keeps a track of the keys pressed. The proc 'encode_key' must dynamically encode the character entered depending upon the context, i.e., it must look up the last character to do the encoding. I have made $last a global variable that is set from the proc 'keep_accounts'. However, I am seeing that the proc encode_key receives the value of $last only at start (at the time of bind) and never after. How do I make encode_key use the current value of $last?

If any further clarifications are required, I'll be glad to provide them. Thanks,AB - RS: Hm.. best put all binding code into a single proc that gets %K and %W as arguments. The brackets around del_text etc. will be evaluated too early - at definition time of the binding. I think you rather want them to happen at event time, so put them into the binding proc. Use global variables for maintaining state (like what the last keypress was).

Question (9 June 2003)

I am planning to write an editor for Indic scripts (Devanagari, Bengali, Gujarati etc) using an English keyboard and so the code needs to encode the entered text. I am planning to build upon TIM (a tiny input manager). The TIM uses a simple lookup inside the foreach {in, out} loop for map the entered keystroke and the output which is displayed; however, here things are more complex and each keystroke has to be bound with a procedure that has to dynamically alter the glyphs to display depending upon the context. Can anyone suggest a way to do this? Thanks, AB -

RS: You want context glyph selection, and a simple Arabic renderer might give you ideas in that direction. I've also toyed a bit with Hindi, but one problem is that the Unicode does not include the ligature glyphs, so fonts (like MS Mangal) don't deliver them... But you might have better equipped fonts. Binding a keystroke to a procedure is very simply done; but the implementation of this proc will need a lot of linguistic knowledge. Be assured it's possible, but I have no easy solution at hand.

Question (19 June 2003) - huge file

[SSA] I have got a huge ASCI file generated by an application as a tracefile. Its size is 8.28GB! Now when I try to open this text file in tclsh using the open command with r(ead) permission, an error is generated.
 open "mp3frame.trc" "r"

The error generated is:

couldn't open "mp3frame.trc": Value too large to be stored in data type

Can anyone make head or tail of this and any workaround for the same.

schlenk If you use Tcl 8.3 this can happen, it does not use 64 bit file size pointers, so you cannot open files larger than 2GB, use Tcl 8.4.

July 18, 2003 pdm

Extending Existing TCL-based Programs or Getting Other Interpreters

I would like to add my own commands, written in C, to a third-party program that uses TCL. I have read the books, tutorials, etc about Tcl_CreateCommand and know how to use it. It, however, needs a pointer/handler to the interpreter.

If the existing app does not supply me with a "get interpreter" or "add function" C function, can I get access to the interpreter that the program is using? It doesn't do me any good to define a new interpreter since the it won't be the one the user is interacting with.

Does this make sense? I can explain more if needed. Thanks in advance for any suggestions.

pdm It appears that the third-party program does have an "add function" C function. I am still curious about the original question. I had even considered the nasty hack of writing the pointer to a file in text format, reading it in my C code, converting it to a pointer, and using that pointer for the Tcl_CreateCommand function. Not a production-strength fix!

schlenk You could look for the load command and if it is provided just write a shared library (a tcl extension). See the sampleextension for an example.

Question (10Jul2003)-menu

When tearing off a menu (e.g. from Tk's menu widgets demo). The torn-off palette always appears at the upper-left corner of the desktop (under MacOS X and Windows at least), which is likely to be a long way away from where the actual 'tear off' action took place! Looking more closely at the underlying code, I actually can't see any way to make the torn-off menu appear in its most logical position: with its titlebar under the mouse pointer which was used to tear it off! The '-tearoffcommand' (which is the logical place) doesn't have any facility to discover the current mouse x,y coordinates. How can one do this in Tk?

Answer (from comp.lang.tcl):

menu ... -tearoffcommand mytearoff

proc mytearoff {w menu} {
    set x [expr {[winfo pointerx $menu] - [winfo width $menu]/2}]
    # Subtract 8 so the mouse is over the titlebar
    set y [expr {[winfo pointery $menu] - 8}]
    wm geometry $menu +$x+$y
    global tcl_platform
    switch -- $tcl_platform(platform) {
        "windows" {
            wm attributes $menu -toolwindow 1
        default {
    # Put the focus on the torn-off palette, so the user can move it
    focus -force $menu


This still has the side-effect that the torn-off menu flashes in the top-left corner of the screen before being moved to the correct place. Not sure if much can be done about that...

Question (08Jul2003)

Been working with TK and have a basic question I can't find an answer for. How do I change the default graphic (currently the TCL feather image) in the window decoration to the left of the title text?


MAK - With version 8.3.3 and later you can use "wm iconbitmap $w -default /path/to/image" in your script to set the application-wide default icon, and this works on Windows. Earlier versions required the winico extension to change the icon via script on Windows or to recompile wish to include a different icon at build time.

Question (07 July 2003)

Hey everyone. I'm currently working with tcl 8.3.4. I have a pretty basic question about this language. Lets say I source a file by the name of foo.tcl. Is there any possible way to print out the current filename that you're working with? Thanks in advance!

schlenk Look up info script in your manuals. This gives you the file currently evaluated.

FW: The simplest way is to get the full path is, eg,
  puts "The full path to this script file is [info script]"

. Or to get just the file name, do:
  puts "The filename of this script file is [file tail [info script]]"

. This doesn't work with some cases like symlinks, but I doubt this will be an issue for you.

Question (07 July 2003)

Hey Guys, I am new here. I have an application written with tcl/tk8.3. I am displaying iwidget::dialog windows at various instances of my application. I have the modality on those popups setup to "global". So the idea is, if there is a popup the user will only be able to click on the dialog box. Unfortunately when the application receives other signals my popup gets pushed behind the main window and makes my appication totally useless. :(

My quesition is, how can I put all my popups inot a "Always on top" mode? I tried the "wm transient .dialogbox ." and it didn't help. Any suggestions please.

Thanks in advance.

FW: See Always on Top, perhaps?

Question (6 jun 2003)

I have a Tcl/Tk script which I have used on flavours of redhat since V4.2. However when used on RedHat 9 all text labels appear double width (i.e. each character has a space - shown as a 'square') between it and the next character. I have searched everywhere for any reference to this problem on the web but no-one else seems to have encountered it. Can anyone tell me what the likely cause may be ? - paul / RS: You seem to be bitten by RedHat 9's incompatible Tk build, which makes Unicodes 4 bytes wide instead of two. You might rebuild Tcl/Tk with the original sources, or maybe get a prebuilt binary to replace the RH bugger.

Question (06/06/2003)

if some one can help me with this question, i'll be very greatful. i want to write a program in tk . the program will make the graphical user interface to assist the novice to use unix command ln. the tk program must have atleast 10 options availaible as buttons. Options that are mutually exclusive must be grouped as radiobutton groups. On line help/explanation of each support option must be availaible to the user preffrably by double clicking (or other means) the button concerned. Default option if any should be pre selected. A start button will start executing the unix comand . Output from the unix command should be displayed on the tk text window. the unix command is ln. i 'll be very greatful if someone can solve this one for me. if anybody can't put the solution here can they e-mail it to me at [email protected] thnx.

Question (05/30/2003)

Say i have 2 servers up and running, now as a cleint how can i get a choice to connect between the 2 servers, without prior knowledge about their address and port number?? Or simply said how do i get a list of the existing servers?? -- sudhi

DKF - There's no truly general solution to this (other than something disgusting like port-scanning!) though one cheap trick is to use a well-known hostname and port (e.g. insisting that the server runs on a machine with a known alias in your local DNS and on a predefined port.) Other than that, you're asking for a service registry, and this is indeed a component of all higher-level RPC systems...

Question (05/30/2003)

Thanks for the continuous answers i'm getting.I'm able to login using the serial port connection and also execute process listing (ps -aef) on the remote solaris machine. As of now i manually type in the password, but i need to send the login name and password in the background and login. As was told i downloaded Expect and tried running the Expect commands on the TCL prompt but it says "Invalid Command". How do i integrate Expect commands inside the TCL script because i'm expected to complete this project work using TCL scripts and not anything else. Can Expect commands be embedded inside TCL script and if so how do i run it. Can't i do the above in TCL itself.

FW: Some very basic features are provided at expect in pure Tcl. Does that help?

Question (05/28/2003)-beep

Hey guys I am try to write a Tcl script that works both on Windows and Linux. All what I need is, when there is an event happens in my application I want to play a BEEP. I don't want to use SNACK because of the Hardware requirements. I am focused strictly towards the internal speakers. In order for me to test this, I wrote a script that calls the "bell" command. It works on Linux but not on Windows! Does anyone had the same problem before? Any info is really appreciated. Thanks!

kroc: bell is a Tk command. Try "puts \a" instead.

Question (05/26/2003)

append var string isn't exactly parallel to lappend var list', in the first case you can combine a string of length x and a string of length y and get a string of length x+y, in the second case you can combine a list of length x and a list of length y and get a list of length x+1. What's a good way to get the list of length x+y? Best I can think of is foreach element $list {lappend var $element}, or eval lappend var $list

There is a slight mismatch and you have discovered the right answer to the problem. Another possible solution would be:
  set var [concat $var $list]

or (maybe faster):
  set var [concat [lindex [list $var [set var ""]] 0] $list]

Question (05/26/2003)

My last posting was on the 05/15/2003 regarding the serial port. Thanks so much, in fact i had lost hope because i kept checking for replies everyday but could not find any. Today when i checked i found the answer and was overwhelmed. Actually my requirement is as follows. I need to login to a Solaris machine through a serial cable connection (com1) from a Windows computer. Then run process listing (ps -aef) on the Solaris machine, tail the output, parse them, get back the results and store it as a file back on the Windows machine. Please help. Thanks so much.

As told before expect is perfect tool for this, but Expect for Windows is a bit of unfinished, not everything works, for your task though it should be perfectly ok to use the unfinished port from david graveraux. If not you could use cygwin and its expect binary for a unix environment on windows. For the details of the scripts you should read the book BOOK Exploring Expect or the expect webpages.

Question (05/16/2003) http and cookies

Similir to "An Http Robot in Tcl", I'm interested in creating a tcl script using the http package that allows me to log in a website that I subscribe to with username and password and get to the subscriber pages; following the example, I viewed the html source to find the form method is "post" and the form name strings of interest, so I used the lines below:
  set query [http::formatQuery UserName $user Password $passwd]
  set http [::http::geturl $url -query $query]

However, I believe the site is relying on cookies as well. What else do I need to do to handle the cookie requests within the script to get beyond the login screen and get to the pages I'm interested in getting to automatically? If it helps, the url looks something like this: www.website.com/Login/Login.aspx?reqpage=/sub/subfolder/page.htm Thanks!

Question (05/15/2003)

I need to connect to a machine using the serial port, poll that machine at 5 minute intervals and be able to send traps. Thanks in Advance, Chacko.

Follow the links to the man pages from Serial Port, if you want to send SNMP traps you should take a look at Tnm/Scotty/TkInEd, for other automation tasks expect is The Best Tool.

MIB Smithy SDK also supports sending traps, though it may be overkill for your project.

Question (05/12/2003) Image Brightness and Contrast

Is there a quick way of adjusting an Tcl/Tk image's brightness and contrast levels. Currently I have a C funcion that does this by recalculating each image pixel based upon the brightness and contrast level, but to update the image display I need to pass back the entire image, which takes time. I am looking for a solution that is much quicker. Using XWindows/MOTIF I was able to do this by directly changing the colormap for the image, is there something similar for Tcl/Tk?? I have seen some things related to colormaps in Tcl/Tk, but there is very little written about them it seems. Thanks, Alan.

Question (05/12/2003) atoi

Hi, I'm looking for a function in Tcl/Tk such like atoi() in C or ord() in pascal.

RS: atoi() parses an integer from a string. Tcl parses integers from strings whenever it needs one, without you having to call a converter. ord() converts a single char to its ASCII integer, right? Then use scan with a %c format:
 set outint [scan $inchar %c]

Question (05/07/2003)

I am trying to write a tcl/tk program for windows which is stand alone ie the user cannot escape out to windows, I have used the overridedirect to remove the controls but I am having problems with the famous CTL-ALT-DEL, does anyone know of a simple way to block/intercept/... from within tcl (registry) or an extension DLL or (last resort) in c/c++ to add a DLL. I'm using freewrap for the distribution and the option to pass on standalone can be activate from within the application. - RS: I'm afraid no user software can intercept Ctrl-Alt-Del - that's why it triggers the login, for instance. - JPT: Using the DLL extension, you can achieve what you want (on win95/98) with the following call:
  to disable CTRL-ALT-DEL: ::dll::call user32.dll SystemParametersInfoA v {i 97} {i 1} {i 1} {i 0}
  to re-enable it: ::dll::call user32.dll SystemParametersInfoA v {i 97} {i 0} {i 1} {i 0}

Question from amarnr concerning displaying text in a text widget moved to text.

Question (05/01/2003)

I am a tcl/tk newbie, and would like to know how to control the positioning of windows on the terminal screen when they pop up. If I run the same wish script multiple times, I would like the windows to appear so that they are visible in their entirety, if possible. The current behavior is that they pop-up in a cascading fashion, each overlaying the previous ones. Thanks for any guidance you can offer.

Answer (05/01/2003) The initial placement of a program's window is in general a window manager issue. Many X Windows based window managers are quite smart in their layout while Windows is notoriously bad. That being said, a tcl/tk program can help in creating good layout. The key command is wm geometry which lets you place a window anywhere on the screen. The hard part is figuring out the best place to put it--only the window manager knows the placement of all the other windows. But for the problem of running the same wish script multiple times then there are some clever solutions. One way is to use the send or dde command to have the programs talk w/ each other to figure out layout. Another way is to always place the Nth instance of the script in a fixed location and spawn the ps command (or tlist on windows) to determine which instance you are.

Question (04/08/2003)-tcl-compiler

Hey Guys, this site rocks! Now to my question..., I have an application written in ActiveTcl-8.3, I like to compile my tcl script into a binary. Is there a free version of the compiler available out there? I try to use procomp and it is looking for a license! Please help! Thanks! Answer (April 11, 2003) See deployment

Question: (4/08/03)

I am a novice at Tcl. I would appreciate some suggestions for script to extract a single word (variable) from the body of an Email Webform. There are no keywords or other delimiters to use as a reference, because the text immediately before and after this variable is not constant. However, the word always appears as the first word on a specific line of text. Any suggestions would be most welcome. Thanks, David Dantes. [email protected]

FW: Do you have the data stored in a variable already? If so, let's assume it's the third line. It's as simple as this:
 regexp {^(.+?) .*$} [lindex [split $text "\n"] 2] text word

will place the relevent text into the variable word.

Question: (4/07/03)

Hi yall. I have tcl code that uses a command pipe to send commands to a daughter process. How can i send an interrupt signal (specifically Control-C) to the duaghter process? Would i use the command pipe at all? Thanks everyone.

DL: You would use the command pipe if it's a pty. If you're not using Expect, it almost certainly not a pty. In that case, just send a signal using kill (from C code) or TclX extension or exec kill on a UNIX box.

QUESTION: (07-Apr-03) - Tcl_CreateInterp

Hi All, I am using Tcl_CreateInterp to create multiple tcl interpreters which dont need to communicate with eachother. It seems to work fine but is it ok to do this OR should I be using Tcl_CreateSlave etc? If so does any one have a piece of sample code? thanks a lot! -KG

Question : [4/02/03]

(See Update below) Hi! I am trying to create a dynamic table which is basically many rows of iwidget::combobox. User should be able to add a new row to the end of the table with a pushbutton. The limit on the number of rows is limitless or a large number. This I can do, but when user is playing with one of the comboboxes, I need to know which one user is playing with. In other words, if user is picking the combobox on the second row, I need to know that it is the second row. Since the table is dynamic, I cannot have hardcoded row numbers to each combobox. If I send the row index to a procedure as a variable, like in the code below, the variable is constantly changed and the command always recieves the last row index. How can I get the row that the user is in? Thanks!
 proc addRow {} {
   global row_ix

   iwidgets::combobox $w_btch.table.prj_entry($row_ix) -command {thisRowClicked $row_ix}
   grid $w_btch.table.prj_entry($row_ix) -row $row_ix -column 1

   incr row_ix

UPDATE - [4/03/03]

Somebody helped me fix this problem and wanted to share... Instead of defining the command arguments in braces, make a list as in;
 iwidgets::combobox $w_btch.table.prj_entry($row_ix) -command [list thisRowClicked $row_ix]

Thanks Jeff!

FW corrected the formatting in this question.

Question : [3/29/03]

How do you prevent unix commands (e.g. clear, ls, rmdir etc) to trigger the eof and eeof status in the text entry box?

Question : [3/28/03]

I'm running Tcl/Tk 8.4.2 on Win2000 and having some trouble changing background colors on menus. I can change background in all other widgets but for labels of cascade menus added to other menus like you see on a menubar. Is there a trick to this? I've even tried
   options *Menu.background white startupFile

upstream. Thanks, jtg [3]

MGS [2003/03/30] Haven't tried this, to see if it answers your question, but your syntax above is incorrect. Try:
   option add *Menu.background white startupFile

In fact, on Windows, I think colors for all native Windows widgets are controlled by the Windows display properties. so you may not be able to change the colors at all from within tcl/tk.

Question : [3/27/03]

Is there any method to know the underlying OS from within a script. sudhi [4]

See: tcl_platform

photo album

Hi I am a tcl/tk dummy. I have created a simple tcl/tk based photo album. I like to make it look sexy with some cute backgrounds/canvas. Does tcl/tk support this feature? If so..., where should I be looking for information? Thank you folks!

FW: Depends on what you mean. You can put images in an application, or place buttons on an image, or use a canvas to create custom widgets or draw shapes... what sort of stuff do you need, exactly?

Bear in mind, the software industry is heading towards encouraging a consistent look-and-feel with other applications rather than flashiness, so my main goal in the decoration of an interface is usually to make it look familiar.

Hey Thanks for that reply. I was thinking about the common look and feel too! Say I wanna create a windows xp look and feel (hope its not too much for tcl/tk!). Or even something colourful like QT Front ends.

FW: Well, Tk looks averagely native on Windows XP (uses the correct scrollbars and such). It adapts to match the look and feel of the platform it's on to some extent. The colors on all the widgets are tuned to match the current platform and such, and the overall look is also maintained, but there still are a couple shortcomings you may want to consider. The buttons, for example, still aren't quite native in appearance (they look like ones from earlier versions of Windows), but you could simulate them by using the 'SystemButtonFace' color and building up a very approximate likeness using a canvas. However, the old-style buttons are fairly common in XP applications, so people don't really tend to even notice. Most widgets let you customize the background, foreground, and relief style (flat, groove, raised, ridge, solid, or sunken) - but any customized widgets beyond that have to be made with image and/or canvas-based simulations. I myself am making a custom look-and-feel application, and I intend to use images that swap with click events for the buttons.

Question: [3/22/03]

I am responsible for maintaining a C++ application with a Tcl interpreter embedded in it. I need to modify the application to contain multiple Tcl interpreters, each running in a different thread. These interpreters need to be able to execute scripts concurrently. I also need to load a set of user-defined C extensions into each of these. I have compiled Tcl with the flag that enables threading, but I'm stumped as to how to proceed. I have tried creating threads in C++, but Tcl_DoOneEvent hangs/kills threads when I try to run it in two threads simultaneously. I replaced this with a C++ event loop for each thread, but then Tcl_Eval hangs/kills threads.

How do I create threads containing a Tcl interpreter that will wait for and process commands/scripts until told to terminate? Essentially, the process needs to behave as though it contains multiple instances of tclsh. This process run on a Unix platform.


GUI - disable exit

I am creating an application using Tcl/Tk. I like to disable the ability to exit out of the GUI by clicking on the "X" on the upper right hand corner. How do I do that? I am a dummy for this place as well as for Tcl/Tk. Any info is much appreciated. Thanks!!

Answer: See: Catching window managed events

TCL at sonic speed? 11 Mar 2003

What about speeding TCL up a bit (read: lot)? TCL is slow compared to Perl, Python and even Ruby and the question ponders me what can be done to improve TCl's performance? Just wait for Parrot?

FW: You're just plain wrong. Look at the numbers [5]. However, if you insist on speeding Tcl up (which if you sped it up much more would be making it generally faster than the aforementioned languages), there are a few ways. Some minor startup speed decreases can be attained by using one of the bundling packages which stores Tcl as bytecodes rather than source, avoiding compiling expense. You may also use the ICE Tcl "compiler," which really just translates Tcl to C source code using Tcl libraries to do much of the work. It results, as of its last release, in approximately 30% faster code. It's pretty old, though, 1998, and uses Tcl 8.0.

Can one implement C unions in TCL? 12 Mar 2003

Basically my problem is that I need to read and write fixed length records but a requirement is that I can "somehow" associate field names with the fixed length record and manipulate those the data via those field names and write out the record. I can use binary scan/format happily enough, but it would be nice if I didn't have to "unpack - binary scan" or "unpack - binary format" after reads and before writes. Is there any hope for me?

file lock?

There are several processes which can access some file, say a.dat The rule is that only one process accesses a.dat at time. More detaily, if some process accesses it, others waits for unlocking.

So, I used "flock" in tclx.

Each process do : 1. give a.dat read-lock 2. reads data 3. write data 4. unlock read-lock

but, I have some problem.

First it didn't work "flock". see this source :
 set hFile [open aaa.log r]
 puts "hFile1 : open r"
 flock -read $hFile
 puts "hFile1 : lock "

 set hFile2 [open aaa.log r]
 puts "hFile2 : open r"
 puts "hFile2 : read - [gets $hFile2]"

 funlock $hFile
 puts "hFile1 : unlock "
 close $hFile2
 close $hFile

I expected Error at "set hFile2 [open aaa.log r]" since "flock -read $hFile". But, there is no error. What happended?

Seconds, althought flock works well, since flock have not filename as parameter but file-channel, I must open file first and lock it. If this happened, it is wrong but possible.
 process1 : set hFile [open filename r]
 process2 : set hFile [open filename r]
 process1 : flock -read $hFile
 process2 : flock -read $hFile
 process1 : read data
 process2 : read data

So, what I misunderstands? And how use file-lock so that only one process accesses some file?

Regards from Nams.

mailto:[email protected]

How do I call from within Tcl/tk an external Unix library function?

 Like initscr() from /libncurses.so
 Regards, Norman.

Answer (tentative): Use Critcl to wrap the function in question - note that the functions from the ncurses or curses library assume control over the terminal that may not be actually there.

ncgi/cgi.tcl : blank/unspecified argument

Q) FW: Is there any way to distinguish a blank CGI argument from an altogether unspecified one using ncgi/cgi.tcl? Thanks.

Q1.) please any one reply to this question. My problem is "while compiling any tcl -c program the following error is being displayed
  *in function 'main'
              undefined reference to 'tcl_appinit'
               undefined reference to 'tcl_main'
  *in function 'tcl_appinit'
                undefined reference to 'tcl_init'
                 undefined reference to 'RandomCmd'
                  undefined reference to 'tcl_createcommand'
    collect2:ld returned 1 exit status

Please if any one know the solution please mail to
                [email protected]
                [email protected]

January 22, 2003 -Iwidgets::tabnotebook index

I am trying to use the index method of the tabnotebook of Iwidgets v. 4.0.1... My problem is that when a space exists in the tab name, index always return's -1. Here is an example:
 package require Iwidgets
 iwidgets::tabnotebook .t
 .t add -label "Hello"
 .t add -label "Goodmoring"
 .t add -label "See ya"
 .t add -label "Howdy"

 # => 0
 .t index "Hello"
 # => 1
 .t index "Goodmorning"
 # => -1   --------------- this is the problem here
 .t index "See ya"
 # => 3
 .t index "Howdy"

Does anyone know how I can find the index of a given tab name? -- jnc

MSW: As the "See Ya" Example works, I'm just guessing that you typo'd just like you did on this page ? (Goodmoring vs. Goodmorning) (I know exactly nada about iwidgets btw, just saw the typo)

jnc: Yes, I just typed it into the screen here, however the See ya does not work for me (copied right from my code above). Here, however, is a more clear example:
 package require Iwidgets
 iwidgets::tabnotebook .t
 pack .t

 .t add -label "Hello"
 .t add -label "Goodmorning"
 .t add -label "See ya"
 .t add -label "Howdy"

 puts [.t index "Hello"];       # => 0
 puts [.t index "Goodmorning"]; # => 1
 puts [.t index "See ya"];      # => -1  --> this is the problem here (-1)
 puts [.t index "Howdy"];       # => 3

 puts [.t index "See ya"]; returns -1 when it should return 2.

January 22, 2003 - send/expect / spawn_id invalid

i have the same problem, as in the question number 63 in FAQ. After first send/expect is spawn_id invalid. This Problem exist only under Windows, don't under Linux. I try to solve it for Windows.
 set serial [open "com1:" RDWR]
 fconfigure $serial -mode 38400,n,8,1
 set process [spawn -open $serial -noecho]
 puts "\n\nSTART\n"
 expect -exact "Press Ctrl-C to bypass this."
 puts " -trying to abort the boot procedure......"
 send "\u0003"                    procedure......"
 expect_after {                             # on this way I'm coming forward for one step only
   eof {puts "\n eof \n"}

 expect "YAMON>"
 puts "\n problem1  Done \n"
 puts "\n ........\n"
 puts "\n ........\n"
 send "set whatever\n"                     # here the problem return, spawn_id is invalid
 expect "YAMON>"
 puts "\n problem2  Done \n"

After each expected String is EOF set, how can i ignore it? Thank you for your efforts Alex

December 11, 2002 - Wikit on the web

I downloaded Wikit. Everything worked the first time and I was making my own structures within 5 minutes.

I downloaded tclhttpd. Everything worked the first time and I had a server up that I could access locally with Netscape within 10 minutes.

I wanted to use Wikit with tclhttpd and look at the Wikit pages with Netscape, and I'm completely lost. Tclhttpd has a bewildering variety of ways to work, beautiful stuff but I don't see which of them works with Wikit. The info here about making Wikit work with Apache is marked obsolete. I get the impression I'm missing something simple and obvious, but what?

Map27 Interafce

Has anyone used TCL to send and receive information from a Map27 interface card. Usually located in the back of a MPT1327 complient Radio Transceiver. Or even played with Map27 at some stage. If so please drop an email to [email protected]

itcl/tk app hogging resources

I've inherited a somewhat large itcl/tk app. On disk, it has nearly a meg of tcl code, and around 10 megs of data (most of which is also tcl code). When it's running, it eats up nearly 300 megs of ram and some of the time saturates a 2 GHz CPU (at which point it sometimes seems to "lock up"). I want to find and focus on the parts of the application which are hogging the most resources.

Typically, there's a few "hot spots" in an application like this which, if addressed, give huge gains. So, typically, it's not necessary to profile the entire application -- instead you can usually rely on some simple sampling techniques to figure out where most of the resources are going.

In other language environments I've tackled this kind of problem by random sampling in space (look at a random spot in memory and see what's there) and in time (interrupt the program and see what it's doing). But I don't know my way around tcl well enough to do this here.

Also, while I have managed to capture some timing statistics, I'm concerned that the technique I've used (modify the code to keep track of time spent in a location) isn't very good for an application with data-dependencies which border on real-time. I'm worried that the measurements distort the results, and no single instrumentation technique is very universal.

I've concluded that it's spending most of its time in event handlers (in a compartmented interpreter), but I don't even know the notation to use to reach inside that interpreter for analysis (and just interrupting it and seeing where it's at a few dozen times would do a lot to prove/disprove whether my analysis thus far is on track). And I don't know how to weed through all the objects to find out which parts of which kinds are taking up most of the space.


window manager closes tcl script

Q) Please tell me how to prevent window manager closing my tcl script without giving a warning.

This code catches the close button, alt-F4 etc, but not a logout (eg Start -> Shut Down in Windows):
 # Catch window being deleted (icon or otherwise)
 wm protocol . WM_DELETE_WINDOW {
        if {[tk_messageBox \
                    -icon    question \
                    -type    yesno \
                    -default no \
                    -message "Do you want to go?" \
                    -title   "Quit Application?"] == "yes"} {

I want to be able to interrupt the shutdown and carry on running the script.

Thanks -Chris.

optcl / tcom : enter data in msword

Q) Does anyone used optcl or tcom to enter data in a msword template or form? I could use some sample code on that. Can anyone help ?


Q) I use TkpGetColor to get color pixel and Xlib to draw line on tkcanvas:
 tkColPtr = TkpGetColor(tkwin,"orange3");

It draws the line correctly in orange color on 8bit (256 colors) display mode but wrong color (blue or gray) on 16bit or higher display mode! Can anyone help?


Q) i have this tcl program that i called "gnubidlg". it functions as a service routine/driver for the gnubi test box. gnubidlg opens another file that contains SCPI commands that it sends to the test box. here is an example of how a user would call it:

gnubidlg ip_addr=gnubisat5 scpi_file=id_board slt=1:4

 ip_addr   = gnubisat4 | gnubisat5 | gnubisat6
 scpi_file = cfg_ds1 | vfy_ds1 ...
 slt       = 3 | 4 | 3:18

gnubisat4, gnubisat5, and gnubisat6 are aliases for IP addresses. The values for the scpi_file parameter are SCPI Command file names that contain a line such as: SYST:BOAR(@$slt):IDEN?

the values for the slt parameter are either a single slot number or range of slot numbers.

my problem is that when the line is read from the scpi_file the following line is sent to the Gnubi box:


i.e., the $slt variable is not substituted with the value passed in the call. i've tried numerous solutions, like upvar and uplevel but can't seem to get it to work.


Q) Where is the latest pre-compiled version of winico?

upgrading older Tcl code

While I understand and acknowledge that the Wiki has pages detailing differences between versions, I would love to see a series of articles discussing specifics of upgrading older Tcl code to newer versions - such as Tcl 7.6 or 8.0 to 8.3.x ...


Anyone have Tk-style config/cget behavior coded up in Tcl? The Tk_SetOptions family of functions is easy to use, but it seems silly for that to be the only reason my extension requires Tk. If no one has done this, I'll have to bite the bullet. SCT

Somebody must have done this--that's what I keep thinking, but I have no definite memory of ever coming across it.

tclPro / self-extracting files

I was downloading the tclPro 1.4 as well as the Optional C programming libraries for the Windoze platform. It says that the tclpro141.exe is a self-installing executable. that worked fine, but to install the optional C libraries I need to << extract it into the installation directory of TclPro. >> What does that mean, like how do I install a self-extracting files into a <<installation directory" of another extracting file. Am I missing something here?

Answered Questions edit

03/07/2003 - stderr

Question: The default stderr channel in Tcl is not readable. Can I reopen this channel in read-write mode?



Answer: I will answer my own question. Just close the stderr, then open another channel (for example, a file for writing). Please see the code below:
 % proc outStderr {string} {
 %   upvar 1 $string str
 %   puts stderr $str
 % set string "This is an error message!"
 This is an error message!
 % close stderr
 % set errFile [open "error.log" w+]
 % outStderr string
 % cat error.log
 This is an error message!

I swear this didn't work before I ask the question!

mailto:[email protected]


Q) All the code in the wiki to send mail assumes the existence of sendmail or a known mail gateway to do SMTP.

I want to just pass the mail off to the default client app (presumably already configured with the knowledge of how to hand off or buffer outgoing mail).

Thus, it seems to me that most of the SMTP examples here on the Wiki are wrong (or at least misleading). Does anyone have REAL code to pass outbound email to the default client?

A) [Someone replies]: Isn't it that most of these examples work on Unix/Linux systems, and you are asking for examples that will work on Windows in an environment where you don' t have access to an SMTP server?

[Someone else replies]: Have a look at the AlphaTcl mailMenu package [6]. It can do this kind of thing in a variety of ways. There doesn't currently seem to be any Windows method implemented in it, but if that is what you need then the authors of that package may well be interested in a collaboration on the problem. (In case Alpha/Alphatk is news to you, then check out http://alphatcl.sourceforge.net/wikit/ and the links there.)

[Alastair Davies replies]: It is quite straight-forward to Use Windows default mail client to send email.


Q) How can I remove the title bar and borders of a window (and anything else which the window manager adds) without removing its entry in (for instance) the Windows taskbar? -FW

A) ALOVE The method below works great on WindowsXP and I suppose it will work on other operating systems too. Just click on the "minimize" button or the <Escape> key. The trick is to use <Expose> to detect that the window is being deiconified. The "focus force ." is necessary for Windows, otherwise the <escape> doesn't work until you click on the window first. - 6 May 2004
  package require Tcl 8.4  ;# other versions??

  wm title . "Minimize Test"
  wm geometry . [winfo screenwidth .]x[winfo screenheight .]+0+0
  update idletasks               ;# updates the full-screen
  wm overrideredirect . yes      ;# removes window decorations
  wm attributes . -topmost yes   ;# stays on top of other windows

  frame .x -highlightthickness 0 -bg #c8efff
  place .x -x 0 -y 0 -relwidth 1 -relheight 1

  button .x.min -text "Minimize" -bg #ffdbff -font "arial 10 bold" \
    -command x_iconify
  place  .x.min -x [expr [winfo screenwidth  .] - 140] -y 10

  button .x.end -text "Close" -bg #ffdbff -font "arial 10 bold" \
    -command "destroy ."
  place  .x.end -x [expr [winfo screenwidth  .] - 60] -y 10

  bind . <Expose> "wm overrideredirect . yes; focus -force ."
  bind . <KeyPress-Escape> x_iconify

  proc x_iconify {} {
  wm overrideredirect . no
  wm iconify .


I installed the Threads 2.4 package. Does anyone know a good source to find all the commands that the threads 2.4 package provides AND some simple example code of them in action. I have looked everwhere and found nothing!!!! thanks. email: [email protected] -Brian

A) Jan. 22: The doc is inside the package, for usage examples you could look at the test suite under tests.

incr Tcl - private variables

Q) When debugging an incr Tcl application, is there any way of examining private variables of an object? Or do you have to go through and change all "private" to "public" when debugging incr Tcl?

A) JPT: Suppose your object is names obj, you can list all? obj's variables and their properties with something like that:
  foreach item [obj info variable] {puts [obj info variable $item]}

Also, is there a way of getting array names of a public array variable, or do you have to go through and build accessor methods for all public array variables when debuggin incr Tcl?

January 16, 2003 - imitation of digit of number

I am testing some hash function with large prime of 10 digit like "unsigned long" in C/C++. But in tcl, prime of 10 digit is overflowed. I thinks there is other method for handling numbers more than 10 digit. Is there?

Regards, Nams. mailto:[email protected]

A)Jan. 22, 2003: There is, either use 64bit enabled 8.4 release or use Mpexpr, an extension for handling large numbers.

Feb 19, 2003

Q) Why when I search for 'vfs' doesn't the page tclvfs show up in the results?

A) LV because the Wiki search looks for words that begin with the string you entered as a search term.


(unknown date - moved from bottom)

Q) HI. I am new to TCL/TK.while using Iwidgets::scrolledtext , automatic focussing is not possible even if I use focus -force command. what is the remedy??

A) JPT: I had the same problem with the entryfield widget. What I've done is set the focus on the entry component inside the entryfield. I suppose you could try something similar with the scrolledtext:
  # .ef is the entryfield
  focus [.ef component entry]

Question about using an 'undo in a text widget moved to text.


FW: How does glob sort its results? It appears to be alphabetical usually, but using braces for example seems to alter that.

LV: glob doesn't sort its results. The man page states, in part:

The glob command differs from csh globbing in two ways. First, it does not sort its result list (use the lsort command if you want the list sorted). Second, glob only returns the names of files that actually exist; in csh no check for existence is made unless a pattern contains a ?, *, or g construct.

February 10, 2003 - resize a toplevel window

When a user resizes a toplevel window I want to get a continuous feedback about the window's dimensions, so that I am able to display that on a label and user can set the exact size. The problem with <Configure> event bind is that it is fired at the end of the resizing operation.I want dimensions 'live' during resizing.

Neo [email protected]

A(s): Februrary 19, 2003:

Dunno how to do that, but did you think of offering an input dialog where the user can set the dimensions of the window via wm geometry ? when you use scales e.g., can resize 'live', too :) (an example of this is sizepanel)

See also sizeinfo.

January 6, 2003 - fork and signal

Hi, I am newbie about tcl/linux.

I want to fork 5 childs. Then, there is 6 process, one parent process and five child processes.

My Object is : Parent process must be able to manage child processes.(Interrupt/Stop/Continue)

For example, if one of childs exits abnormaly, parent process finds it and sends SIGINT to other childs that some process exits abnormaly. Then, other childs exits. Also, if parent needs to stop childs to fix source code, parent sends SIGSTOP to childs that childs must stop. Then, childs can stop. Last, if parent needs to continue childs which has stopped, parent sends SIGCONT to childs that childs must continue. Then childs can continue.

This is my object. In a word, parents can manage(interrupt/stop/continue) childs forked.

here is two sample for test.

== main script ==
 proc DoMainSIGINT {} {
    global lsChildPID
    puts "\[Parent\] gets SIGINT(interrupt)."
    if {[info exists lsChildPID]} {
        foreach nPID $lsChildPID {
            kill 2 $nPID
            puts "\[Parent\] puts SIGINT(interrupt) to Child \"$nPID\"."


 proc DoSIGINT {} {
    puts "\[child [pid]\] gets SIGINT(interrupt)."

 proc DoSIGQUIT {} {
    puts "\[child [pid]\] exits normaly."

 proc DoSIGSTOP {} {
    puts "\[child [pid]\] stoped."

 proc DoSIGCONT {} {
    puts "\[child [pid]\] coninue to progress."

 signal trap SIGINT DoMainSIGINT

 for {set i 0} {$i<5} {incr i} {
   if {[catch {fork} nPID]==0} {

       if {$nPID==0} {
            # Child process
                keylset klsList SIGCONT 25
                keylset klsList SIGSTOP 23
                signal trap SIGINT DoSIGINT
                signal trap SIGQUIT DoSIGQUIT
                signal trap SIGUSR1 DoSIGSTOP
                signal trap SIGUSR2 DoSIGCONT

                while {1} {
                    execl ./subprocess

                exit 0

        } else {
            # add PID
            lappend lsChildPID $nPID
    } else {
        # fork failure


 puts "Child PID List  : $lsChildPID"

 set nCount 0
 set nExitCount 0
 set nChildNum [llength $lsChildPID]

 while {1} {
        incr nCount
        incr nCount
        if {[set lsMsg [wait -nohang ]]!=""} {
            puts "\[Paranet\] $nPID is terminated. $lsMsg"
            incr nExitCount

        if {$nExitCount==$nChildNum} {

        if {$nCount==3000} {
            foreach nPID $lsChildPID {
                kill SIGUSR1 $nPID

        if {$nCount==6000} {
            foreach nPID $lsChildPID {
                kill SIGUSR2 $nPID

        if {$nCount==9000} {
            foreach nPID $lsChildPID {
                kill SIGINT $nPID


== subprocess ==
 proc DoSIGKILL {} {
    puts "\[SubProcess\] interrupted. "

 signal trap SIGINT DoSIGKILL

 for {set i 0} {$i<3} {incr i} {
    sleep 1

 puts "\[SubProcess\] normaly exits."

 exit 9

I forks five childs in main script. And, main script sends signal(SIGUSR1-stop,SIGUSR2-continue/SIGINT-interrupt) But, when main script send SIGUSR1 to childs, Childs exits.(I expected "executes DOSIGSTOP"). Why this result occurs?

regards from Nams. Thanks.

mailto:[email protected]

FW: I solve it and append comment here. I use SIGUSR1, SIGUSR2 signals insteads of SIGSTOP, SIGCONTI. They have worked well. I think that there are some signals which is not handled in TCL like SIGSTOP, SIGCONT, SIGKILL.

FW: I didn't really write this either. These initials are taken, buddy.

From Nams.

RBR: SIGSTOP and SIGKILL cannot be handled by Tcl or any application. This is a RTFM case, try "man signal".


I cannot understand callback such as eval,after,uplevel? Hi, I had much help from here to study TCL by a newbie. :) Now I cannot understand callback such as eval,after,uplevel. What means "callback"? And why uses "eval" in practice? Moreover, books for TCL said "There is a variation on command callbacks called a command prefix.", what means "command prefix" and how it is used? Thanks and regards. mailto:[email protected]

This was signed "- FW" but I didn't write this. -FW

RS: To set a callback is roughly to instruct some part of the program to execute a script under certain conditions. eval is most straightforward: "Take this string and run it, now". [after (ms) (script)]: "When (ms) milliseconds have passed, run the following script". uplevel: "Take this script and run it, now, but in a higher level of the callstack - different variables may be visible there". Only after is a real "callback" of the three; others are bind, fileevent etc. But you can write well-functional scripts without these, so don't worry too much ;-)


Thanks a lot. I can understand it.

But, I cannot understand well for some.

uplevel: "Take this script and run it, now, but in a higher level of the callstack - different variables may be visible there".

What means "higher level" and "different variables may be visible there."? You said it under callstack? Then, what is higher and lower relatively?

[RS-more detail from Suchenwirth Richard] Code entered in an interactive Tclsh, or written in a script outside of any procedure, is at top level. For each procedure you call you go one level down (and up again on return). Examples:
 proc a {} {puts "a"; b}
 proc b {} {set x 42; puts "b: x=$x"; c; puts "x=$x"}
 proc c {} {puts "c"; uplevel 1 set x 24}

 % a
 b: x=42

a is level 1 and calls b (level 2), b calls c (level 3). c uses uplevel to change a variable (x) one level up, i.e. in the scope of b. In c, there is no variable x. FW corrected some formatting errors, hope you don't mind.

Don't worry if this is difficult - one can write very good Tcl code without uplevel and the like...

FW: If it helps any: "uplevel" performs a similar task to "upvar", but runs some code as if it were on a higher level rather than retrieving a variable from a higher level and binding it to a lower-level variable. In other words, this code:
  upvar 1 a b
  puts $b

could be accomplished somewhat more elegantly by
  uplevel 1 {puts $a}

Hope this helps.

network interfaces

How can I easily find out all network interfaces on a host (Windows, in particular)?

All interfaces use DHCP; I want to be able to allow the user or program to pick the right interface. (Thanks - Henning Schulzrinne)

DKF - Try [exec ipconfig /all] and looking at the (human-readable) data it returns.

canvas explicit coordinates

Is there any easy way to provide explicit coordinates to move a canvas element to, rather than relative ones like the 'move' subcommand does? I know you can do it by subtracting appropriately to compensate for the offset, but is there any elegant way? -FW

ulis, 2002-11-24. Are you after the coords canvas command? This command permits to replace the current coordinates. From the manual:

pathName coords tagOrId ?coordList?

Query or modify the coordinates that define an item. If no coordinates are specified, this command returns a list whose elements are the coordinates of the item named by tagOrId. If coordinates are specified, then they replace the current coordinates for the named item. If tagOrId refers to multiple items, then the first one in the display list is used.

FW: Yes, this is great - thanks

Differences of 'error' and 'return -code error' ??? and Differences of 'global' and 'upvar'?

I am newbie who begins to study a TCL. Since some long time for JAVA, TCL is strange language for me but I feels that TCL language is good if having some skills. But I confuse for the differences of some Commands for using and deeply meaning and needs to help for advanced senior people. Thanks and regards. mailto:[email protected]

''FW: The stack trace generated by the error' command includes the invocation of the error' command itself, whereas the stack trace generated by the return -code error' construct from within a procedure foo' starts at the invocation of the procedure foo' itself. Next: The global command merely specifies a variable or series of variables to be taken as referring to the global versions of the variables, rather than internal variables within the procedure. The upvar' command is a bit more complicated: it's used to retrieve a variable from the procedure that called the current procedure.

Take this example: You have a variable a' defined within a procedure called qaz.' This procedure calls another procedure baq'. Now, say you want to access a' from the baq' procedure. What do you do? Well, the upvar command allows you to attach it to another variable, let's say b', local to baq', which when set will automatically alter a' and when read will automatically retrieve the value of `a'. It's a bit like a shortcut in Windows - you can use shortcuts to create a reference to a file outside of the current directory.

Anyway, if the evaluation level that called the current procedure wasn't another procedure, merely the global evaluation level, using upvar 1' can be used to attain the same functionality as using global.' Finally, here's the actual syntax - in order to make the a' variable in the procedure that called the current one be referred to by b' within the current procedure, you use this code:''
  upvar 1 a b

...And to merely gain access to the global variable `c', you would use this code:
  global c


15 Nov 2002

I couldn't find any example here for the glitch that I face with.

A part of my source code is below... It is Tk... Somewhat I omitted....

set omp Omp1

set row 0

set col 0

set omp_sys { list Bomp1 Bomp2 Omp1 Omp2 Omp3 Omp4 Omp5 Omp6 Omp7 Omp8 Not_Used }

set omp_nm { list bomp4 bomp3 omp1 omp2 omp3 omp4 omp5 omp6 omp7 omp8 omp9 }

foreach o1 $omp_sys o2 $omp_nm {
        set omp_array($o1) $o2


button_crete $omp $row $col

proc button_create { omp row col } {
        global omp_array
        set row [ expr $row + 1 ]
        button .b_$omp -text $omp -background #4477bb
        grid .b_$omp -row $row -col $col
        bind .b_$omp <ButtonRelease> { exec hanterm -T $omp -e telnet $omp_array($omp) & }


Proceeding until "grid.b_$omp -row $row -col $col" is OK.

But At a point of executing the external command "exec........" occurs an error that

shows below.
       Can't read "omp": no such variable
       while executing
       "bind .b_$omp <ButtonRelease> { exec hanterm -T $omp -e telnet $omp_array($omp) & }"
        (command bound to event)

OS : linux on intel Celeron 7xx Mhz Tcl/Tk Ver : 8.3.x

Anybody give me a help? I'll appreciate it!

Have a nice day, guys~~~

FW says: There are a good number of things wrong with this code, if you fix them all the problem will probably become clear. Firstly, you should use the -command option for the button rather than binding it to a button release. Binding it removes the default binding for button release, which is what makes the button appear to "raise up" when you let go of it. Secondly, you should invoke the "button_create" command after rather than before you define the procedure. Thirdly, you misspell "button_create" as "button_crete" when calling the procedure. Fourthly, you define both global and local variables called "omp," which can be confusing. On a less important note, please use four dashes (-), not four underscores (_) when trying to make a horizontal line on the Wiki. Also, please put at least one space before each line of your source code in the future in order to make it appear formatted for easier reading.

JIS / utf-8

I'm currently writing a script that deals with Shift JIS encoded arguements and I convert them to utf-8 in the script at the beginning. The main problem I have encountered is that tclsh automatically escapes square brackets when setting $argv, which interferes with the Shift JIS encoding, ie: it changes the character. My question is, can I remove those backslashes or is there someway to convert the text to utf-8 while ignoring the backslashes in the variable?

RS: Try, at the beginning of your script,
 set args [string match {\\\[ \[} $args]

to remove backslashes in front of open brackets - hope that helps...

Original submitter: Are you sure that's right? [string match] returns either a 0 or 1... Also, I used a while loop that basically prints [string index $arg $i] where $i is from 0 to [string length $arg]. It's printing two bytes per line, as in one multibyte character and the backslash tclsh put in is coupled with another letter now and treated as one character...

RS: Oops, of course I meant [string map] to remove the backslashes. And [encoding convertfrom shiftjis $input] will reinterprete your input bytes into UTF-8.

configure the flowcontrol of serial interface

It is possible to configure the flowcontrol of serial interface?

default is:
     IOCTL_SERIAL_SET_HANDFLOW Shake:1 Replace:40 XonLimit:2048 XoffLimit:512

needed is:
     IOCTL_SERIAL_SET_HANDFLOW Shake:9 Replace:80 XonLimit:10 XoffLimit:10

DKF: Only in Tcl 8.4, but there you should use the fconfigure command to do the job. See the documentation supplied with Tcl 8.4 for details.


How come when I create a scrollbar in the usual way using Tcl/Tk 8.3 on Solaris 8, the borders of the bar, the trough, and the arrow buttons are all stippled? And how come when I run Tkman, its scrollbar (using apparently the same color scheme) looks great? I've played with every option I can think of, and can't find anything that makes any difference. i.e., this code exhibits the problem.
    scrollbar .xscroll -orient horizontal
    pack .xscroll -fill x -expand 1

A: It was *!$%@$&* OpenOffice which was stealing all of my colors so that there weren't any left for the relief colors. Tkman was OK because it was somehow getting started before OpenOffice. Anyway, never mind.

Question about text widget not having -readonly moved to text


FW: This code is expected to create a 100x100-pixel frame with a 2-pixel border which changes to raised relief when you move your mouse pointer over it, sunken when you click, raised again when you release the mouse button, and flat when you move your mouse away. It works.
 frame .f -bd 2 -height 100 -width 100
 pack .f
 bind .f <Enter> {%W config -relief raised}
 bind .f <ButtonPress-1> {%W config -relief sunken}
 bind .f <ButtonRelease-1> {%W config -relief raised}
 bind .f <Leave> {%W config -relief flat}

But when I add some text into the frame by way of a label, it resorts to very spazzy and strange behavior. It's hard to describe, I'd recommend pasting it into Wish yourself to see. Here's the modified code which is failing.
 frame .f -bd 2 -height 100 -width 100
 label .f.l -text "Test"
 pack .f.l
 pack .f
 bind .f <Enter> {%W config -relief raised}
 bind .f <ButtonPress-1> {%W config -relief sunken}
 bind .f <ButtonRelease-1> {%W config -relief raised}
 bind .f <Leave> {%W config -relief flat}

...Why? This baffles me

A: MSW: It's all packs fault. pack will adjust the size of the containing widget (the frame here). To see its effect, try a
 winfo height .f
 winfo width .f

after the second pack. The problem is that the frame still has the old width/height set, try
 .f cget -width

to see it. I'd recommend you to use place instead of pack, and all will be fine. E.g. use the following:
 frame .f -bd 2
 label .f.l -text "Test"
 place .f -width 100 -height 100
 place .f.l -in .f -anchor c -relx 0.5 -rely 0.5
 <your bindings>

Note that place .f won't adjust the size of the toplevel. An alternative is
 frame .f -bd 2 -width 100 -height 100
 label .f.l -text "Test"
 pack .f
 place .f.l -in .f -anchor c -relx 0.5 -rely 0.5
 <your bindings>

Here pack will adjust the size of the parent (toplevel) window. And as you can use different geometry managers within frames, it's safe to use place to adjust the contents of the frame. place in turn won't adjust the size of the parent (frame).

interface tcl code to 3D graphics package

How can i interface tcl code to another 3D graphics package to provide interaction?

It depends of your circumstances but in the case your package is available as a dll on Windows system or as a .so on Linux you may access its public API using the ffidl extension from http://www.elf.org/ffidl.

Creating a Category

I was trying to create a new Category, Category Foreign Interfaces but it didn't quite work.

I did it by adding a row in the New pages page * [Category Foreign Interfaces]

Obviously this created a normal page, and I can add my links to it for now, but it would be nice to have a proper category for this.

Veronica Loell

Answer?: Category Pages are just normal pages, as any other. The purpose of them is to be link-collectors, i.e. you use other pages in the Wiki and add a reference to the Category Page. When you then click on the Category Page title, a list of all links pointing to that page are displayed, i.e. this is how the Category is created: By adding a link to the page.

So I do not really understand what your problem is ?


watch for file-updates

Q. How about code that watches the file so that if it is updated, the application reflects the changes? Is there a way these values could be accessed by a second Tk app and modified, triggering the save or reuse operations? Basically, I'm looking for a way to make it easier for users to change things like color, size, shape, etc. of an application without having to worry about esoteric windowing information.

A. You might start with autoupdate from Braintwisters:
 proc uptodate {filename {time 0}} {
        set filename [file join [pwd] $filename]
        set mtime [file mtime $filename]
        if {$mtime > $time} {source $filename}
        after 1000 [list uptodate $filename $mtime]
 } ;# -- maybe every second is a bit too often..

See also Tail and the directory notification package in Tcl.


Can you use pipes to achieve simple things without Expect? Pipes vs Expect says you can't, but I don't understand why... Answer: gosh, yes, you can use pipes to achieve even complicated things, without Expect.

delete an HTTP token

How do I delete an HTTP token (using the HTTP package) so I don't have the data from old tokens filling up my RAM? I have to save a large amount of images served off the web, and I only have 512MB of RAM.

...NEVER MIND, I figured it out. It's the "cleanup" command.

Oracle / eMATRIX

I would like to know whether code written in tcl can create locks in Oracle. I am using eMATRIX , a pdm software. Here we use Matrix Query Language to access the ematrix Database The eMatrix deals with the Oracle itself. So when i write some code in TCL/MQL can it create some locks in Oracle.

do let me know

raj kiran

This depends on the abilities of eMatrix, and thus this question should be answered by the documentation for eMatrix.

How to create a array from a existed list

From another TCL program. I got a variable $data with the elements... like following code

  set data {"abc"   www.abc.com
            "yahoo" www.yahoo.com}

''now I need to put the elements of $data into a array named db. how can I implement it? Does anyone has some suggestions?


ulis, 2002-07-14:
  array set db $data

from manual:

array set arrayName list

Sets the values of one or more elements in arrayName. list must have a form like that returned by array get, consisting of an even number of elements. Each odd-numbered element in list is treated as an element name within arrayName, and the following element in list is used as a new value for that array element. If the variable arrayName does not already exist and list is empty, arrayName is created with an empty array value.

grab stderr output from a process

Joe Chott:

I want to know how to grab stderr output from a process I launched with the open pipe command. For instance, the textbook example:
 set fd [ open "|somecommand" r ]
 while { [ gets $fd line ] >= 0 } {
     do_something_with $line

Obviously, the gets is only going to grab stdout from somecommand's output. How do I go about grabbing both stdout and stderr, and hopefully keep them separate?

Found my own answer: stderr

This wiki rocks!

run a C++ procedure

I want to run a C++ procedure in TCL8.0 platform. How can I do that? Is there any examples or tutorals on the website?

Donal Fellows writes: The easiest way involves SWIG.

As an alternative, consider this code:
  // The standard declarations we need
  #include <tcl.h>

  // The functionality being presented to Tcl
  int somefunc(int x, int y, int z) {
     return x*x*x+y*y*y+z*z*y-z*y*z; // <-- Your functionality goes here!

  // The wrapper functions
  static int somefunc_cmd(ClientData clientData, Tcl_Interp *interp,
                          int objc, Tcl_Obj *CONST objv[]) {
     // Note that we're ignoring the clientData argument here
     int v1,v2,v3,result;

     // Now we make sure we have the right number of arguments
     if (objc != 4) { // cmdname + three args
        // Use a library function to generate the error message
        Tcl_WrongNumArgs(interp, 1, objv, "x y z");
        return TCL_ERROR; // Indicate that something went wrong

     // Parse the integers out of the arguments
     if (Tcl_GetIntFromObj(interp, objv[1], &v1) != TCL_OK ||
         Tcl_GetIntFromObj(interp, objv[2], &v2) != TCL_OK ||
         Tcl_GetIntFromObj(interp, objv[3], &v3) != TCL_OK) {
        // One of the args was not an integer, already have error msg
        return TCL_ERROR;

     // Call our wrapped function
     result = somefunc(v1, v2, v3);

     // Pass the result back to Tcl
     Tcl_SetObjResult(interp, Tcl_NewIntObj(result));
     return TCL_OK;

  // A function to install the code in Tcl
  extern "C" int Somefunc_Init(Tcl_Interp *interp) {
     // Register the command; note that the NULLs are for features we don't use
     Tcl_CreateObjCommand(interp, "somefunc", somefunc_Cmd, NULL, NULL);
     return TCL_OK;

search links and titles in a html file

I use the following codes to search all the links and titles in a html file, but it did not work. Does anyone have some suggestions or better way?
    set data {<td valign="top"><a href="antennas/index.html"><img src="images/but_antennas.gif" alt="Antennas and
              Propagation" HEIGHT="30"></a><br></td>
              <td valign="top"><a href="cellular/index.html"><img src="images/but_cellular.gif" alt="Cellular
              Systems" HEIGHT="30"></a><font face="Arial, Helvetica"><br> </font></td>}

    foreach {_ url content} [regexp -all -inline {<a href="([^"]+?)" *>(.*)</a>} $data] {puts "$url -> $content"}

mailto:[email protected]

GPS writes:
 while 1 {
                if {![regexp {<a href="([^\"]+?)" *>(.*?)</a>} $data all href linkData]} {
                set data [string range $data [string length $all] end]
                puts "href $href"
                puts "linkData $linkData"

Donal Fellows writes: In general, HTML is awful to parse with regular expressions; in the most general case, you'll need an SGML DOM parser/tree-builder to make head or tail of it, and there is an awful lot of really badly written HTML out there too. :^(

Making Windows Active?

Nice simple question: how do I bring a window to the front (make it active, I suppose) without making it always on top (which is what a global grab does) and without it only working on one platform (which is what wm deiconify does).

Rohan Pall Try this:
  focus -force .

Dynamically editable browser widgets

Is there any browser widget, embeddable within Tcl/Tk, that allows for adding text "on-the-fly", so to speak. I'm writing a chat client type thing, which requires HTML-based markup capabilities, and I tried using scrolledhtml (or something - I forget exactly, but it's one of the pure Tcl, text widget-based ones) to render one line at a time and then copying over all the tags from the browser widget, which technically worked, but it was blindingly slow. So I repeat: is there any Tk browser widget that allows you to add text on to the end at any moment, rather than rendering an entire page at a time and then stopping? -FW

BTW: it should work with Tcl versions going back to 7.6, I believe. (FW: Not quite, with ActiveTcl Beta-2 wish I had to mod some things to use the "tk" namespace - for example, had to change TkTextSetCursor to tk::TextSetCursor. So it's backwards compatible, but it doesn't quite work now. Thanks though, that helps a lot.)


Can anybody please explain how to translate into TCL the following bash code fragment:
  exec <&4         # dup file descriptor 4 into stdin
  exec 4<&-        # close file descriptor 4

for non shell-script programmers follows the same code in C language:

DL: I doubt that you can do it so trivially. But it's certainly easy enough to generate your own version of gets and read that behaves as if you did. Would that be acceptable?

Question about text widget bindings moved to text.

save / load data

Does anyone have sample code which illustrates how a Tk program can save and reuse at start up time information such as window size, position, etc. into a resource file?

  • MPJ:Here is a procedure to save the window size...
 proc save_window_size {filename} {
    set filename [file join $save_dir $filename]
    if {[catch {open $filename w} dest]} {
        return 0
    puts $dest "wm geometry . [wm geometry .]"

  • And a example of the use of save_window_size
 wm withdraw .
 catch {source myfile.rc}  ;# catch if file does not exist
 # load rest of the application
 wm deiconify .
 wm protocol . WM_DELETE_WINDOW {save_window_size myfile.rc}

Tcl Initialization

Can someone describe exactly what goes on during Tcl initialisation? I've been tracing the code for 2 hours now and can't make heads or tails of it. My specific problem: on Unix, the first thing tclsh does is to crawl over half the filesystem looking for iso8859-1.enc, and I'd like to make it stop doing that.

  • Arjen Markus As part of a TIP (number 66, I think) I wrote a sizeable memo on the subject. It is not finished yet (of course), but I should simply publish what I have now. Early 2002, I will do this!

Constraining windows

How do I constrain a toplevel within a frame, so that it'll snap back to the nearest edge of the frame if it's moved outside of range? I know I'd have to allow the user to move the toplevel past the edge of the frame, but snap it back to the nearest edge of the frame afterward, if needed, but how, exactly?

  • I'm (bbh) not sure what exactly is being asked. If you want to keep the user from changing the size of your toplevel use [wm resizable...]

to keep them from changing it in the first place (you can set either horizontal or vertical or both as being forbidden). If you want to allow resize but only within certain parameters you can use [wm minsize ...] and [wm maxsize...] to constrain the user. If you want some other behavior you can always bind to the <Configure> event to detect changes in window size and then use [wm geometry ...] command to adjust the size to your liking (taking care not to get yourself into an infinite loop of re-acting to your own changes). See the wm page for details of all the commands I mentioned. And if you have something else in mind then please give some more details or scenario that you are trying to achieve.

Tcl Regsub

I need to make a regsub on a list of strings for certain pattern. But the trick is that it should not match the pattern if it occurs within an <a href>...</a> tags.

  • I don't think you can do that with a single regsub, and even if you could (using some combination of looakead constraints or something) it would be very unreadable imho. I think the best solution if to use regexp -all -indices to get ranges of all the <a href>...<\a> stuff and then go thru the string range by range - copy the href ranges unchanges and perform your regsub on the in between ranges. bbh

How do I make icon bitmaps on windows?

I'm creating a telnet client, and open sessions with new text will have a different image as their bitmap in the taskbar. Is this even possible? It says since 8.3 this is supported, however using ActiveTcl 8.3.3 and this as a test:
 wm iconbitmap . hourglass

It returns "" but does nothing. -FW

 wm iconbitmap . "myicon.ico"
 wm iconbitmap . -default "myicon.ico"

What Tk needs is for someone to contribute code to convert an Tk image or bitmap type into the Windows-specific .ico format internally, and then it would be easy to make 'wm iconbitmap . hourglass' work.

How do I make the grid of a window expand with the window?

Eg, I have a form-style gridded dialog and I want people to be able to resize it without having all the data be bunched up in one place.

  • use rowconfigure & columnconfigure to set the -weight option to non-zero for any/all rows you want to expand into any extra space

  grid rowconfigure $parent 1 -weight 1
  grid columnconfigure $parent 1 -weight 1
  grid columnconfigure $parent 2 -weight 2

In this case row one will get all extra vertical space and columns one and 2 will share extra horizontal space (with row 2 getting twice as much as row 1) see grid for more details

TclX]'s keyed list operations

Where are the good places to look for explanation and examples for TclX's keyed list operations (e.g keylset, keyldel etc)?

  • LV: I've seen very little written concerning these operations. Look for links off the TclX web page for future writing.
  • Arjen Markus The only place I know is Tcl/Tk tools by Marty Backe and others.

Windows extensions

What are the most requested, but not yet available, Windows extensions?

  • LV I don't use Windows much, so I don't know about requested but not available - perhaps an up to date port of Expect?

tcllet for the TCL plugin for Netscape

I am writing a tcllet for the TCL plugin for Netscape. Is anyone still developing/supporting/knowledgable about this product? Esp. on the Mac? Thanks'''

  • See Tcl/Tk Tclet Plugin for a bit of information about the software. The primary thing of which one needs to be aware is that such software needs active advocate programmers for work to proceed farther.


I have a computational program that takes a few minutes to run. I can tell that the program is "working" because the button that invokes it remains depressed. That is apparently too subtle for my users. Is there a way to bind (or perhaps some other way) the "button is invoked" to some display (like an hourglass)?

  • The BLT extension has a command for indicating busy - perhaps others can point to other useful ways of indicating this? Answer: [7] begins to answer this.

Where can I find the source code for tcl/tk/etc.?

  • The master CVS repository for Tcl is currently at http://tcl.sourceforge.net/ . The distributions for many releases of Tcl - from the past as well as the current release and the releases beyond can be found there.

Where can I find online tutorials for learning tcl/tk/etc.

Where can I find mailing lists or newsgroups that discuss tcl?

enumerated types

Is there a mechanism whereby I can create "constants" or even better, enumerated types within Tcl?

call libraries of functions written in other language from Tcl

Is there a simple way to call existing libraries of functions written in some other language from Tcl?

  • Swig is one way - requiring some preprocessing of the library in advance.
  • Ffidl is another way, requiring no advance processing of the library but requiring that the library's API be described in Tcl.
  • TclBlend is a way to do this if the existing library is Java code.
  • I Arjen Markus have a small library for mixing Fortran and Tcl. Just ask... (not fit for wide spread use yet, but useful enough).

serial port

How do I communicate with the serial port from tcl/tk? Is there some tcl extension or library that I can download for this purpose? I don't need high speed - 9600 bps is okay. I just want to do some instrument control.

create buttons on the fly

My application creates buttons on the fly, depending on certain parameters and the buttons text and the id are also built on the fly. My question, I might intend to do something depending on which button is invoked.

How to know that which button has been pressed and how to do it using the -command option of the button???

  • Try this:
 proc handle_button_commands {w label} {
    # w holds the widget name of the pressed button
    # label holds the text displayed by the button.
    # Do any sort of dispatching you feel like...

 pack [button $frame.$buttonname -text "$buttontext" -command [list handle_button_commands %W $buttontext]]

What are the most commonly used Tcl/Tk extensions for Windows development?

How can I execute C code in the background

i.e. when the event loop would normally block waiting for events? The 8.3.2 documention specifically warns agains a doWhenIdle callback rescheduling itself. The suggested way is to schdule a timer event with a zero timeout, when I do that my GUI stops responding. Using a timeout of 1 ms, my GUI works fine , but I lose a lot of background processing time. --HBP 24/Apr/01

  • After posting this I managed to figure it out! In the idle callback procedure, issue an "AFTER 0 {doWhenIdle callback}" i.e set a timer callback with zero time which THEN reschedules the idle callback procedure. The documentation does say that if you interpret it correctly.

What values count as 'true' and 'false' in Tcl?

The man page for "if" lists "true" and "yes" and any non-zero number as examples of true values, and "false" and "no" and zero as example of false values. However, it says a string value such as true or yes for true, which implies that there may be other values which are true.

So, what is the range of true values in Tcl? And what is the range of false values in Tcl?

  • '''LV: From looking at the source code (always a good route to take for questions such as these...) I see the following list:
 0, 0.0, no, off, false

 1, any other int or double, yes, on, true

as the list .'''

  • Don't count on that too much. I have Tcl/Tk 8.4a1 for Win95 and only 0 and 1 seem to count as boolean values -- or am I missing something?
  • LV perhaps different commands have different meanings - that would be nasty.
  • Glenn Jackman: the Tcl_GetBoolean[8] man page reveals all.

custom "source" command

I have a program that is primarily command-driven with a Tcl interface, however there is a GUI aspect to it as well. Users may execute scripts using a custom "source" command. This modified source command is implemented in C, and uses Tcl_CreateTrace to echo the commands as they are executed. Unfortunately, if the mouse drifts over the GUI while a script is being executed, lots of Tk garbage is printed. Is there any way to differentiate events coming from Tk so they can be excluded? (Micah Johnson -- [email protected])

  • comp.lang.tcl is generally where I'd recommend posting this sort of inquiry. I understand you don't know of easy Usenet access; perhaps you'll want to read about no-cost access methods toward the bottom of "comp.lang.tcl".
  • In any case, my first reaction to this description is that you can hack a quick and reasonably reliable solution simply by filtering out the X-ish events you don't want to see. They're all in just a few classes, and I speculate just a few lines of pattern-matching will be enough to eliminate all of them from users' view. I don't understand where in interpretation you're catching them now, so I can't easily describe the details. What are you printing out, and what values does it appear to assume?

display a tk_dialog

Aug 1, 2001 Sheesh. I'm a TCL beginner and I just want to write a program to display a tk_dialog. Here's what I have so far:
 # test1.tcl
 # make a tk_dialog button

 toplevel .mainwin
 wm title .mainwin "Test title"
 tk_dialog .mainwin -title "Test title" -text "This is testing." -string  "One" "Two" "Three"

But when I double click it to run it in wish83 I get an error:
 bitmap "-text" not defined
  (processing "-bitmap" option)
  invoked from within

(and some more errors...)

Where did this -bitmap come from? I didn't even specify it.


  • Someone else writes: Check the docs for tk_dialog:

tk_dialog window title text bitmap default string ?string ...?

tk_dialog doesn't take the switch-style arguments.

You would probably be happier with tk_messageBox.

  • LV writes: and you did specify a value for -bitmap - the 4th argument to tk_dialog is the name of a bitmap, if provided. So you told, by accident, tk_dialog that a bitmap called "-text" should be displayed.

Tk interface to a C-based OpenGL program

Does anyone know about rigging a Tk interface/GUI to a C-based OpenGL program? I have not found much on interfacing Tk with C and/or OpenGL. I have a scientific graphical simulator which requires a better GUI than GLUT/MUI (OpenGL). Cheers!

What factors to be considered to create Persistent Tcl and Tk Applications

Wiki - change page names/titles

So I've downloaded the wikit and have a copy of The Tcler's Wiki to use as a base. There's talk about changing page names/titles, but I don't see how. And is there a way to expand a list of ALL of the pages, and to remove some of them?

  • LV writes: See Wikit Command Line for some information about dealing with a wikit, as well as a tool specifically designed to interact with the tcler's wiki, which is an older version of the wikit. Additional questions can be dropped there, or sent to the metakit mailing list which also seems to cover wikit issues.

how to make automated script

My purpose: just send Login and Password to a TELNET IPADDRess i can execute by "command(exec telnet.exe)". It will pop up a Login and password query.

My idea is to automate this. Means i have to write a code which will automatically supply login=XXX and Password="xxx" ,without goin to the telnet and typing it!!!

Please send ur suggestions to: [email protected] [email protected]

  • CL responds: Someone please have this person look at Expect.

things Tcl can portably do

A correspondent asked for a reference on "a checklist for things Tcl can portably do instead of 'exec ls', etc". Presumably one of us will launch a page some day on the topic.

What are some options for managing variations of Tcl on your machine?

What is the advantage of Tcl over Perl?

How to run C procedures in background

i just begin in tcl programmation and i wanted to know how to run C procedures in background in a tcl/tk script(just like a tcl command for example) ? thanks CL answers: if at all possible, ask this in comp.lang.tcl. While your question is a reasonable one, there happens to be so much ambiguity in at a technical level that it's likely to take at least a couple rounds of dialogue before we can answer you satisfyingly. In the meantime, though, read about "exec".

"channel busy" error

I am working on a client/server Tcl and Tk program. The process needs to copy a file from the client to the Server(Unix). I am using a fcopy but I get a "channel busy" error. I am not sure how to turn off the fileevent and then turn it back again as mentioned in the fcopy documentation. Does anyone have any examples ?

See fileevent. Also see, "How to send a file through a socket connection".

Searching on wiki

A correspondent asks, "I'm missing something. I seem to spend an awful lot of time on the Wiki for very little return.

I have a hell of a time finding what I'm looking for at the Wiki. I've used the search feature-- it seems to search page titles. I've now realized that by appending an asterisk onto my url level search that I can search page text; but that's still not the 'full search' I suspect is available.

Where am I going wrong? How do you find what you're looking for on the Wiki? Is there some sort of organizational super structure I'm overlooking?

I've read and reread the welcome to the Wiki page and I'm not seeing the information I'm looking for there."

I'm sympathetic. Searching is not as easy as one might imagine. I usually find what I want, but that's because I've already memorized much of what's there (umm, here). So how should we advise Wiki readers at this level?

Hm, searching seems get worse as content grows... took me 3 attempts to find Searching and bookmarking URLs on the Tcl'ers Wiki - with "search" and "Search" both failing to find it. Looks like the search logic is going to have to be revisited... -jcw

Does it help to use google[9] with a "site:mini.net" term, or the equivalent on your favorite search engine? - SCT

capture Unix environment variables

I want to capture Unix environment variables but can't seem to get the $ to pass correctly.
 set authstate [ echo \$AUTHSTATE ] ; does not work

Any suggestions? Thanks. Bob. '''RS: The environment variables, in Unix and Windows, are brought into Tcl in the global env array, so you could more smoothly write
 set authstate $::env(AUTHSTATE)

and also change the environment via env (but effective of course only for child processes started later from your Tcl script..)

Moreover, you could have found much of this information on your own by trying such searches as http://wiki.tcl.tk/env or http://wiki.tcl.tk/environ '''

simulate a cell phone interface

For building a MMS-Viewer I have to simulate a cell phone interface. The problem is, how can I get buttons into tcl/tk that are shaped like cell phone buttons (you know oval sloping buttons and stuff) ?

Answer: "Fancy Tk Buttons"

procedure as an index in a Tcl array

I have the following tcl code:
     set shat($key) $s

now "s" is an integer, "shat" is an array. It appears that "$key" is a C function that I cannot trace. So when you run the above line the value of the array at position "$key" is not $s but some computed value based on "$s"!

The question is, can you have a procedure as an index in a Tcl array, and if so how does it work? If not may you recommend anything about what could be happening?

Thank you in advance Yanni

RS: "$key" is dereference (the value) of the variable "key". If you have no such variable, it will raise an error. If you want to call an embedded command, put it in brackets:
 set shat([myCommand $s]) $s

This will first call myCommand with the value of variable s as argument; then insert the result of that call in the place where the brackets are now; and finally call the set command with these two arguments.

E.g., if
 proc myCommand n {expr $n*$n} ;# compute the square
 set s 4
 myCommand $s == myCommand 4 => 16
 set shat([myCommand $s]) == set shat(16) 4

Indexing arrays is always done with strings (which might of course be the name of a command).

[Insert] key does not work

I'm here because a program I use (LEO) uses Python & tcl/tk. The difficulty I have is that the [Insert] key does not work - I expect it to toggle between Insert and Overwrite mode. (I'm using Windows 98, and Python 2.2.? and tcl/tk 8.3 ) Is there any way to get the overwrite going? I usually use it for something like:

I can cut-n-paste "xyz(1);" repeatedly, and then change the 1's to 2, 3,... To have to remember type-and-delete is a pain, especially since overwriting has been around since the early PCs.

Thanks, --Rich

leak memory

What stupid thing am I doing that makes this leak memory? davidw
    while (1) {
        Tcl_UnsetVar( interp, "RivetUserConf", TCL_GLOBAL_ONLY);

        arrayName = Tcl_NewStringObj( "RivetUserConf", -1 );

        obj = Tcl_ObjSetVar2(interp,
                       Tcl_NewStringObj("foo", -1),
                       Tcl_NewStringObj("bar", -1),
        Tcl_Eval(interp, "puts [info exists RivetUserConf] ; catch { puts [array get RivetUserConf] } ; catch {unset RivetUserConf} ");

MS: you are leaking the object "foo" - array references are stored as strings, so that nobody keeps a reference to "foo", and hence its refCount never will be decreased. "bar" is not leaked, as it gets to be the value of the variable and its lifetime is managed by the variable itself. IOW, you should do
        arrayName = Tcl_NewStringObj( "RivetUserConf", -1 );
        elemName = Tcl_NewStringObj( "foo", -1);

        obj = Tcl_ObjSetVar2(interp,
                       Tcl_NewStringObj("foo", -1),
                       Tcl_NewStringObj("bar", -1),

For this particular snippet (ie, where all Tcl_Objs are created for this one particular call), I'd recommend using Tcl_SetVar2 instead of Tcl_ObjSetVar2 - it will do precisely the same thing.
        obj = Tcl_SetVar2(interp,

OTOH, if this is a big loop and you manage to use the same objects at each iteration (doing Tcl_DecrRefCount outside the loop), performance may be slightly better if you do the lifetime management yourself.

debugging version of foreach

kpv : For debugging, I often copy and paste into a console window to see what's happening step by step. This works well, especially for commands like set which echos the value to the console, but not so well for foreach when used like foreach {var1 var2 var3} $mylist break. What I'd like is a debugging version of foreach, perhaps called xforeach, which would echo the values of the variables (var1, var2, var3 above).

FW: I'm disinclined to use foreach for that sort of thing. I use a procedure I call "scatterset", which takes the same args as the traditional "foreach" method except without the "break" at the end, as in scatterset {a b c} {1 2 3}. I've added a debug line for you. Can you use this to solve your problem?
 proc scatterset {varnames vals} {
   set i 0
   foreach varname $varnames {
     set val [lindex $vals $i]
     puts "$varname = $val" ;# Comment this line out for normal behavior
     upvar $varname curvar
     set curvar $val
     incr i

scale the windows, etc for different screen resolutions

I'm currently developing a gui w/ tk and was wondering if there was a way to scale the windows,etc for different screen resolutions. If not, would i have to scale everything manually, ie-windows, canvas', text, etc. Thanks.

ulis: You can try to play with 'tk scaling'.

Try successively:
  tk scaling 0.66
  tk scaling 0.75
  tk scaling 1.00
  tk scaling 1.25
  tk scaling 1.33

And watch...


I am a new user working with cgi-tcl. Using this for setting up cookie and getting back. but having problem while retriving back.

First of all, I a form on a windows NT server. This form is used for authentication purpose. if the user is authenticated, than only the scripts on another server which windows 98 is executed. this is done using cookies. When the user is authenticated, cookies are set. And the scripts on another machine is executed using these cookie values. The program work fine when cookies are transfered from Windows NT to windows NT machine. But the problem comes when they are transfered from Windows NT to Windows 98 machine. I am using cgi_import_cookie

also what i found was that, it does give an error for cgi import, but when i print this cookie value. in p statement.

I am doing something wrong.

tcl on a handheld

Is any one running tcl on a handheld with win ce or linux if so what unit and what os thanks DS

schlenk Look at the pda pages to find out.

network connection to a POP server

Write a short Tcl/Tk or C program that opens a network connection to a POP server, authenticates, and makes at least one request and receives the response.

Rama Krishna Kattamuri

See tcllib, the pop3 module. The refered page contains examples.

MacOS X problems : testtcl crashes wish under macOS X 10.2.1


I'm not an expert, so I have done the following, can anybody check/answer to see what is wrong ?

1) I downloaded TCL/TK 8.4.1. 2) Unzip created 2 directories ~/tcl and ~/tk (renamed from original tcl841 and tk841 3) cd ~ 4) run succesfully "make -C tcl/macosx deploy", "make -C tk/macosx deploy" 5) typed "sudo make -C tcl/macosx install-deploy", "sudo make -C tk/macosx install-deploy"

now my question:

a) I found in System/Library there is already a tcl folder with subdirectories containg the string tcl. do i have to remove this or what ? Why are there ? I thought that standard Jaguar did NOT have tcl installed, so what is these stuff ?

b) How do i install man pages for tcl ? This is not documented (and if it is in man page I cnnot read it)

c) To check installation I want to run test. The documentation is not very clear and the info in tcl/test/README is not clear/consistent (e.g. it says to run make ../unix (!?), it also says to source all.tcl (but i think it means running wish and use that to source it and so on). Anyway, if I start wish, then from the menu I choose source and then select all.tcl I get a crash as described in log below.

Can anybody help ?

Regards Michele Zundo

===CRASH Log attached ===

Tests running in interp: /Applications/Utilities/Wish Shell.app/Contents/MacOS/Wish Shell Tests located in: /Users/mzundo/Development/tk/tests Tests running in: /Users/mzundo/Development/tcl/tests Temporary files stored in /Users/mzundo/Development/tcl/tests Test files sourced into current interpreter Running tests that match: * Skipping test files that match: l.*.test Only running test files that match: *.test Tests began at Wed Nov 06 12:04:36 CET 2002 bell.test Bell should ring now ... bgerror.test bind.test

==== bind-15.7 MatchPatterns procedure, ignoring type mismatches FAILED ==== Contents of test case:
    bind .b.f <Double-1> {set x 1}
    set x 0
    event gen .b.f <Button-1>
    event gen .b.f <Key-Shift_L>
    event gen .b.f <ButtonRelease-1>
    event gen .b.f <Button-1>
    event gen .b.f <ButtonRelease-1>
    set x

---- Result was: 0 ---- Result should have been (exact matching): 1 ==== bind-15.7 FAILED

==== bind-22.10 HandleEventGenerate FAILED ==== Contents of test case:
    bind .b.f <Key> {set x "%s %K"}
    set x {}
    event gen .b.f <Control-Key-1>
    set x

---- Result was: 4 a ---- Result should have been (exact matching): 4 1 ==== bind-22.10 FAILED

bitmap.test border.test button.test canvImg.test canvPs.test /usr/bin/wish: line 2: 737 Segmentation fault "/Applications/Utilities/Wish Shell.app/Contents/MacOS/Wish Shell" "$@"

tag with -bgstipple option

JES: I'm trying to use the -bgstipple option for a tag. It works fine with predefined bitmaps, but doesn't seem to work with ones I've created with "image create"... image create returns 'image1,' for example, and I use this after -bgstipple and then: Error in startup script: bitmap "image1" not defined

suggestions? Thanks in advance

New Question 12/14/02

I have defined variables for the current date and the name of the current day. I want to create an expression that allows me to set the Subject of an Outlook 2000 message to read "Report for $day, $date" where the variables are resolved in the final message. I cannot seem to find anything that works. I am trying variations of the following:

set subject {Report for &day;, &date;}

What I get as the message subject is "Report for day, date" as the variables do not resolve.

Can anyone offer some suggestions?


Lars H: The answer is actually present in your question. As long as it is Tcl you want to resolve the variables, you should do
 set subject "Report for $day, $date"

Also: Be sure to read the Tcl man page (e.g. [10]).

New Question 12/22/2002

I want to print the following on channel stdout "4P7" I am doing

% set x 4 4 % set y 7 7 % set a "$xP$y" can't read "xP": no such variable %

Can anybody tell me y its giving that error?Treaorytically it should write 4P7 to stdout. Thanks for any help. Kedlaya([email protected])

MT: It doesn't know where the variable name ends. There are several work-arounds including:
 set x 4
 set y 7
 puts "$x\P$y"
 set p "P"
 puts "$x$p$y"
 puts [join "$x P $y" ""]
 puts [format "%i%s%i" $x "P" $y]

MrReach: this should get you what you want -
 puts "${x}P$y"

Reply 27 Dec 2002

PSEUDOCODE - and a DRY RUN might help ?
 set x 4
 set y 7
 puts "$x\P$y"
 set p "P"
 puts "$x$p$y"
 puts [join "$x P $y" ""]
 puts [format "%i%s%i" $x "P" $y]

(MSW) (Question) (some rant about tcl_{,non}wordchars)

(Answer) (File a TIP)

(MSW) Done :)

Sharp zaurus

2004/10/08 - Felipe Voloch

I am using Tcl/Tk (tclkit actually) on a Sharp zaurus C 860 with its original ROM and the XQt environment. It works fine except that buttons and labels default to huge sizes. This can be fixed by adding -padx 0 -pady 0 (or some other small number) in the definition of the widget. But it can be a pain editing a big file to change all such occurrences. Any suggestion to a workaround?

Iwidgets combox

2004/10/02 - Satya I noticed something strange in the combox provided by Iwidgets. I am using Iwidgets version 4.0.1. I tried the following piece of code %iwidgets::combobox .c -editable true .c % eval .c insert list end {a b c} % pack .c

If I click on the pop-up cursor, it pops up the list box. Let's say I decide not to select anything from the selection list. So I left click my mouse on the entry field, the list box goes away. But the problem is that I don't see the cursor in the entry field. The entry field becomes uneditable. I tried several things, and found out that I can get back the cursor in the entry field only when I select something in the list box or when I press the escape key when the list box is open. Did anyone else notice this problem in combobox? Any combobox option I am missing here?

Thanks Satya

translate some text using babelfish

2004/10/02 - HZe

I tried to translate some text using babelfish from Altavista. This is the code I use:
    package require http

    proc translate {text from to} {
        # ::http::config -proxyhost proxy -proxyport 80
        set url "http://babelfish.altavista.com/tr"
        set query [::http::formatQuery doit done intl 1 tt urltext trtext $text lp ${from}_${to}]
        set token [::http::geturl $url -query $query]
        regexp {<td bgcolor=white class=s><div style=padding:10px;>([^<]*)</div></td>} \
            [::http::data $token] dummy translation

        if {1} {
            set name out.html
            set fp [open $name w]
            puts $fp [::http::data $token]
            close $fp
            global tcl_platform
            if {$tcl_platform(platform) == "windows"} {
                exec cmd /c start $name &
            } else {
                exec mozilla file://[pwd]/$name &
        return $translation

    puts [translate "foot" en zh]

It works fine for european languages, but translating en (english) to zh (chinese - simple) gives no correct results. I assume it is something with the encoding of the page, which is UTF-8, I think. On Windows for debugging, a browser is started and shows the wrong translation in the complete page. Just pressing Translate in the Browser again shows the correct results.

What has to be changed to make it work for chinese, too?

run wikit on OpenBSD

2004/09/30 - LES

I want to run wikit in my Web site, which is hosted in a server that runs OpenBSD 3.3 i386. The only build of Tclkit for OpenBSD I found is here: [11]. But this one doesn't work. I need a static build. I can't build one myself because I don't have OpenBSD or even the required expertise to build Tclkit on my own. Can anyone donate a static build of Tclkit for OpenBSD? The fine gentlemen of Equi4 [12], perhaps?



I'm looking for a "usb-cam-mksnapshot" tcl-package for Linux. vfwtcl-package works fine, but it's only win32-stuff.


query Active Directory

2004/09/24 BMA

Platform: Windows 2000/XP

Is there a way in ActiveState Tcl to query Active Directory? I'd like to find out which computers are running Windows 98 and which computers are running Win2k pre service pack 4.

MG Oct 3rd 2004 - I've never used Win2k, but can you not check the version with the tcl_platform array? On Win98, I believe $tcl_platform(osVersion) is "4.10". I don't know what it would be on Win2k -- possibly you tried this and it also reports 4.10, hence your problem -- but $tcl_platform(os) should be "Windows NT" on Win2k, and "Windows 95" on Win98. Does that help at all?



hi, is there a possibility in tcl to define a filepointer (pointer which points to a special position in a file) while opening a file? I have to read frequently a syslogfile and want to prevent reading the whole file every time. PB - RS: seek positions a file at a given integer byte position. Use tell to record that position at first time, and then seek there for repeated reading.

2004/09/20 - Breadcrust

Lately I have been experimenting with my own Mac OS X style menubar at the top of the screen. The menubar is basicly just a canvas inside a toplevel. I am using "wm overrideredirect .menubar true" so that the window manager forgets its there. I have some questions on how i should do some certain things.

1. How can I keep the menubar above all windows (except for stuff like popup menus)?

2. How can I stop windows from being under the menubar?

3. What would be the best way to 'intercept' calls to toplevel about the window's menubar so that my menubar can handle it? I have trying doing something like this before by renaming the widget's procedure to something else and creating a new procedure for the widget that passes all details to the real (renamed) widget proc except the ones I want to take care of my self, but this can get a little ugly and it would be good if there was a better way of doing it I knew of.

4. How can I stop a desktop environment/window manager from taking care of iconic windows? (Is this more of a question I should be asking on wm forum or wiki?)

5. How can I take care iconic windows though my program?

I am also looking for ways to take charge of the menubars on gtk/gnome and qt/kde apps, but that is a question I think will ask on a on wikis or forums for those librarys. If you happen to know anything about this, dont hestitate to email me tho.

no internal frame on text widget

In Tk 8.4/8.5 the following script:
    set w .twind
    catch {destroy $w}
    toplevel $w

    frame $w.f -bg blue
    set t $w.f.text
    text $t -width 70 -bg green -height 35
    $t insert end "test"
    pack $t -expand  yes -fill both

    panedwindow $w.pane -bg red
    pack $w.pane -expand yes -fill both
    $w.pane add $w.f
    # Why is the paned window red?  What
    # happened to the text widget or the frame?

gives me just a big red widget, with no evidence of the internal frame or text widget. Why doesn't the frame/text show up?

I know I could make $w.f a child of $w.pane, but if I add the following line:
    $w.pane add [text $w.text -bg green]

Then this second text widget does show up! (And this one isn't a child of $w.pane either)

The answer is that raise $w.f is needed in the above. Thanks to comp.lang.tcl.


I have an application where at the end of a lengthy procedure (minutes) a tk_messageBox pops up for user confirmation to continue. I would like to put a timeout on this, in that if the user fails to press on one of the buttons within a specified time, I could either - simulate the appropriate button press, or - just destroy the messageBox and continue on.

Thanks for any help.

MG 30 Aug 2004 - at least using the Windows native tk_messageBox, I don't think that's possible. If you used tk_dialog instead, though, you could do something like this (where $w.button0 is the first button, $w.button1 the second, etc)...
 set w .dialog
 set afterId [after $timeout {catch {$w.button0 invoke}}]
 set ans [tk_dialog $w "Proceed?" "Do you want to proceed?" questhead 0 "Yes" "No"]
 after cancel $afterId
 if { $ans == "1" } {
      # They clicked No
    } else {
      # carry on

gDW Thanks MG, the above works like a charm.


2004/08/23 - PB

1) What is the sense of using Interp-Concept w/o thinking on checking untrusted sources?

RS: As Tcl is (at least partly) an interpreted language, you need one interpreter to start with. For untrusted source, safe child interpreters were explicitly developed.

2) Could it be that the creating of a slave interpreter can be understand as creating a new thread inbound a invoking (and single) process?

RS: The other way round: if you use multi-threaded Tcl, each thread gets an interp of its own. But even in standard single-threaded Tcl, you can use interps to partition responsibilities into "padded cells".

3) Exists a Tcl-Concept to create new processes (such as fork() and NOT exec $progr &) and to realize interprocess-communication (such as pipe())?

RS: TclX has fork, I suppose (void where illegal), and one way of inter-process comms is to open a bidirectional pipe with [open "|cmd arg arg..." r+]. Other possibilities are writing/reading "semaphore" files, etc.


MG Aug 17, 2004

I wanted to know if it is possible to scroll down or sideways a window with the widgets. It seems to be unlikely that a GUI would not have that sort of capability. Is there an additional package that has to be included? can that be somehow avoided?

RS: BWidget has a ScrollableFrame, see [13]. But pasting so long code here isn't considered good style - the best way is: short question, short answer :)

For example, if I have the following code (taken from this website and added on to... )
 proc scroll_combine {frame widget} {
   set border_width [$widget cget -borderwidth]
   $widget config -borderwidth 0
   $frame config -borderwidth $border_width -relief [$widget cget -relief]
 } ;# FW

 # scroll --

 # Description
 #   Create a scrollable-widget frame

 # Arguments
 #   type : type of  scrollable widget (e.g. listbox)
 #   W    : name for scrollable widget
 #   args : arguments to be passed to creation of scrollable widget

 # Return
 #   name of scrollable widget

 proc scroll {type W args} {

 # ----------------------------------------------------------------------

   set w $W.$type
   set x $W.x
   set y $W.y

 # ----------------------------------------------------------------------

   array set arg [list \
     -borderwidth 0 \
     -highlightthickness 0 \
     -relief flat \
     -xscrollcommand [list $x set] \
     -yscrollcommand [list $y set] \
   array set arg $args

 # ----------------------------------------------------------------------

   frame $W \
     -borderwidth 1 \
     -class Scroll \
     -highlightthickness 1 \
     -relief sunken \
     -takefocus 0

   # create the scrollable widget
   uplevel [linsert [array get arg] 0 $type $w]

   scrollbar $x \
     -borderwidth 0 \
     -elementborderwidth 1 \
     -orient horizontal \
     -takefocus 0 \
     -highlightthickness 0 \
     -command [list $w xview]

   scrollbar $y \
     -borderwidth 0 \
     -elementborderwidth 1 \
     -orient vertical \
     -takefocus 0 \
     -highlightthickness 0 \
     -command [list $w yview]

   grid columnconfigure $W 1 -weight 1
   grid    rowconfigure $W 1 -weight 1

   grid $w -column 1 -row 1 -sticky nsew
   grid $x -column 1 -row 2 -sticky nsew
   grid $y -column 2 -row 1 -sticky nsew

 # ----------------------------------------------------------------------

   return $w


 # demo code
 set text [scroll text .scroll -wrap none]
 pack .scroll -side top -expand 1 -fill both
 for {set i 1} {$i <= 30} {incr i} {
   $text insert end "This is line $i of text widget $text\n"
   if {[expr [expr $i%3] == 0]} {pack [button $text.b${i} -text "--- This is a my button ---" -default normal -command exit]}

Thank you very much in advance, have a great day!

convert to a decimal value

BM 15-08-2004

I have a series of 2 byte variables which I want to convert to a decimal value but can not follow the binary command details. I know that \xff = 255 and \x01\x0a is 266 etc. Could someone please quote the code for the conversion?

RS Here you are, software to go:
 proc bytes2int bytes {
   set sum 0
    foreach byte [split $bytes ""] {
        set sum [expr {$sum*256+[scan $byte %c]}]
    set sum
 % bytes2int \x01\x0a

hlist widget

Florian Bösch 26. Juli The hlist widget accepts an additional parameter for arbitary data associated with an entry. Neither the tlist nor the list widget accept such a thing otherwise. Do I miss it or is it realy so that it's tought to be a convenience function not worth the efford implementing it.

I also wonder how to do something like a table-view of data in tk ( see xforms table for a good example ).

Tk scroll bar / login sample

Scott Nichols

I have a Tk scroll bar question. For some reason I can not get the scrollbar widget to stretch to the size of the text widget's width. Below is my code, which is made up of samples from Practical Programming in Tk book and a login sample in the wiki. Thanks in advance.
 # Create the login window
 proc tk_login2 {w {title "Login please"}} {
    toplevel $w -borderwidth 30
    wm title $w $title
    wm resizable $w 1 0

    label  $w.s -text "Server:"
    entry  $w.server -textvar _server

    label  $w.dr -text "Driver:"
    entry  $w.driver -textvar _driver

    label  $w.da -text "Database:"
    entry  $w.database -textvar _databse

    label  $w.u -text "User name:"
    entry  $w.user -textvar _username

    label  $w.p -text "Password:"
    entry  $w.pass -show * -textvar _password

    label  $w.t -text "Tables:"

    text $w.tables -height 5 -width 10 \
        -wrap none \
        -xscrollcommand [list $w.xbar set] \
        -yscrollcommand [list $w.ybar set]

    scrollbar $w.xbar -orient horizontal \
        -command [list $w.tables xview]

    scrollbar $w.ybar -orient vertical \
        -command [list $w.tables yview]

    button $w.ok -text OK -command {set _res [list $_username $_password]}
    button $w.cancel -text Cancel -command {set _res {}}

    grid $w.s $w.server    -     -         -sticky news
    grid $w.dr $w.driver   -     -         -sticky news
    grid $w.da $w.database -     -         -sticky news
    grid $w.t $w.tables    -     -         -sticky news
    grid $w.ybar  -row 3 -column 4 -sticky ns
    grid $w.xbar  -row 4 -column 1 -sticky ew

    grid   $w.u $w.user -     -         -sticky news
    grid   $w.p $w.pass -     -         -sticky news
    grid rowconfigure $w 0 -weight 1

    grid   x    x  $w.ok $w.cancel -sticky news -row 11
    grid columnconfigure $w 1 -weight 1

    center_window $w

    # bind $w <Return> [list $w.ok invoke]
    raise $w
    grab set $w

    focus $w.server

    vwait _res
    destroy $w
    return $::_res

Peter Newman 12 July 2004: I think you need -weight non-zero, if you want a grid row or column to stretch. Don't think you've done that for the ybar.

aricb 12 July 2004 -- This line:
    grid $w.xbar -row 4 -column 1 -sticky ew

needs a -columnspan argument:
    grid $w.xbar -row 4 -column 1 -sticky ew -columnspan 3

SJN, Thanks, your suggested columnspan argument did the trick.

Florian Bösch Juli 6th 2004 ( shortify )

I need to remotely or localy out of sync, mirror multiple text widgets, some of them won't have access to a graphical display, have no tk root and will not be event pumped. How do I make insert/delete/mark_set work properly on them?

Peter Newman 6 July 2004: Have you seen MGS's text::sync?

Peter Newman 6 July 2004: Don't really understand your app. very well. But I can't see how the text widget would work if it didn't have a graphical display, Tk and the event loop. Could you not switch to using tkhtml. It supports background images (so you get much more interesting reports) - and is much easier to code for than the text widget. For example, to do "<B>Hello World</B>" in the text widget you have to a) create a font, b) create a tag, then c) insert the text and tag. Five to ten times the code for something that can be done with a single HTML string. In addition, your text widgetless apps can presumably create HTML, and send that to the HTML widget - in another local or remote process - via http or through some form of IPC like YAMI - for display. tkhtml also supports text insertion and deletion, much like the text widget.

Florian Bösch Juli 6th 2004 ( also shortyfied by me ) I do a distributed editing system. I need to check for differences between local-documents ( the text widget ) and the networked version of a document ( what would happen if you had only networked editing events ), and for this I need an invisible document capable of doing exactly the same stuff as the text-widget, only doesn't need display nor events.

Peter Newman 7 July 2004: Sounds interesting. Perhaps ulis Serializing a text widget might help. It's two complementary routines; one that writes the contents of a text widget to an ASCII string/file; and other that reads the same back into the text widget. I tested it and it seems to work OK. The file format looks quite simple too - so it seemed to me that an app. could write a document in that format - and then simply load the thing back into the text widget. In other words, external 3rd-party app.s could write a text widget document, without having access to the text widget themselves. Maybe some variation of that would work for you

Florian Bösch Juli 6th 2004: I deal with a distributed, mutable dataset. Replicating it on all nodes in its full length everytime somebody changes a part of it is something I consider inferior to replicating the stream of mutate-events. Of course I persist/restore the text-widget when somebody connects to the server.

Peter Newman 7 July 2004: With the tkhtml widget, you can build up a document with insert/delete, like the text widget. But it will also parse an HTML string/file in one hit. It parses it into a list of what it calls tokens (text, white space and tags). So:-
 <FONT size="7" color="Blue">Hello World</FONT>

might become:-
 { 101 font size 7 color blue }
 ( 102 Text Hello }
 { 103 Space 1 }
 { 104 Text World }

Note that each such token has a token id to identify it. So if each user has the token list of the master document, then they can quickly send/receive details of the changes they've made to others. And it's a piece of cake to receive details of changes made by others, and update the local copy of the master document.

Florian Bösch Juli 7th 2004: I need a text-widget as primary client document so users can edit the text. Thus I need a thing that reseembles a text-widget behavior on marks_set, mark_names, insert, delete and index as closely as possible, at a later point the same behavior for tagging is desired. It seems to me there is no other way to get this then to take an actual text-widget and make it uneditable and invisible. Even then there is a number of drawbacks. My server will need a windowing environment to run on, I need to split a thread from it to keep the mainloop happy, I need to move the local master widget out of a users way on the client. I can't help but feel stupid about such a solution ( partly because it renders a ton of servers unsuitable for my programm ) and partly because I feel that I have to do handstands, somersaults or an enourmous amount of code only to make an existing library happy.

Peter Newman 7 July 2004: Sorry, I thought tkhtml supported interactive editing. But it doesn't. But I still don't see that you have any problems. The documents that are being edited don't live in the text widget. Obviously they've got to be saved to disk. So if you use something like Serializing a text widget to do that, you then end up with an ASCII file that that be loaded directly into the text widget. But it can also be edited and maintained in console mode Tcl/Perl/CGI text crunching programs. You don't need the text widget to edit or maintain the document. It's just a case of designing the file format appropriately, so that not only can the text widget read/write it directly - but your client and server apps can do the same thing, independently of the text widget, and so as to support the collaborative, distributed editing you're talking about. The text widget also supports elided or hidden data. So possibly you can embed the data needed to support the distributed, collaborative stuff in the same file, and have that completely invisible to users editing the document in the text widget.

The other approach is the text widget source code. My understanding is that the text widget stores its data internally in a tree structure. Which is probably quite a complex one. But all you have to do is take the source code, and strip away the keyboard, mouse and screen access stuff. I looked at the source code a few months ago, and it seemed to me to be well-written, and clearly documented. But I don't see that's really the answer, since your problem is surely designing that ASCII master document file, so as to support/enable collaborative, distributed editing.

raise window

Sven Bauer June 29 2004

On raise there is a Problem described with bringing a window to the very top of the stacking order (under Windows 2000 as Operating System). Is there no known workaround for this Problem?

Peter Newman 30 June 2004: Isn't the info. below the sentence that mentions the problem the work-around?

Sven Bauer June 29 2004: You mean "focus -force $window" ? This doesn't work properly either (as mentioned). My Script is running a long time and my Window should appear in Foreground, when it has finished the work to show the results. If I've understood the Problem description correctly I need a method to "steal" the Permission to get focus... Think this really doesn't exist.

Peter Newman 30 June 2004: I found the discussion a little confusing. But I interpreted it as meaning that if you used the C code at the bottom, you had the final solution. Though I'd do the C bit in Ffidl.


June 27 2004 (Continuation of June 18 2004) by Hubert Halkin CATCHING COMPILER ERROR If a tk script contains a syntax error and I try to compile it (within a catch) the Wish application "unexpectedly quits" instead of "catching" the error. Suggestions? Hubert

Peter Newman 25 June 2004: You'll have to put your code up, so we can look at it.

Hubert Halkin here it is:
 proc myCompile { what } {
        if {[catch [list compiler::compile $what] result] == 1 } {
                puts "$what was NOT compiled result: $result"
        } else {
                puts "$what was compiled"

Please note that everything works if the file $what is syntactily correct.

MG - The bug must be in the [compiler::compile] proc, then, I'd imagine; that proc must be written wrong, so that instead of returning with -code error if there's a problem, it locks up/crashes the app. Can you put the code for that proc up, or tell us where it is?

Peter Newman 28 June 2004: Yeah, I agree with MG. And it's irrelevant whether the script being compiled has errors in it or not. The compiler should issue an error message and exit gracefully. But the catch in your script above would catch compiler::compile detected errors (returned via the Tcl error handling routines). It's not going to catch errors in the script being compiled (as your orginal question suggests to me that you were expecting).

Hubert Halkin I am using the package tclcompiler1.5. The C source for that package is at http://tcltkaqua.sourceforge.net/8.4.6/src/tclcompiler.tar.gz . Of course it would be nice if the user of the package could get information about the nature/location of the error encountered by the compiler. At a minumum I would expect to be informed that an error has occured (without necessarily specifying the details of the error) instead of crashing the app.

AK: The catch cannot trap the error because it is a segmentation fault. This is a deep issue with the handling literals in the compiler package, unfortunately. This is a known issue for which we don't have a resolution yet. The crash happens when it tries to cleanup its own and Tcl data structures after it encountered the error in the script. Note: The static checker in TclPro/TDK can help to find the location of the problem.

Hubert Halkin Thank you AK.


Mark Schonewille 27 June 2004: I found an extension called OSAItcl. As I understand it, this extension should allow for using Tcl as an OSA component in MacOS 9 or earlier (PPC only). It comes with a Read Me file written by someone called Vince. Vince says he used the PowerPC C++ OSA Component Sample by Matthias Neeracher. The extension is also accompanied by a shared library named shared Tcl.

There are no installation instructions. I put the extension into the extensions folder of the system folder, together with the shared library. It becomes available to applications such as the Script Editor and HyperCard as it should. Yet, if I try to run a small Tcl script, I get an error similar to "OSA component not found".

I have four questions. Does anyone have experience using this OSAItcl extension? How should I install it correctly? Is there a good alternative? Where do I find more information about using Tcl as an OSA component? As to the last question, I searched this WIKI for "OSA" but got no results.

I'd rather not use AppleScript to tell the Tcl environment to run a script. I want to run Tcl scripts from within the script editor or HyperCard directly.

Help to solve this problem is highly appreciated!

multiple cursors in a Text Widget

June 24th 2004 - I try to maintain multiple cursors in a Text Widget, I set marks for these cursor, but I also want to see where the cursors are at any given moment. How can I make those marks between characters visible?

Peter Newman 25 June 2004: As far as I know, the text widget has no built-in support for showing the marks. But you could put an image or a widget to the left or right of the mark - or perhaps set a different background for (say) 1 character either side.

Florian Boesch 25 June 2004: If I put an additional element in the text I have got two problems. It changes the positions of the marks, which is something I want to limit to real editing ( for reasons of synchronizing the text with other textual representations ), and it occupies text space itself, which looks rather funny. Managing multiple mark-positions accurately with some 'cursor' characters shifting around the whole place also gets messy. Inserting tags in the text is working, but I think those are not very intutive representations of text, and they might be obstructed by other marks insofar that the cursor will have a bad visibility. Also I have to unset/set the tags everytime the mark moves. Is there a way to determine how many times a given tag is applied in the text?

MG - This should show you how many times a particular tag appears..
 expr "[llength [$text tag ranges $tagName]]/2"

June 6th 2004 - tcl version 8.0.5 on SCO Unix

I have installed tcl version 8.0.5 on SCO Unix. Tcl installation has gone through perfectly well. I have downloaded expect version 5.41. I am not able to install expect. When I run make I get the following errors: TCL_INTEGER_SPACE, the symbolic constant is not defined is any of the header files and while compiling program exp_command.c the compilation terminates. The error is that the structure Tcl_ThreadDataKey is not decalred either in the program or in any of the header files included therein. Based on this structure type the data element dataKey is defined which is passed as a pointer to functions. Where have these been decalred. Or, is it that the verion of expect that I am using with tcl is wrong. Even compilation of expect.c throws up hundreds of errors. Could be something wrong with the version of expect.

schlenk Probably not with your expect version, but it could be that your tcl version is a bit dated. Recent version is Tcl 8.4, Tcl 8.0.5 must be about a decade old. Maybe get a more recent Tcl version?


Breadcrust on 12th June 2004: I'm trying to use iconwindow on a window but it wont work. Code:
wm withdraw .

# ...

tk_toplevel .icon
label .icon.img -image $::img::xbashserv16
pack .icon.img

proc mainwindow {} {
  wm geometry . 400x500+100+100
  wm resizable . false false
  wm protocol . WM_DELETE_WINDOW confirmExit
  wm iconwindow . .icon

# ...


not long after this code, mainwindow is called and . is deiconifyed. but the icon isnt there!

Peter Newman 10 June 2004: As I read the wm manpage, the iconwindow appears when . is iconified - and disappears when it's de-iconified - as you're reporting. So wm iconify ., after wm iconwindow . .icon should produce it.

Breadcrust on 13th June 2004: I tryed it, but it still doesnt work. maybe its a bug in tk? or maybe its my window manager (kde)? ive tryed gnome too, but still no improvement

FW: See How do I give my application a color icon. Since the icon is only checked for when a window is drawn onto the screen, on some platforms there are tricks needed. That discusses the issue.

-cursor @filespec

Peter Newman 5 June 2004: I'm wondering if -cursor @filespec has a bug in it. Using:-
 $mywidget configure -cursor built-in-cursor-name

works fine on my Windows 95 Activestate Tcl 8.4. But:-
 $mywidget configure -cursor "@[file attributes {c:/temp/cursors98/link.cur} -shortname]"

causes a complete system lock-up after a few seconds. Has anybody else used this form of -cursor successfully? Has anybody else experienced problems with it? Many thanks.


LES on June 1st, 2004: I have this habit of typing a command in Tkcon and an obviously incorrect option (like [winfo dsfg]) to get a list of the available options. Is it possible to acess that list programatically? Say, get that list of existing options as output and foreach it?

Lars H: The list you get is probably an error message, so what you do manually by typing could be done programmatically with catch:
  catch {winfo dsfg} msg

I'd expect some additional parsing of this $msg will be needed. TIP #193 [14] seeks to deal with the general problem in a more robust way.

LES: Why, of course. "In Tcl, errors are friends you can play catch with". Duh!

put binary data through a socket

05/27/04 how I can put binary data through a socket without it interprets 0x0A as "new line" character? following code should (just) show what I mean ...
 fconfigure $chan -buffering none -translation binary
 gets $chan data
 foreach x [split $data {}] {
     scan $x %c dval
     puts -nonewline "[format %02x $dval] "   ;# result I want to see: 0A FF FF

 fconfigure $chan -buffering none -translation binary
 puts $chan \x0A\xFF\xFF             ;# 0x0A at end will be added by puts-command
 flush $chan                         ;# ... sign for server that transfer is complete

Any ideas?

MG May 27th 2004 - I believe (not tested) the problem is that you're using [gets], which retrieves the information available on a channel up to the last newline. Try replacing your gets $chan data with
 set data [read $chan]

and try again.

It doesn't work but taking read instead of gets makes sense of course. I think the problem is the configuration of channels. Sample code for trying I put here now:

 console show

 proc client_handle { __chan __ipaddr } {
        set __data [read -nonewline $__chan]
        foreach _x [split $__data {}] {
                scan $_x %c dval
                puts -nonewline [format %02x $dval]
        puts ""
        catch {close $__chan}

 proc request_handle { __chan __param2 __param3 } {
        fileevent $__chan readable "client_handle $__chan $__param2"
        fconfigure $__chan -buffering ful -translation binary

 socket -server { request_handle } -myaddr localhost 9393

 set __chan [socket localhost 9393]
 fconfigure $__chan -buffering full -translation binary

 puts $__chan "\x0A\xFF\xFF"
 flush $__chan

hope, we will find a solution ...

PB: you will need to set channel into nonblocking-mode (-blocking 0). that should work.

'Recent Changes' page

24may04 Dossy -- How do you get your initials added to the Recent Changes page next to your IP address? Like these:
  Windows wish console . . . JH,
  ...                       ^^^^
  A Snit News Ticker Widget . . . NEM,

MG - See Wikit user names for the answer to this one

A second question: has this wiki been getting hit with lots of spam URL vandalism lately? The AOLserver Wiki [15] has been getting hit nearly daily -- I'm about to implement registered editors only (confirm identify before being allowed to Edit pages) in response to this annoyance. But, it's a step I would really rather avoid, if possible. Suggestions on how to alternatively handle the vandalism would be appreciated, too.

5/23/04 - vTCL

Anyone have experience with VTCL and the output from it? What I'm worried about is the "final output" - whether it is completely transparent? I'm reading an older manual, and the manual (on visual TCL) says that a "competitor to visual TCL is Tk" (as if the "pure" Tk is a different beast from the output from vtcl). Anyone know anything about this? Is the output from vtcl "just the tcl" (with, of course, the internal name conventions for the program)? Is is it a different extension that is difficult to understand later without using vtcl.

Also, any other "visual" tools that are recommended would be of great help. Thanks. d

help with regsub

05/21/2004 (or 21-MAY-2004) --

I'm trying to write a proc that "sanitizes" text so it's suitable for including in an html document. I use [string map] to "escape" the < > and & characters, then I [string map] again to turn specific sequences like <i> and </strong> back into straight html. My problem is with trying to "unescape" the < and > characters in something like <a href=(url)>(text)</a>. I do want to permit hyperlinks. I know exactly how to do it by parsing the text a character at a time the way I would in Pascal or C, but I want something a little more concise. I'm pretty sure regsub can do what I want, but I don't have a clue how. Help? aa

Peter Newman 22 May 2004: You could write a book providing the generic answer to this question. Could you perhaps provide say a few lines representative of the raw text you want to convert?

MG - I think this is a pretty good example of RMMADWIM. It's pretty much impossible; sometimes HTML pages have text reading <b> or </i>, etc, and want that text displayed, not formatting done. Unless you can guarantee that'll never happen, I doubt it's possible. As Peter says, though, it'd help if you could give some actual examples of just what you're working with.

FW: Hmm, reading your question simply, I'd say maybe:
  set newString [regsub -- {<a href=(.*)>(.*)</a>} $string {<a href=\1>\2</a>]

Of course, that for example doesn't notice any links with extra whitespace within the tags (rather easy to add granted, replace a couple spaces with " +"s), but you get the idea.

aa - Thanks, that's exactly what I was looking for (after adding the missing } to the end of the replacement string, of course). I think you're saying that (.*) will fail to match when there are spaces, though the suggestion on how to fix it isn't clear to me. My understanding of regular expressions is still miniscule.

FW: Nah, what I'm saying is that won't match things like
  <a  href= "url">...</a>

because I hard-coded the whitespacing within the tags. Here's a less readable solution which acommodates for any ordinary permutation (with the end-brace added too):
  set newString [regsub -- {<a +href *= *(.+?)>(.+?)< */a *>} $string {<a href=\1>\2</a>}]

{ *} represents any number of spaces, including none, and { +} represents at least one space. I've also fixed the regexp to use non-greedy quantifiers so it won't take the beginning of the first link and the end of the last one as one big link. It's a long story. Just use it, you'll do fine ;)

aa - I appreciate the pointer to "non-greedy" quantifiers. Without them, my first real test of the code did turn things into one big link.

Peter Newman 25 May 2004: Try [16] for a great tutorial on regular expressions. Takes you from the standard stuff, to the advanced, in easy to understand chunks.

aa - Someone apparently misunderstood the nature of the task and "helpfully" replaced < with <, etc, ruining the code completely. I think I repaired things appropriately.

size of wm-decorations

May 20 2004

How can you work out the size of wm-decorations on any X11 system?
    wm geometry $win ; # returns the size of the window contents on X11, but of the total window on Windows, OS X.

DKF: You're SOL here. :^( The problem is that different Window Managers (which Tk is not responsible for) produce different answers here. Sorry.

Hmm, a related problem is that 'wm geometry' is totally incompatible between X11 and Windows. On Windows it is used to get/set the window including its decoration, while on X11 it only deals with the window contents. This means using 'wm geom' in a cross-platform way is basically impossible. I guess this is a bug in Tk really.

See Documenting 'wm geometry'

current mouse x,y position

Vince May 19 2004

How can one determine the current mouse x,y position programmatically (i.e. without being triggered by an event). For example is it possible to write a proc:
    proc mouseCoordinates {} {
        # What goes here?

which returns the x,y pair of coordinates where the mouse is currently pointing?

MG May 19th - To get the x, y, or x and y coordinates of the mouse pointer on the screen containing window $w, use:
 [winfo pointerx $w]
 [winfo pointery $w]
 [winfo pointerxy $w]

access Webcam-devices

Hi, I'am looking for a package or libary for Tcl/Tk to access Webcam-devices under Windows, just to make a single snapshot and saving it as imagefile. Hints for an existing commandlinetool to make webcam-snapshots would also be nice. Unfortunatelly I couldn' find such software in www. Thanks in advance.

PB vfwtcl-package is the right one I think. Take a look at http://avicaptcl.sourceforge.net/ Note, that you will need Tcl/Tk 8.3 or higher.

button with a image


Hi, following piece of code should produce a button with a image within. Unfortunately, image-command is not be able to read vars $xmax and $ymax in data-context. Is there a way to make image-command reading vars?
 set xmax 8
 set ymax 1

 image create bitmap pic -data {
 #define pic_width $xmax
 #define pic_height $ymax
 static unsigned char pic_bits[] = {

 button .btn -image pic
 pack .btn

Thanks for each hint. PB

MG May 7th 2004 - The problem would seem to be the braces you're using. When you give a string in {braces}, Tcl doesn't evaluate it for variables, etc; you'd need to use "quotes" instead (or force substitutions with [subst]?).
  set xmax 8
  set ymax 1
  image create bitmap pic -data "
  #define pic_width $xmax
  #define pic_height $ymax
  static unsigned char pic_bits[] = {

PB Tcl can be so easy :) Thanks for your help. (By the way: My first try was to put all data from data-context into square brackets, but it failed.)

MG - Basically, the rule is that [square brackets] force evaluation as a command, "quotes" force evaluation as a string, and {braces} do no evaluation. :) - RS: In fact, "quotes" just group into one word (in case of whitespaces etc.), so "$foo" == $foo, etc.


how is auto_path supposed to work?

I'm trying to run the script "C:/CSLU/Toolkit/2.0/script/training_1.0/categories.tcl", but from within a different directory. E.g.
   CSLUsh 2.0.0% pwd
   CSLUsh 2.0.0% source categories.tcl
   couldn't read file "categories.tcl": no such file or directory

From DOS, tcl C:/CSLU/Toolkit/2.0/script/training_1.0/categories.tcl invokes the script, as does source categories.tcl from the tcl80 prompt, but only from that directory.

My auto_path includes "C:/CSLU/Toolkit/2.0/script", so isn't it supposed to look inside the training_1.0 directory as its immediately below? As you can probably tell, Tcl and me are still circling each other like uncertain dogs. :-)

CPW 6th May 2004

RS: man library: "auto_path - If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable." But no implicit searching of sub-directories - I'm afraid you have to specify them (lappend to auto_path) yourself. Note however that it may be easier to just install packages in the usual location (below .../tcl/lib, for instance), if you can.

MG - Isn't $auto_path only for things like package require, whereas source needs a complete path? So you'd either need...
   CSLUsh 2.0.0% pwd
   CSLUsh 2.0.0% cd ./script/training_1.0
   CSLUsh 2.0.0% source categories.tcl

   CSLUsh 2.0.0% pwd
   CSLUsh 2.0.0% source ./script/training_1.0/categories.tcl

RS admits MG is right - auto_path is most prominently used for auto-loading files where a pkgIndex.tcl is in the same directory... and source just wants an absolute, or relative, path.

tcl8.4.6 on AIX 5.1

I just installed tcl8.4.6 on an AIX 5.1 box, the install went ok, but after the make install I ran make test and it blew up with a segv signal. After going through the Makefile and the config.out file I saw no problem. So, I tried the make shell and did a puts "Hello" but that segv'd as well tried tclsh and puts again it blew up went back to my home directory and tried /path/to/tclsh and at the prompt again with puts "Hello" and it blew again. Now comes for the weird part I created a small tcl script in my home dir with #! /path/to/tclsh

puts "Hello"

Lo and behold it ran. I added more stuff to the script and all went fine with it. No change in the other tests. I installed with --enable-64bit and --prefix /path/to/install/dir. Has anyone else run into this? Can this install be trusted? Any ideas what went wrong? Thanks Ken

Question moved from clobbered New Pages web page.

Does someone know, why this programm doesn't show the keyboard key which was pressed?
 fconfigure stdin -blocking FALSE -buffering none -translation {binary binary}

 while {1} {
  set line [read stdin]

  after 500
  switch $line {
        a {puts "You pressed a"}
        b {puts "You pressed b"}
        c {puts "You pressed c"}

MG Apr 28th 2004 - You shouldn't use while {1} for reading from a channel, since it won't always be readable. The better solution is to use the fileevent command. Something like...
 fconfigure stdin -blocking false -buffering none -translation binary
 fileevent stdin readable "readChan stdin"
 proc readChan {chan} {
  puts "You pressed [read $chan]"

I haven't tested that, but I believe it should work. (May 4th - at least, it should now that the proc has the same name as the command 'fileevent' calls. Apparantly I was half asleep when I wrote that first time around:P)

28.04.04 SZ edit

 puts "Testing SPACE: [regexp -start 0 -- {^[[:space:]]+} {   Testing our language} v]"

produces "Testing SPACE: 1", but
 puts "Testing SPACE: [regexp -start 1 -- {^[[:space:]]+} {   Testing our language} v]"

produces "Testing SPACE: 0". Other regexps, such as [\ \t\n] do not work too.

I use tcl8.3 under Linux. Is it bug, or did I do something wrong? This thing prevents me from using Tcl regexp as a basis for simple lexer.

Peter Newman 28 April 2004: Your regular expression looks OK to me. But I'm no expert. However,I NEVER build up regular expressions using double quotes. You end up with VERY hard to understand/debug problems like you may have above, due to the need to escape both the Tcl special characters ({, [ and $ for example) - which are also special and need to be escaped in regular expressions. I would code the above as:-
 set re {^[[:space:]]+}
 puts "Testing SPACE: [regexp -start 0 -- $re {   Testing our language} v]"

That takes you out of quoting hell. But whether it will fix your problem I don't know. If not, it looks to me like regexp has a bug in it. (However I've never used the -start option. Maybe that's the problem?)

Lars H: There is no quoting hell here! From that Tcl starts scanning the command following the [ of a command substitution, and until it finds the matching ], it makes no difference whatsoever what surrounds those brackets. The Tcl parser never does more than one thing at a time.

MG Apr 28th 2004 - When you use the -start option with [regexp], ^ no longer matches the start of the string (according to the Win help for ActiveTcl Try using this instead...
  puts "Testing SPACE: [regexp -start 0 -- {\A[[:space:]]+} {   Testing our language} v]"
  puts "Testing SPACE: [regexp -start 1 -- {\A[[:space:]]+} {   Testing our language} v]"

SZ Thank you! This solves the problem.

4/27/04 Has anyone had success building dqkit on solaris sparc (I'm running 2.8)? I'm having Linking problems (i.e. - -ldl)

WK Solaris support has been added in 0.8 releases. It took some work to get all things right, but it shouldn't be an issue anymore. Tested on SF compile farm (both sparc-solaris1 and sparc-solaris2).


hi, in 19/02/2004 I asked for saving contents of canvas-widgets. follwing lines should help, but it doesn't:
 package require Img
 set im [image create photo -format window -data .canvas]
 $im write mycanvas.gif -format GIF

Interpreter says 'couldn't recognize image data'. Interpreters I checked out are wish82.exe and itkwish31.exe running under XP.
 package require base64
 package require Img

 canvas .cv
 pack .cv

 proc inlineGIF {img {name ""}} {
    set f [open $img]
    fconfigure $f -translation binary
    set data [base64::encode [read $f]]
    close $f
    if {[llength [info level 0]] == 2} {
        set name [file root [file tail $img]]
    set image [image create photo [list $name] -data {\n$data\n}]
    .cv create image 32 32 -image $image

 inlineGIF ./test.gif testgif

What is going wrong? Thanks for all answers!

Peter Newman 26 April 2004: I'm not familar with img and the other stuff you're using; so I can't really comment on the code. But see Serializing a canvas widget, which presumably does what you want.

2004/04/24 DK

Is there a tidy program, similary to perltidy (http://perltidy.sourceforge.net/), that cleans up tcl code?

Peter Newman 25 April 2004: frink might help.

2004/04/22 Vince

What is the right (x-platform) way to find the size/position of a toplevel window, including all window-manager decorations (so that I can position two windows without their wm borders overlapping)?

See Total Window Geometry


hi all. i'm using a TCL script that uses the 'flush' call to open and send commands to an external (non TCL) program. here is a sample of my lines:

to start the pipe to the program:
         set OUT [open "|the_program " w+]
         puts $OUT "command_1 "
         puts $OUT "command_2 "
         puts $OUT "command_3 "
         puts $OUT "command_4 "
         puts $OUT "command_5 "
         flush $OUT

then i'll make subsequent calls, in a separate function, with something similar to:
         upvar #0 OUT out_
         puts $out_ "command_1"
         puts $out_ "command_2"
         puts $out_ "command_3"
         flush $out_

it works OK, but i'm apparently experiencing a buffer overload, and the program stalls/freezes after some use. it's somewhat described on this page: http://wiki.tcl.tk/919

anyone know how i might be able to adjust my output (the above) so that i do not experience buffer overload (and, subsequently, a program stall)?

many thanks for the help!

2004/04/22dk i've been given the idea that using mkfifo to create a piped file for control of output may resolve the issue. could anyone give me an example of how i might do so? i've had some trouble trying to figure it out. thanks!

2004/04/22[dk-edit2] changing
     [open "|the_program " w+]

     [open "|the_program " w]

solved the lock up problem, but i'd still like to see the fifo example if anyone cares to share.

Vince 2004/04/20, Has anyone tried building TclKit from the 8.5a2 cvs sources of Tcl, Tk?

Hubert Halkin 2004/04/20

Multiple interpreters and cd command. I have one application with several interpreters. Each of those interpreters needs to move around INDEPENTLY in the directory structure. Unfortunately a cd command in one interpreter affects ALL the interpreters. Is this a feature or a bug? Has anyone done a work around for that? Thank you.

Peter Newman 21 April 2004: See this detailed article [17] on interp by Brent Welch. It mentions cd. I've never used interp myself, so I've no idea if it'll answer your question.

Hubert Halkin 2004/04/21 Thank you Peter. I own all four editions of Brent Welch: this is where I learned the little I know about interp.

MG April 21st 2004 - I've also never used interp, but could you not keep a variable in each interpreter of the absolute path you want to use in that interp, and then use [file join $path $file], rather than changing directory? $path should be unique to each interp, even if cd affects them all.

Vince cd is a process-wide concept (in fact it is an OS concept for each process, as one can tell when using 'exec' which implicitly knows what the current pwd is). It might be possible to modify Tcl's behaviour to allow for interp-specific cd/pwd, but the semantics of commands like 'exec' would have to be defined appropriately -- if you think you can do this, then this might be a worthy addition to Tcl.

Hubert Halkin 2004/04/21 Thank you MG and Vince. You suggest the type of work around I am thinking about. If you ever hear that it has already been done, let me know. By the way is there some reservation about using interp in the Tcl community? I was surprised that there was no mention of interp in the latest book by Cliff. Multiple interpreters are essential to my application but I do not know of any other application making use of them.

MG April 22nd 2004 - I've seen mention if interp used in a few places, though to be honest, I've never found a use for it in my (somewhat limited) use of Tcl, and can't really think of one; I know the console on Windows uses its own interpreter, but to be honest I don't really see why even that's necessary. May I ask what your application is, and why it needs to use separate interpreters?

2004/04/19 YC I have a couple of entry widgets that receive focus in and focus out events and process SHARED data on those events. Unfortunately, Tcl/Tk event handlers (the "-command" arguments to the entry widgets) are dispatched asynchronously in different threads (as it seems to me) which can cause unpredictable results. Example:
 - click on entry field A
 - now click on entry field B

The focus-out handler of A gets called, but before it can finish, the focus-in handler of B is called.

I think what I need is a way to specify the handlers for A and B be executed as an atomic operation. Or alternatively, I need to put a lock on the data item that A and B share.

Is there an easy mechanism to allow me to do it without getting into too deep in thread programming? Or maybe there are some simple event handler writing suggestions for me to follow to avoid the problem that I am having.

Thanks for any pointer


Peter Newman 20 April 2004: The Tcl Event Loop is completely undocumented, so we're both just guessing in the dark. But in my experience, the Tcl Event Loop seems to operate synchronously. In other words, event handler i doesn't start till event handler i-1 has finished. UNLESS you call update or after ms script in event handler i. Which you should NEVER do (for reasons discussed elsewhere on this Wiki - and it's even more dangerous than those guys suggest).

Put another way, I don't think the Tcl Event Loop handler uses threads, and runs event handlers (-command routines) asynchronously in them. Or put yet another way, Tcl already does what (I understand,) you're wanting it to do. And the only way that focus-in B can get called during focus-out A, is if your focus-out A code (or some routine or package it calls,) calls update or after ms script.

I could be wrong about the above, but check your code again in light of those comments. Sorry, it's not a complete answer (because without the code I'm not entirely sure what you're trying to do).

[YC] April 21 2004 Peter, you are absolutely right. There is a call to update in some parts of the code that I wasn't aware (written by someone else) that is causing what I observed. Thanks a lot. YC

2004/04/19 Hubert Halkin Where can I find a Windows Tcl compiler package which can be distributed freely? The ActiveTcl compiler package requires a license key. I could not find a compiler package on the equi4.com site. On the Mac OS X I have used the compiler of the Aqua distribution. It works well and produce byte code which can be used also on the Windows machine.

MG April 19th - It sounds like freeWrap could be what you're looking for. That allows compiling of Tcl scripts into Windows executables, using Tcl/Tk 8.4 . There's also prowrap, an older version of TclApp which performs the same task, but I believe only works with Tcl/Tk 8.3 FW: See deployment.

Hubert Halkin 20 April 2004 Thank you. I want something producing an .tbc file (NOT an .exe file)

Peter Newman 20 April 2004: TclPro is the Tcl 8.3 version of ActiveTcl's Tcl Dev Kit. It's freeware and has a license key - but that license key is available from the download site [18].

I have an app. that I want to distribute commercially, and wanted to compile/obfuscate. Abd TclPro and TclDevKit are the only two (currently available) Tcl compilers that I could find. But TclPro wouldn't compile my Tcl 8.4 application. And I noted that there seem to have been some previous Tcl compilers that now appear to be defunct. Obviously working Tcl compilers are not easy to write. Since I was unwilling to fork out good money for TclDevKit with no guarantee that it worked (on my app.), I decided to give obfuscation a go. But the only Tcl obfuscator I could find was frink. But all that does is strip comments and unnecessary white space - and wrap everything onto a (default 80 column) line. So I wrote my own obfuscator, which I'm hoping to finish today.

It strips out the comments, and (irreversibly) converts all variable, proc, and widget path, names to randomly generated strings of "1" and "l"s. So for example:-
 proc my_proc { parameter1 parameter2 } {
     global my_variable
     set my_variable $parameter2

 proc 1ll111l1l1l1ll1 { l1l1l1lll11l11 l1l1l1lll1l1l1 } {
     global l1l1lll1l1l1l1
     set l1l1lll1l1l1l1 $l1l1l1lll11l11

It's not perfect (standard Tcl command names and text strings go through untouched, at the moment). But hopefully anyone seeing a complete app.'s worth of the above will find it easier to reverse engineer the app. - rather than try to manually de-obfuscate the obfuscated source. Let me know if you want a copy.

Another approach would be Mktclapp.

Hubert Halkin 20 April 2004

Thank you. I will work on all that.

JH: Please note that you can get a free trial of Tcl Dev Kit whereby you can test and see that everything works as expected before you buy.

Hubert Halkin 20 April 2004: I have indeed a licensed Tcl Dev Kit. I want something that I can distribute freely.

2004/04/15 JB: My computer shows this strange behaviour:
 (bin) 22 % expr sin(3)

The result does not look like a mathematic expression and causes an error. This problem occurs somwhere during a complex tcl-application but I cannot locate the reason. My system configuration is Windows 2000/Tcl 8.2.2/Tk 8.2.2/BWidgets 1.2

Does anyone know how to handle this problem within this Tcl/Tk version?

FW: That is the correct value for sin(3). Could you elaborate a bit?

% expr sin(3) 0.14112000806

No that is the correct value for sin(3), no commas or extra decimals. Some weird locale issue?

2004/04/16 JB: The format of the result mixes up comma and full stop, actually it should look like your result. The problem seems to be related to the tcl command win32::link which is included in my application by way of a C-program (tlink32.c). This command creates a program shortcut in the Windows start menu. After this command has run the tcl command expr produces an error.

Do you know an alternative way how to create a regular and consistent program shortcut in the Windows start menu?

Peter Newman 17 April 2004: As far as I know, to add items to the Windows Start Menu, you just add the necessary directorys, files, and/or shortcuts to the start menu directory - which by default, on Windows 95 at least, is C:\Windows\Start Menu\. Find and browse that directory tree, comparing it with the displayed Start Menu, and you'll soon see how it's done.

The only problem is that if your distributing your program to other users, you have to find out where the start menu is on the system your installing to. I use the Nullsoft installer, which provides this info, as do most others. But I assume that they (and you) can get it from the Windows API.

To create the link/shortcut files themselves, see Windows shell links.


sheila I'm having difficulties with a script I adapted for changing env variables. When I use it to change my environment variables, the env global in my wish shells does not update until I use the Windows System Properties panel to view the environment. I started a wish shell before running the gui, printed the array before and after, and saw no change. A wish shell started after running the gui still had the old values as well.

here is the script I used
 package require registry

 proc set_user_env {key value} {
    global env
    ;# Support OS expandable params
    if {$key == "PATH" || [string match "*%*" $value]} {
        # Indicate this may have expandable params in it
        set type expand_sz
    } else {
        set type sz
    if {[catch {registry set "HKEY_CURRENT_USER\\Environment" \
            $key $value $type} ec]} {
        tk_messageBox -title "OK to Continue" -icon info \
                -message "Error setting env var $key to $value"
    set env($key) $value

Peter Newman 15 April 2004: Which Windows are you using? On my Windows 95/Tcl 8.4, I've never experienced trouble with environment variables from Tcl. "set env($key) $value" is ALL you need. (I've no idea what all your registry fiddling stuff is about.)

Under Unix, Linux or Windows at least, a child process CAN'T change its parent's environment. So if you go:-
 wish script_that_does_"set_env($key)_$value".tcl

then the "set" will work whilst the script is running (by changing the environment of the wish/tclsh it's running in - which on Windows at least, is a COPY, in another memory location, of the environment of its parent). But when wish and the script exit, that environment disappears along with them, leaving you back at the environment you started with.

In general, you CAN'T change the environment of the current process, by using wish or tclsh to start a new process and then running the environment variable changing script therein. And similarly in Perl and Awk. IMHO the inability of a child to change its parent's environment is a serious defect/bug. I don't see why a child shouldn't be allowed to do this on demand. You can get around this on MS-DOS and Windows 9x at least, by searching operating system memory for the current process's parent's environment (I probably have or could get the docs). But whether that's portable to Windows NT/2000/XP, I don't know. And there are usually better ways of doing things.

If you want to (permanently) change the Windows PATH environment variable - such as in a program install script, for example - you have to edit the AUTOEXEC.BAT file (and then restart the computer) (MS-DOS and Windows 9x; not sure about NT/2000/XP). The gory details are no doubt on the Net somewhere.

3-4-2004 I am trying to call Tk functions from C program, the simple program below does not compile:

#include <tcl.h> #include <tk.h> int main () { }

g++ test.C tk.h: No such file or directory

I am using a Mac, OS 10.3 and I installed tcl/tk using fink as well as using dmg image I downloaded from apple.com. However, it seems the compiler still cannot find tk.h (but it can find tcl.h). Thanks for the help.

31-03-04 BM How do I read the x & y resolutions of a monitor in to pass as a variable to a routine such as:
 label .l -width $x -height $y

MG March 31st 2004 - Try this...
 set x [winfo screenwidth .] ; set y [winfo screenheight .]
 label .l -width $x -height $y

Note that that only works if the label is displaying an image; if it's displaying text, the -width option is characters, rather than pixels.

01-04-04 BM Thanks for the reply. Winfo only gives info on the root window created by tk/tck. I did not explain what I am attempting very well.

I have a picture ($filenm.jpg) which I want to resize the display by calling convert
 exec convert -size $xx$y $filenm.jpg $filenm2.jpg

Then I create a picture
 image create photo img -file $filenm2.jpg

& insert it into a label
 label .l -image img

This label will then be packed into a toplevel widget. What I want to find is the resolution of the monitor so that the image in .l fills the whole screen irrespective of a specific resolution as the app may run on various boxes.

Peter Newman 1 April 2004: Surely "winfo screenwidth/height ." does what you want. On my Tcl 8.4, Windows 95, with a 800x600 monitor it (correctly) returns 800x600. The monitor can also do 640x480 and 1024x768 etc. But it's what it's currently set to that matters - which is what "winfo screenwidth/height ." (in my case, correctly,) reports. On a 1024x768 monitor, it should return 1024x768...

19/4/2004 BM - thanks for the help, I misread the documentation so did not try it 1st time. It now works in linux & win95 but coding it for both was a nightmare

30-03-2004 Hubert Halkin I have a TK script involving a master interpreter and several slave interpreters each of them with their own separate windows. I want to define a proc bringForward in the main interpreter which, when invoked with the name of one of the slave interpreters, bring the window corresponding to that slave interpreter to the front of the all the windows.

RS Wouldn't this be enough?
   $slave eval raise $slaveToplevel

31-03-2004 Hubert Halkin It works.Thank you. I was under the wrong impression that raise worked only among the windows of the same interpreter.

RS: It does. But with (interp) eval, a master interp can assign work to his slaves...

25-03-2004 MSH I have written a TK script to enable my collegues to generate executables from tcl scripts using a starkit/starpack and I would like a solution to prevent copying our standard libraries (eg BWidgets) into every xxx.vfs/lib directory, I tried making a BWidget.kit as per Starkit - How To's which works fine but generates a VFS erro when it is included in the executable (source $starkit::topdir/BWidget.kit). Does anyone know how to include xxx.kit in yyy.kit without extracting it first to /tmp or similar.

25-03-004 BM

I wish to be able to resize downwards any selected photo in order to display it in its entirety full screen - eg my camera takes photos @ 1800 x 1200 pixels approx. For display purposes I wish to display at 800 x 600 or 640 x 480.

I have tried the following sample code:

#create a label to hold the image


pack .l

#enter the name of the oversize photo

set filename "....."

#create the image & load the photo

image create photo img1 -file $filename

#create a second image to hold the resized photo

image create photo img2 -file ""

#copy & resize the image

img2 copy img1 -shrink -from 1 1 -to 1 1 800 600

.l configure -image img2

This results in displaying a portion of the original image at the original size, not a reduced image in its entirety.

The documentation for 'image - copy - shrink' is totally inadequate, I found it of no use whatsoever.

Could someone please advise me how this process should be coded as I have been unable to find any examples on the web

MG March 25th, 2004 You seem to have misread what the -shrink option is for; it shrinks the target image to make it the size of the image you're copying, if it's larger. The -from option, too, isn't for scaling, but for selecting only a part of an image. What you actually need is the -subsample option (or -zoom, if the picture is smaller than 800x600 and you need to enlarge it). Since you can only use whole integers with -subsample, though, I don't think this is totally possible. But I think you'd want something like this...
 set num [expr [image height img1]/800]
 img2 copy img1 -subsample $num

That won't be exactly right, but that's as near as I can think of, without shrinking the image right down and then enlarging it with -zoom again. Anyone know a better way?

Peter Newman 26 March 2004: TclMagick does image resizing. And there are heaps of (freeware) command-line driven (as in DOS/Windows/Linux shell command line) image resizing programs on the Internet that you could run with exec. You could also resize the image yourself. The basic algorithm is just a few lines of code. But the above solutions would probably be faster (than something in Tcl)

26-3-04 BM - Thanks for the replies, I will experiment some more. Under linux I am using qiv but have not found an equivalent for windows yet.

Jorge Moreno March, 24, 2004 How to know if an icon is being displayed in the system tray (windows 98)? in other words: how to query if a process that displays its activeness by an icon in the system tray is active?

Peter Newman 26 March 2004: Have you checked out winico?

How can I create a Tk app with no GUI? I would like to use the Img library in a C extension for what is essentially a batch application, but the default (main) window appears (with nothing in it, of course) when I load the extension (or soon after - it's not clear what the exact sequence of events is). I saw one suggestion to use "wm withdraw .", but I'd rather not have to do that in every script I write with the extension, and it seems to be unreliable, and when run with tclsh will hang with no GUI when it reaches the end of the script (whereas if I close it by hand, tclsh returns.)

Thanks, pcf

Peter Newman 24 March 2004: I don't see anything wrong with either "wm withdraw ." or "wm deiconify .". And either "exit" or "destroy ." at the end of the script should cause both tclsh and wish to return. Note that wish has what to me is a bug in it, in that it automatically appends the event loop to every script it runs. So when you reach the end of the script it "hangs" - and must be closed manually or with "exit" or "destroy ." - instead of automatically exiting, as the Perl or Awk programmer expects. But that shouldn't happen with tclsh, unless you've (intentionally or otherwise,) invoked the event loop (with vwait or tkwait for example).

pcf: This script:

package require Tk wm withdraw . puts foo

prints foo and hangs (with no visible window) when run with tclsh (well, it creates the window and then hides it - this is evident from the fact that the console window I am running it from loses focus, which is annoying) Append an "exit" and it exits. That works - thanks Peter.

Peter Newman 25 March 2004: Looks like "package require Tk" automatically invokes the event loop too. I've never used it. I always "wish" and "exit". I'm pretty sure you could get the focus sorted with either the "console" and/or "focus" commands.

how to create symbolic link on windows 2000 to an existing directory (Tcl 8.4.6)?
 following call fails:    file link aLink.lnk aDirectory
 following call succeeds: file link aLink.lnk aDirectory.lnk
           (where aDirectory.lnk is a shortcut to aDirectory)
 why does the former fail?

schlenk (2004-03-22) Probably because it is windows: On Windows NT/XP (NTFS filesystem) file link can be used to create symbolic directory links (a little known feature of Windows) or hard file links (an almost as little known feature of Windows).

So you can create links from files to files and from directories to directories, but not mix them. Your use of .lnk files indicates you want something different, more like the faked links used on FAT drives.

(2004-03-24) Thanks for you answer. My mistake was, that i wanted to make a symbolic link to a directory on a substituted drive (D:\ => C:\Drive_D), which is not possible.

MSW (2004-03-08) bug or feature ?
 % namespace eval A-B { variable bla; array set bla {a 1 b 2 c 3 d 4} }
 % parray A-B::bla
 A-B::bla(a) = 1
 A-B::bla(b) = 2
 A-B::bla(c) = 3
 A-B::bla(d) = 4
 % puts $A-B::bla(a)
 can't read "A": no such variable
 % puts ${A-B::bla(a)}
 % foreach n [array names A-B::bla] {
     puts "A-B::bla($n) = $ ???? A-B::bla($n) ????? "
 # following works but is quite awkward
 % foreach n [array names A-B::bla] {
     puts "A-B::bla($n) = [lindex [array get A-B::bla $n] 1]"

What to put instead of question marks to access A-B::bla with varying indices ? (As seen on tcl 8.3.5) - RS: Feature - the $ parser stops on the first char out of [A-Za-z0-9_], as documented in man Tcl. $x is a shorthand for [set x], which doesn't have this restriction. So just use:
     puts "A-B::bla($n) = [set A-B::bla($n)]"

MSW Thx for the quick reply (another case of tomatoes on eyes obviously :)

I would like to draw a 500 x 500 canvas pixel by pixel. I have looked through the do's and dont's of images and realize this is very slow doing it pixel by pixel. Should I draw it row by row or should I draw the whole image at once?

Also let's say I set up an image for each row, how would I be able to reference that image in another loop?

MSW (2004-03-07) Reformatted some. For the first question, test some and see what fits you ? For the second question: store the return value of <canvas> create. It's returning an item id, which is unique in the canvas and can be used to adress items on the canvas unambiguously.
 canvas .c -width 500 -height 500
 pack .c

 for {set i 1} {$i <= 500} {incr i} {
   # create an image for each row
   # instead of ... set img$i [image create photo]
   image create photo c_img_$i
   # instead of ... .c create image 0 $i -image $img$i
   set img$i [.c create image 0 $i -image c_img_$i]

 for {set i 1} {$i <= 500} {incr i} {
    for {set j 1} {$j <= 500} {incr j} {

      # if some test color blue
      lappend temp blue
      # if some test color black
      lappend temp black
  lappend out $temp
  $img$i put $out
  set temp ""
  set out ""

I know the above code will not work. The above code should have an image setup for each row and color it according. I think this is the best way to make the code fast as setting up the image takes the most work. Thanks so much for the help.

MSW I don't understand what you try to achieve by drawing into a 500 x 500 canvas by using 500 1x1 pixel images. Use one image of size 500x500 and paint into it by using
 $img put $out -to x1 y1 x1+1 y1+1 ;# mind the -to args

With -to you can adress each single pixel, and when it comes to storing or drawing the thing it'll be much faster than a canvas loaded with tons of single pixels (at least should be :)
 pack [canvas .c]
 image create photo c_data -width 500 -height 500
 for {set i 0} {$i < 500} {incr i} {
   for {set j 0} {$j < 500} {incr j} {
     if {[set rem [expr {($i+$j)%3}]] == 0} then {
       set color green
     } elseif { $rem == 1 } then {
       set color blue
     } else {
       set color white
     c_data put $color -to $i $j [expr {$i+1}] [expr {$j+1}]
   puts -nonewline "."
   flush stdout
 .c create image 0 0 -image c_data

Hope that helps some although I'm kind of confused what it is you want to achieve.

(2004-03-01) How can we achieve Unix equivalent of rcp (Remote copy) and remsh (remote shell command) using Tcl? Do we have to use sockets and clients ot achieve the above commands between two computers or is there any other way? Thank you . -PK. USA

MSW, 2004-03-02: I'm not aware of such functionality builtin in tcl (except maybe via send -- but this requires tk apps to run, and imo isn't a very favorable way to do communication across external networks), i.e. write a little server. To get an idea of how easy that is, I'm sure there are tons of examples on the wiki, e.g. Einfach Tcl has some at the lower end (comments are in german, code really is self-documenting :).

(2004-02-25) Wondering: how is namespace current convenient to programmers ? Consider you want to return a fully qualified variable, no matter in which namespace you are.
 return "[namespace current]::variable"

doesn't work for the global namespace;
 return "[namespace current]variable"

only works for the global namespace. If the variable doesn't exist yet, namespace which won't help either. So someone mind explaining to me why exactly this is not inconvenient to programmers ? Seems I got tomatoes on my eyes.

So the question is :
 namespace eval bla { variable v }
 # now how do I give a FQN of v (::bla::v here) as -textvariable ?
 # here [namespace which -variable v] would work.
 # but ...
 namespace eval bla { widget .bla -variable [namespace what-exactly var] }
 # .bla should set ::bla::var

RS How does namespace current::var not work for the global namespace? Two or more colons count as namespace separator, so this works for me:
 % parray [namespace current]::env
 ::::env(ALLUSERSPROFILE)        = C:\Documents and Settings\All Users

MSW Didn't know that. It's dead ugly [19], but will work, so I'll settle for it.

Anyone have a Tcl function that, given a file containing newline terminated, returns a random line from the file?

PT - This is one way.
 proc randline {filename} {
    if { [catch {file size $filename} size] }  {
        puts stderr "$size"
        return ""

    if { [catch {open $filename "r"} f] }  {
        puts stderr "$f"
        return ""

    ste offset [expr {int(rand() * $size)}]
    seek $f $offset
    set r [gets $f]
    if { $offset != 0 } {
        set r [gets $f]         ;# toss away the potentially partial line
    close $f
    if { [string length $r ] == 0 } {
        set r [randline $filename]
    return $r

Should do something about end-of-file. Also this won't ever return the first line.

What other error conditions does the above code need to handle?

RS would, if the file fits into memory, just compose these two general utilites:
 proc readlines filename {
    set fp [open $filename]
    split [read $fp][close $fp] \n
 proc lpick list {lindex $list [expr {int(rand()*[llength $list])}]}

So, if you want to display a random "fortune":
 puts [lpick [readlines myFortunes]]

i need to access a tcl procedure from a c function. the tcl procedure is written in mod_dtcl(server parsed Tcl, running under Apache). to access tcl procedure i am firstly creating an interpreter using Tcl_CreateInterp() and then calling Tcl_Eval to evaluate a command . But it as giving invalid reference to Tcl_CreateInterp() & Tcl_Eval. can you give me a example how to access the tcl function.

thanks neo

I have curious problem with tdom while usint selectNodes with xpath. I suppose this problem occurs due to the xmlns in the xml file. I have included both codes. If I remove the xmlns from the xml file the tcl code will return the desired node, but I need the xmlns. Any suggestions?

there is a yahoo group for tdom - http://groups.yahoo.com/group/tdom/ - might get a better answer there

The xml File:
 <?xml version="1.0"?>
 <User xmlns="http://hello.world.com/users">

The TCL Code:
 package require tdom;

 # Read the xml file                                     #
 set fd [open que.xml r];
 set xmlcontent [read $fd];
 close $fd;

 # Create xml parser                                     #
 set xmldom [dom parse $xmlcontent];

 # Get the root node                                     #
 set rootnode [$xmldom documentElement];
 set mynodes [$rootnode selectNodes {/User/Lname}];
 puts [$mynodes asXML];

moved below the line by FW

(7/1/4) bash programs from tclsh

I have a bash script /tapestry/tools/delta/delta.

I can run it from an interactive tclsh without problems. But the following script does not work. Why?
   # \
   exec tclsh "$0" "$@"

I get the error:
    invalid command name "/tapestry/tools/delta/delta"
    while executing "/tapestry/tools/delta/delta"
    (file "./ttest" line 5)

(I can't use exec because the the bash script objects to being run in a pipe)

FW: The interpreter in interactive mode passes unknown commands to the OS, so you can run commands and use the language much like a normal shell. When you run a script from a file it assumes the normal behavior, which is to treat all commands as standard procedure calls. So the question is, is there a way to run an app without making a child process, short of interactive mode? On that one I yield.

RB 01/09/04 - Have you considered "spawn <cmd>" using Expect? "package require Expect"

SZ bgerror didn't invoked in child threads (Tcl 8.4, Windows).

I needed a log of errors in threads reported back into main thread. The following script illustrates this:
 package require Thread

 set th [thread::create]

 proc send {script} {global th; thread::send $th $script}
 proc asend {script} {global th; thread::send -async $th $script}
 send [list set owner [thread::id]]
 puts "owner [thread::id]"
 send {
        proc bgerror {msg} {
                global owner
                puts "bgerror 'puts '$msg'' into $owner"
                after idle [list thread::send -async $owner [list puts "bgerror: $msg"]]
 # separate outputs by time.
 after 1000 asend asdasdasd
 after 2000 {asend {bgerror aaaaaa}}
 vwait forever
 # press CtrlC to exit

(after idle added in the last hope to make it work...)

I expect that I will get something along the lines of
 bgerror 'puts 'Invalid command name "asdasdasd"'' into 12345
 bgerror: Invalid command name "asdasdasd"
 bgerror 'puts 'aaaaaa'' into 12345
 bgerror: aaaaaa

if bgerror invoked correctly.

Instead I get two different results - in tclsh I get report "Error from thread 54321\nInvalid command name "asdasdasd"..." and result from direct call of bgerror. In wish I get only result of direct call of bgerror.

Quick glance at Tcl sources of Tcl 8.4.4 and Thread 2.5 tells me that they try to call bgerror.

Also, I use ActiveTcl as a main distribution and had recompiled tcl and tk for thread support.

17/11/2003 I can say
 set a [lrange $v $n end]

but I have to say
 set a [eval concat $args]

why? What is the rule here?

schlenk: You don't have to say it like this, there are other ways to do it (without eval). Basically you want to flatten a list, remove one level of list nesting. concat operates on multiple arguments, while lrange operates on a list. eval flattens the list into multiple arguments and concat is happy. For most cases (- evil eval sideeffects) this does the same:
 set a [join $args]

or use tcllib and the struct::list module.
 package require struct 1.4
 set a [::struct::list flatten $args]

CT - Oh one other very important question... is here How to get tcl to run only one instance of a script/application?

Hi, I have a question about the canvas postscript method, or rather about the postscript it produces. I tried several examples to export a canvas to postscript, including e.g. the first example on http://wiki.tcl.tk/8483 about different scalings of text and graphics, but also other stuff. If I load the resulting file into ghostview I only get a blank page. Also other programs (CorelDraw, Adobe PhotoShop) were not able to show/print the postscript. I am using Tcl/Tk 8.4 as downloaded from ActiveState on a Windows system. There is probably something very dumb, that I do wrong. Any ideas anyone ?

Thanks, Daniel


I'm running a GUI to test some hardware. The GUI takes input from a touchscreen.Several buttons on the GUI control the action. All tests work fine, but there was a problem during an extreme temperature test. I think this has exposed a weakness in the button.tcl script.

The GUI contains a spinwheel, and 2 separate buttons that can also control the wheel.

This is the button code:
 button $a.prev -text "Prev" -command "$a.spin invoke buttondown"

This is the error message that pops up:
 expected boolean value but got ""
 expected boolean value but got ""
 while executing
 7        "if {[info exists Priv($w,relief)]} {
 8            if {[info exists Priv($w,prelief)] && \
                    $Priv($w,prelief) eq [$w cget -relief]} {
 9                $w configure -relief $Priv($w,relief)
 10            }
 11           unset -nocomplain Priv($w,relief) Priv($w,prelief)
 12        }
 (procedure "tk::ButtonUp" line 8)

This code stems from button.tcl (tcl 8.4).

My theory is that the error is caused by the $Priv($w,prelief) expression, which is not defined (see beow for explanation), and the fact that the expression is part of an if{} statement, where all expressions are evaluated before decision making. I know tcl is supposed to use a lazy &&, but only if the expression is enclosed in {} and the {} that is used here seems to belong to the if{} syntax.

My questions:

  1. Does this make sense? Would the reported error be caused by something like this?
  2. Since button.tcl is part of the tcl/tk package, who is going to fix this?

Explanation for prelief not defined - I think our low temperature test on the touch screen caused the button down not to be sent out. The button down routine in button.tcl is the place where the prelief is actually set.

Peter Newman 26 March 2004: (1) Shouldn't there be parentheses around the "$Priv($w,prelief) eq [$w cget -relief]" that follows the "&&" ? I'm not sure how Tcl evaluates expressions - but it seems to me it's going:-
 if { ( [info exists Priv($w,prelief)] && $Priv($w,prelief) ) eq [$w cget -relief] } {

 if { [info exists Priv($w,prelief)] && ( $Priv($w,prelief) eq [$w cget -relief] ) } {

as I assume the programmer intended (and should have coded).

(2) I've never used arrays, but the "info exists Priv($w,relief)" looks a bit suspect to me. "info exists Priv" I understand. The programmer wants to know if the thing named Priv exists. And "info exists $Priv($w,relief)" means the programmer wants to know if the name specified by (the value) $Priv($w,relief) exists. But "info exists Priv($w,relief)" ???

MG April 17th 2004 - [info exists Priv($w,relief)] checks to see if an element named '$w,relief' exists in the array 'Priv', so that's correct. As for the parenthesis... I believe Tcl should eval it fine without them. I've never seen that error, and can't think why it might happen, unless some code you've run as edited the $::tk::Priv array? That is, generally speaking, a Very Bad Thing to do, I believe.

2004/10/20 sheila

How will I invoke package require if the pkgIndex file is byte-compiled? Will I need to alter tclPkgUnknown to also check for pkgIndex.tbc files? Should I call package unknown to get the handler name rather than assuming that it is handled by tclPkgUnknown?

For example, package.tcl has in one spot
 foreach file [glob -directory $dir -join -nocomplain \

  • pkgIndex.tcl] {

Which I can change to include pkgIndex.tbc, as below
 (test) 89 % ls
 pkgIndex.tbc   pkgIndex.tcl
 (test) 90 % glob -directory [pwd] -nocomplain pkgIndex.tcl pkgIndex.tbc
 C:/home/test/pkgIndex.tcl C:/home/test/pkgIndex.tbc

I could go through tclPkgUnknown to scrub for places where pkgIndex.tcl is assumed.

2007/05/05 Duoas I don't know of sheila ever found a solution but here is one: Don't byte-compile the pkgIndex.tcl file. If you strip out the boiler-plate commentary at the top the file is usually less than 128 bytes. That, and it is only ever evaluated once when the Tcl interpreter starts-up, so there is no qualitative performance loss in not having it compiled.

Oct 9th 2004 - MG Does anyone know of a way to stop the console coming up, when you wrap a Tcl application with Freewrap on MS Windows? I'm using freeWrap 5.6.1. Right now, I've just been adding console hide or after idle {console hide} into the end of the script (I can't recall which I settled on, in the end), but it's kind've a pain to have to that with every script you want to wrap. Is there a command-line option to freeWrap, or something you can change with a resource-hacking program, to stop it doing it? Thanks for your help

2007/05/05 Duoas Always start your script with
 catch {console hide}

This is portable (it will work on non-Windows systems). Also, make sure it is at the top of your startup script, or one of the first commands in your main script/proc/whatever. Hope this helps.

!HElp wanted- I am trying to run FindWords.tcl on Text Pad 4.4.0 and it simply does not react. I am doing something wrong. What? Please contact me at [email protected] Thanks. JGL

PS: Sorry, I am having trouble mailing ULIS. I have put details of my Problem on [20]

JGL what is this

hi.. i just want to ask, how do i find my windows and office license in my computer using a command or anything you can suggest in my windows 98?

thanks.. SEYEROJ

HJG How about "MS Systeminfo" ?

April 30 2006 from GY Hello, I would like to ask you all a question about Expect. I want to use expect to change current directory as I can do it in Linux using "cd /home" for instance. However, the command: spawn cd /home

does not work. Neither does "exec cd /home". I really want to know how I can use expect to execute the "cd" command.

Thanks a lot!


Lars H: This is answered on the cd page.

See the individual pages for a historical look at questions which have not yet been distributed throughout the pages of the wiki

Please post new questions on the latest version of Ask, and it shall be given.