Ask, and it shall be given # 9

How to post on this page

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

This page runs the risk of being deleted and corrupted. Please be very careful when editing it. If you inadvertently delete it, immediately revert your edit using the History link on the left side of this page. Do NOT attempt to restore it by copying'n'pasting the text from a previous revision, or all page formatting will be lost!

Please put new questions at the TOP of the page, below this section, so that as the page grows longer, new questions are seen first.

Also please put a section header on top of every question and put two stars in the beginning of the title and two stars in the end. This will make your question's section easily editable.

Once you have received a satisfactory answer, please cut your question and answer directly on an appropriate page of the wiki. If you cannot find an existing page, create a new one.

You might also simply want to put a hyperlink leading to a page of the wiki where your question is included like Didier has done on February 5th 2011. This will save you the trouble of cutting your question to an existing page afterwards.

Please do not put any further questions on this page Use the next one instead. Thanks!


interface for using the statical programm R

hello every one i have GUI builder for tcl/tk and i want to create an interface for using the statical programm R, and i don't know where to put my code

thank's for your help

tk tests in the tk8.5.11

I am desperately trying to figure out how to run the tk tests in the tk8.5.11 tests directory. Building tcl was trivial and it tests beautifully and then installed neatly into /usr/local. All is well there. The build of tk8.5.11 took a bit more time in order to ensure all the X11 headers were available. Once that was done a configure was easy and build seemed smooth. No worries.

However running the tk tests is a total fail. There is no documentation on this issue anywhere I can find. I tried to run tcltest all.tcl in the tk8.5.11/tests directory and saw this foo :

$ ../../tcl8.5.11/unix/tcltest all.tcl can't find package Tk

    while executing

"package require Tk "

    (file "all.tcl" line 14)

It seems as if one has to install Tk first before testing it ? That will never, ever, happen.

So what is the magic incantation to get the tk tests to run ?

Raspberry Pis

beware Has anybody had a look at the pending Raspberry Pis? ( Is there already an existing ARM compiled TCL/TK build that will work? What are the chances that the SD cards they'll be selling will already have a working TCL build?

MG There are Tclkits on the Google Code site compiled for ARM, though whether they'll work on the Pi I'm not sure. (I hope so, though.)

How to take full screenshot in Windows 7?

andy - 2012-01-04 10:41:56

How to take full screenshot in Windows 7? Not widget snapshot. I cannot use BLT package in ActiveState Tcl 8.5.10. Is there other way to capture screen and save to an image? Thanks in advance.

arjen You mean programmatically? I think that is quite possible using the Img package.

I thought it would be, but this little script does not capture the image:

package require Img
set img [image create photo -file "earth.gif"]

::ttk::frame .frame
::ttk::label .frame.label -image $img
pack .frame.label
pack .frame

tkwait visibility .frame.label
after 2000 {
    set img [image create photo -data . -format window]
    $img write earth.jpg -format jpeg

(It does show the contents of the label if I replace "." by ".frame.label", but that is not what you want)

andy Yes, that's not what I want. I want capture full screen, not a Tk window.

Is it possible to divert command resolution in the global namespace?

see namespace path for details on this question.

Retrieving a file name from a file descriptor.

IanMac Dec 6 2011 --

I have a common routine which inspects data in a file, for consistency. It does this by doing

proc inspectfile {fileid} {
# other stuff
seek $fileid $dateRecordLoc start
set dateRecord [read $fileid 2]
# more stuff doing the check and setting a result

What I wish to do is output the actual the filename when I discover that $dataRecord is incorrect so without passing in both the filename and the filePointer as parameters to the proc, and all the higher level procs all down the stack, how to I get the filename from the filePointer - $fileid? It must be simple but for the life of me I can't spot how to do it.

AMG: I am not aware of any way to get the filename back from the channel name. I don't believe it's tracked, especially since many channel types aren't associated with an on-disk file. The architecture of your system doesn't permit passing the filename along with the channel name, so I suggest maintaining a global array or dict mapping from channel name to filename. Whenever you open a file, add an entry to the map. Whenever you close, remove the entry. Whenever there's an error, look up the filename in the map.

Continuously Updating Display

Industrialist Dec 5 2011 --

I have been trying to learn Tcl off/on now for two or three days. My goal is to use Tcl to continuously monitor a USB port and use data encoded within the input string to continuously update several graphical images.

For now I have written dummy procedures to simulate reading data from the USB port.

My main script is an infinite 'while' loop that will 'break' after a certain length of time. My script calls several graphical procedures within this loop.

My problem is that the graphics display is not generated until the break occurs within the loop. The final display amounts to the super-positioning of all graphical 'canvas' calls generated while the script was executing.

What do I need to do to allow the user to watch the graphical display continuously update?

My first excursion into Tcl is to create an script that will continuously monitor a USB port and update any of several graphical images generated by 'canvas'.

My script currently contains a procedure that simulates the reading of a data stream from the USB port.

An infinite 'while' loop in the script terminates with a 'break' after a hard-coded time interval.

My problem is that the graphical display does not appear until after the script is halted with a 'break' and the single screen image contains a composite of all images that were sequentially generated on the screen.

I would like the user to be able to watch the display being updated continuously.

Any suggestions as to how I might code this?

AMG: Easiest answer: periodically call [update] to force a display update. However, there are some negative consequences to this design approach. It's better to tie your I/O into the event system, such that it is automatically invoked whenever there's incoming data. See [chan event] for more. Coroutines may also be useful, if you have stateful code which needs to do multiple reads (e.g. read header, read payload, read trailer, repeat), yet the individual reads may block for a long time during which you would like the user interface to update.

Detecting when a client is not reading data from a socket (or pipe) as fast as the server is writing

jbr Any ideas how to do this?

Connection to a C program from Tcl

Gerry W. I like a lot the way I'm able to run a C code from TCL. I do have a problem however albeit a small one. I enter: long opening bracket c:/Data/Cprogram.exe long closing bracket. No problem everything works fine. The problem is this: I simply need the Tcl program to look up the name of a datafile in a location, to take the 5 last digits of the path and to put them next to long opening bracket c:/Data/Cprogram.exe long closing bracket. How do I do all that.

Let me be more specific. The program in C modifies data and the name of the file to modify must be written at the command line next to the C program. Ex:If I go on c:/Data/ and I type Cprogram.exe Data1, the Data1 file will be treated.

Does my putting in bracket correspond to an entry at the prompt?

The realize of Gaussian stochastic process through TCL/TK

Dear all, I want to produce a vector Gaussian stochastic process h(t) with statistical properties <hi(t)>=0 and <hi(t)hj(s)>=Dδijδ(t-s), where i and j are the Cartesian indices. D is constant number,δij and δ(t-s) are Kronecker δ and Dirac δ. How could I write it with TCL/TK? Much thanks.

Native MDI extension for Windows

MG Anyone know of a native MDI extension for Windows anywhere? I'm sure I saw one once, but can't find any mention of it now. Thanks for your help.

Precompiled threaded 8.5 tclkit for OSX

Ro 2011-09-16 Anyone have a precompiled threaded 8.5 tclkit for OSX? I use Pat Thoyts's builds for Linux and Windows and they work great (8.5.9 tclkit threaded), but Roy Keene's latest isn't threaded on OSX. Thanks!

Supposedly the basekit provided by ActiveState is multithreaded on OS X but is it free to use for any use?

YS Look at result of this script:

canvas .c -bg white
grid .c
set x1 20
set x2 22
set y2 105
for {set f 0} {$f<50} {incr f} {
    set y1 [expr {$y2-0.05*$f}]
    .c create rectangle $x1 $y1 $x2 $y2 -fill black
    incr x1 2
    incr x2 2

On Windows XP I see that at left side of figure bottom margin is one pixel lower than at right side. But it shouldn't happen as y2 is the same (105) for all rectangles. What do you think?

Using TCOM to make DNS changes via WMI

For more detail about this question see

Resolved, follow link to see examples.

Tclkit does not run on my PC

wdb Aug 26 2011 -- yesterday bought and unpacked my PC, installed SuSE Linux, downloaded Tclkit from equi4.

wolf@linux-t1xi:~/Downloads> ls -l
insgesamt 1440
-rwxr-xr-x 1 wolf users 1472785 26. Aug 06:16 tclkit-linux-x86-8.5.1
wolf@linux-t1xi:~/Downloads> ./tclkit-linux-x86-8.5.1 
bash: ./tclkit-linux-x86-8.5.1: Kann die Datei nicht ausführen.

Translation: could not execute program file. No explanation. Any suggestions what went wrong?

I just tried it. File had a slightly different name, but problem was it had been doubly gzipped. I had to gunzip twice, then it worked.


wdb Many thanks! My life has as sense again ;-)

tcom package in 64-bit windows or 64-bit alternative

jrs Aug 19 2011 - I'm trying to port a project that relies heavily on tcom for office automation. Part of the requirements for this port is that it runs on 64-bit. Therefore, I'm trying to compile the tcom project in 64-bit.

Unfortunately it does not compile, due to some in-line assembly code that is used. Here is a snippet of the culprit C code:

static __declspec(naked) void
delegate (void)
    __asm {
        push ebp                // set up simple stack frame
        mov  ebp, esp

        sub  esp, 8                // set up local variables
                                // localVar(hrFromInvoke)
                                // localVar(pArgEnd)
                                // ebp
                                // funcIndex
                                // retAddr
                                // this
                                // args

        call invokeComObjectFunction

        // The following code adjusts the stack and returns to the caller.
        // This involves copying the return address and the HRESULT
        // to the bottom of the stack frame, adjusting the stack
        // pointer, and returning to the caller.
        push esi
        mov  esi, [ebp-4]       // esi = address after last argument

        sub  esi, 4                // esi points to bottom arg on stack
        mov  eax, [ebp+8]        // copy retaddr down
        mov  [esi], eax

        sub  esi, 4
        mov  eax, [ebp-8]        // copy hrFromInvoke down
        mov  [esi], eax
        mov  eax, esi                // reset stack and return to caller
        pop  esi
        mov  ebp, [ebp]
        mov  esp, eax
        pop  eax

So my options seem to be to either figure out how to get this code working on 64-bit or find an alternative to tcom. I've already investigated trying to get this code working in 64-bit and it seems it could be possible using MASM, but unfortunately my attempts at this method were without success. The only alternative I found was package optcl. I downloaded it but I'm still investigating if it will be a suitable replacement.

Any suggestions would be greatly appreciated.

Thanks, Josh

Answer: So I ended up emailing the author of tcom and he suggested I download the latest beta release of tcom which has an included define that can disable this "vtable" if it isn't needed. Luckily the project I'm upgrading does not use this vtable, so I was able to simply remove the preprocessor definition from the project settings. It now compiles fine as 64-bit.

mhofmann (2011-09-19) Putting the assembly stuff into a freestanding MASM64-Module was exactly the thing I've done a while ago. And it did work! Due to different calling conventions, ComObject.cpp and ComObject.h also had to be adapted.

If you are or anybody is interested, you can find the source files at

In the Download folder there, I provide

  • a archive, containing the Tcom 64 library/tcom files (dll's etc) and
  • a simple installer for a 64 bit Tcl8.6 distro, including the tcom stuff.

Hope that helps,


Show activity in a ttk::notebook tab

MG Aug 19 2011 - I'm hoping to use a ttk::notebook for an app, but I need some way to show when there's activity in a tab. The only option I can see so far is using an -image and changing it when there's activity, but that's not going to be very obvious. Ideally, I'd like to flash the tab or something like that, but have no idea if that's possible. I've looked through the ttk theme files and can't see anything helpful, or in the docs. Can anyone suggest anything? Thanks for your help.

Suggestion Box?

gold 5aug2011: Does this TCL wiki have an obvious suggesion box? thanks.

Problems with Set total

gold 11jul2011, problems with set total ... sexagesimal conversion is supposed to be 30/60 or 0.5. gold17jul2011. Fixed problem, closed out.

Tcl syntax

I was just over at RosettaCode. They've marked Tcl as not capable of inverted syntax . I'm pretty sure they're wrong ... BMA

RLE (2011-06-27) While they will likely say that this fails for some reason they make up after the fact, but it would seem that do...until in Tcl would qualify for their definition of inverted syntax.

DCD (2011-07-11) I pasted do.tcl into the RosettaCode page - and added an ugly hack using unknown that should qualify as truly inverted.

Memory pre-allocation

DVB (2011-06-19) Is there a way to pre-allocate a defined amount of memory before the interp use it? It would be like a guarantee that it will be worth to start processing.

Thanks in advance.

gold 28jun2011, Found some references on memory.

If you are on windows, the twapi extension will obtain get_memory_info.

 console show
 package require twapi
 set maximum_memory [expr {1.*1E9}]
 set memory_physical [lindex [::twapi::get_memory_info -totalphysical] 1]
 if {$memory_physical  < $maximum_memory} { puts " memory $memory_physical  "; 
 error " out of memory $memory_physical "  }

Recursive Lists

I Want a Tcl script which does the foolowing:

procedure to generate a single list, by reading the user input from command line.

e.g. User Inputs: {1 5 23 {abc 23 {564 abc}}} 1 5 {56 rrf 45 {127 458}}
So how to output index of each element...

That is, if 23 should output index : 20
abc : 300
Please help

Thanks, Leo

gold 11jun2011,Recommend proc lflatten { list } of cyrilroux from list. Nested list is most intractable of all inputs, but the script below takes your multiple nests and throws out a 1 element1 2 element2 ... N elementN output for loading into keyed lists and arrays. Refs.keyed list,dict,list stripping,args,I love foreach. Proc keyget from Additional list functions is also possible as example below: keyget {$outty} 4. Console input is king { nested list }. On many unix systems, input args will work better as example: proc king {args} {...source Recursive list searching.tcl; lrsearch $args abc;set aa lflatten $args..}.Search "args*" on wiki search engine for more examples.

 # written on etcl console and windows XP
   console show
    global lister5 bush
    set jack [list {1 5 23 {abc 23 {564 abc}}} 1 5 {56 rrf 45 {127 458}}]
    puts "  $jack    "
    set outty [list]
            proc lflatten { list } {
            regsub -all {^\{| \{|\{\{+|\}$|\} |\}\}+} $list { } flatten
            return $flatten
            } ;# cyrilroux 
                    proc keyget {list key} {
                    foreach {lkey value} $list {
                    if [string equal $lkey $key] {return $value}
                    } ;# RS
            proc advisorx {aa } {
                 puts "input has form of king { list }  "
                 puts "advisor: new list???? "
            proc king { aa } {
                global lister5 bush 
                set counterx 1
                set outty [list]
                set aa [ lflatten $aa ]
                foreach item $aa {
                    lappend outty $counterx $item
                    incr counterx
                puts " decision was  , total counters was $counterx   "
                puts " [lflatten $aa ]"
                puts "keyed   $outty "
                puts " keyget [keyget $outty 4]"
                advisorx {aa }
            puts "input has form of king { list }  "

menu radiobutton support with menubutton and ttk::menubutton on Mac OS X

Aud (2011-05-15) It is just me, or do menu radiobutton items act just like plain old command items (no tick displayed when selected via -variable), when the menu is assigned to either the standard Tk or the Ttk menubutton widgets under OS X? Running the same code under Linux gives me the expected behaviour (a radiobutton item shown as selected when menubutton clicked).

Menus assigned to an OS X toplevel don't have this issue, and as far as I can tell from other OS X apps, Cocoa probably supports natively. Then again, isn't Tk 8.5 still using Carbon? Maybe that's got something to do with this?

Example for clarity:

package require Tk
package require Ttk

ttk::menubutton .test -menu .menu -textvariable menu_value
pack .test

set menu_value 1
menu .menu
.menu add radiobutton -label One -variable menu_value -value 1
.menu add radiobutton -label Two -variable menu_value -value 2

How does "fieldbackground" work at ttk::treeview?

enel (2011-05-09)

A small test:

    package require Tk
    package require tile 0.7.8
    frame .f -background red -border 10
    ttk::style configure Treeview -fieldbackground green
    ttk::style configure Treeview.Row -background green
    ttk::treeview -columns {name state} heading #0 -text Id heading name -text Name heading state -text State
 insert {} end -text 1 -values {John OH} insert {} end -text 2 -values {James WV} configure -style Treeview
    pack .f -fill both -expand true

How can I color the empty part of the treeview? I used manual ttk::style examples.

RLE (2011-05-09) Unless something has changed since that page was written (it was for 8.5.8, what version are you using?), your test should have worked and should have colored the empty portion green. What did you see happening instead?

enel (2011-05-09)

- TK_VERSION='8.5'
- tile-

My "result" is.

RLE (2011-05-10) When I paste your unchanged example above into a wish on Linux (also 8.5.8), I get a full green background for the entire treeview area. When I try 8.5.9 under WinXP I get a white background for the entire treeview. It appears that there is some kind of override happening on windows that does not happen on Linux. You might want to try asking your question on comp.lang.tcl in this case.

enel (2011-06-11) Thanks the idea, I did it. I haven't got any answer for a month, so I "close" (give up) this topic.

RLE (2011-06-11) That is too bad. You have either discovered a bug, or you have discovered a manner in which the Win version just works differently. But we don't know which outcome (bug or difference) is correct.

enel (2011-07-02) When a windows-exe generated by tclkit the unconfigurable territory is red colored. My "exe-result" is.

How to run external script from Tk and make it throw output to the console?

gold 2011-05-10, Perhaps, exec, , , , A minimal console, and would be a good place to start.

A session from the Etcl console on a an XP windows.

    2% exec etcl.exe king4.tcl 
    9% exec king4.exe # using freewrap compiled tcl executable
    11% eval exec etcl.exe king4.tcl
    12% set output5 [exec etcl.exe external_script_king4.tcl ]
    15% puts $output5
    17% set tip [ more king4.tcl] #using  more to grab script
    16% eval $tip
    17% console eval $tip # may overwrite console display or functions
     load hello.tcl (text file) as one line, puts "overwrite hello"
    18% source hello.tcl #should see "overwrite hello" on console window
     load pie.tcl (text file) as one line, proc pi {} {expr acos(-1)}
     19% source pie.tcl
     20% set piepie [ pi ]; puts $piepie
         answer: 3.141592653589793

The Combining Fortran and Tcl in one program and Managing Fortran programs are some starter code for calling on external programs and external scripts. Also, the pull down menu on the etcl console has buttons for sourcing and executing TCL code.

Window configuration does not follow the sizegrip while the window manager does

I added a ttk::sizegrip to a window to give the user the possibility resizing the window to his/her needs. Unfortunately, the window contents is not resized when the sizegrip is dragged but the window frame added by the window manager gets the expected size. The same effect occurs if the window is resized by the window manager directly (whether or not a sizegrip is present). What can I do to resize the window contents?

The platform used:

- SunOS 5.10 Generic_144488-08 sun4u sparc SUNW,Sun-Fire-V440 Solaris
- Tcl version 8.5 , Tk version 8.5
- Tcl/Tk compiled from sources by gcc (pre-installed is version 8.4)

A small test program follows (modifying the "sticky" settings has no effect here):

# the next line restarts using wish \
exec wish "$0" "$@"

# Fill window by some stuff:
ttk::frame .top
grid .top -row 0 -column 0 -sticky nswe
grid [ttk::label .top.label -text "Test"] -row 0 -column 0 -sticky w
ttk::button .top.button -text "Close" -command { exit }
grid .top.button -row 0 -column 1 -sticky e
grid [ttk::label .top.status -text "Status"] -row 1 -column 0 -columnspan 2 -sticky we
# Add sizegrip:
grid [ttk::sizegrip .top.grip] -row 1 -column 2 -sticky se

RLE (2011-04-06): Grids by default do not automatically expand when their container expands. You need to tell the grid manager how you want the various rows and columns to expand. Take a look at the "-weight" option to the grid columnconfigure and grid rowconfigure sub-commands.

For your example above, while I don't know exactly how you would want it to expand, if you do:

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

Then your grid layout will expand/contract with changes in the window size (although maybe not expand/contract the way you want).

Multithreaded Image Processing

tml 3/30/2011: I need to load and process quite a lot of big image files, and loading a single image alone will take about 3 seconds, which makes my GUI quite irresponsive. Is it possible to load and process an image in a secondary thread and then transfer that image to my main thread in a similar manner as that's already possible for channels ... maybe by writing some C code for that purpose?

gold 5/16/2011. Found refs. If you can work with thumbnails, a tcl or perl script can use imagemagick to thumbnail every image in a directory or tailor to specific megabyte size.

Especially look at Fast image resizing, which implies you might have to compile the TCL code (possibly Freewrap if speed alone is consideration. Also, has alternative library. PS. One possible alternative would be to preprocess the images of great size with image magick or Pixane and load them as TKphoto onto a script like imagecollection.tcl and source that script on loading the program, as " source imagecollection.tcl". Not sure that one can defeat the entropy of loading files, but the major part of loading would be done before the application screen came up, not during the running of the application.

ABU 18-may-2011 : I think solution should be based on threads (tcl-threads or native threads). We could even get some optimized code as that ones cited, but until image-processing is synchronous (single thread), GUI will behave quite irresponsive. See comp.lang.tcl [L1 ] for a short discussion. Note that we can load an image in a slave thread, but then passing data to the main thread is incredibly slow! The main thread takes more time to get a (very-large) encoded string, than time required for reading and decoding (from jpg to bitmap) a jpg-file ! Tcl-threads cannot exchange data very quickly, since they have no notion of shared-memory (or better,shared-memory (tsv package) is just an emulation achieved by deep-copying 'objects' between threads). Tsv is fine for sharing small data, but it is useless for sharing "images" each taking up several megabytes.

Source vs Double-click to run

Beware 2/3/2011: How can a script know whether it was sourced with 'source' or double-clicked in windows?

tml 3/30/2011: The global argv0 variable contains the name of script supplied by double clicking. If the executable has been started without a script, argv0 contains the name of the executable, which is identical to the result of an 'info nameofexecutable'. In either case, 'info script' will return the name of the script that's currently being executed (i.e., after double clicking, the name of the clicked script). Also, please don't forget that 'info script' will yield the name of a source file only while it's being read in - not if, for example, a procedure provided by that source file is called later (maybe by a button you clicked).

Tracing in Parser Tools

jbr Hi again all - I've continued to play with the very nice Parser Tools packages in the new tcllib (1.13). There seems to be a TRACE facility that would be very useful in finding out what is going on as the data is parsed, but I cannot see how to enable this feature?


AK I am sorry, the TRACE facility is not exposed to user control. You will have to go into the various methods and uncomment the calls to TRACE to activate it.

Accessing Methods of TclOO

Is it possible to access methods of a TclOO object without using self or my? --> Forwarding local namespace proc calls to instance methods in TclOO

I've mostly answered my own question but would like some feedback from those in the know.

Thanks - jbr

DKF: Basically, no (depending on what you mean by ?access? of course). Methods aren't commands; at the C level, they're implemented by a different callback that takes an extra argument relative to commands (the extra value describes the context in which the method was invoked, which typically matters a lot) and doing it that way allowed much of the guts of TclOO to be implemented simply, but it does mean that methods cannot be executed without knowing what object they're being invoked upon. That's in turn handled either through the identity of the public object command (what you normally think of as the ?name? of the object) or the identity of the private object command, which is typically known through which namespace is declaring it.

If you want to forward commands in the object namespace to the object method with the same name, use namespace unknown, perhaps like this (untested!) example that also uses tailcall and my. It needs to be invoked in the relevant namespace; a good time to set it up is in the constructor.

namespace unknown {tailcall my}

regedit on Windows

Beware 18/2/2011 Calling

exec regedit /e temp.txt "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup"

writes a text file (readable in notepad) listing the various key/value pairs.


set fh [open temp.txt]
set data [read $fh]
close $fh
tk_messageBox -message $data

gives me three random characters. Why can't I read the data in the file properly? I'm guessing this is an encoding issue

(about 2 minutes later)

Sorted. fconfiguring to -encoding unicode works...

Writing code for trails

[fs) 2011-02-18 My question is here:

Coding trails for hyperlinks

Exposing TclOO variable names

jbr 2011-02-11

How do I expose the state of TclOO objects for use with Tk and variable traces?

I've been using TclOO for a few months now and have come to like it, but now my application state, which in the past might have been kept in a global array or set of global variables, is inside one of more objects. Does anyone have some good ideas about how to get the value in an object onto a Tk widget? Is is acceptable to add traces to variables in an object's namespace? And more generally "Now that we have objects, How do I tie my application together?"

To date I've written methods to had back the full namespace path to specific value I need to display, but this is tedious.

Thanks - John

DKF: TclOO's instance variables actually have names in the "global naming" hierarchy, and the varname method (defined by oo::object) can report them for you; it's a hidden method by default, so access it with my from inside your methods:

  oo::class create FooBarGrillLabelExample {
      variable x
      constructor {w} {
          label $w -textvariable [my varname x]
      method setLabel {txt} {
          set x $txt

This method also works great for integration with all those places where you need to pass a variable name into Tcl, notably trace and vwait.

jbr - Yes - This is the part that I find tedious. Everything needs to be put in some kind of wrapper. I've solved this for my case by exporting varname.

Accessing the help pages without changing the default directory

Didier (2011-02-09) My question is here: Accessing the help pages without changing the default directory

List of categories on this wiki

Didier(2011-02-09) My new question is here: Where to find the list of categories on this wiki?

DKF: The place to go is the category of categories and click on the link at the very top of the page to take yourself to the list of pages that reference the metacategory. Or go directly there , though that's less mnemonic IMO.

Escapes for individual new lines in a CSV file

bewareQuick silly question (I think)... on windows, "\n" matches both types of newline. What are the escapes for the individual ones? I have a CSV file with embedded soft newlines that I want to replace.

GJS (2011-02-09) I believe you are looking for carriage return "\r" and line feed "\f"

Duoas (2011-02-21) The "\f" escape sequence is for Form Feed, which is not the same as New Line.

You'll want to fconfigure your stream to binary mode and look for "\r\n", which is CR-LF. The non-binary mode is for use on non-POSIX systems to turn the single "\n" (LF) character into the platform-appropriate character sequence. On Windows that's an "\r\n".

Running two copies of the same program simultaneously

Didier(Saturday February 5th 2011) See: Opening a window that duplicates the program we're on

Sizing windows

Didier(Saturday February 5th 2011) I have another question here: Questions related to windows. Thanks again!

Help with notebooks

hshang - 2011-03-17 12:04:48: ttk:notebook help

dmk - 2012-01-15 17:05:38

Need assistance with Linux System command call to AT (the scheduler) via TCL


I'm wrting a app which schedules jobs using the LINUX/UNIX "at" scheduling command

I schedule a script to run at now + (user selected time)

example: echo '/usr/local/scripts/myScript.ksh $path_argument' | /usr/bin at now + 3 days

Note: you must run the command the way show above if you have arguments otherwise there is a more straight forward way as follows: /usr/bin at -f '/usr/local/scripts/myScript.ksh' now + 3 days

I checked permissions which are 755 for myScript.ksh

What I do is assemble the entire command string in a single variable name $commandEXE and the run it as follows

{exec $commandEXE} // I wrap a catch around it too.

No AT job gets scheduled. When I echo $commandEXE and run it verbatim on the Linux command line it schedules the job!

When the exec commend is called in the TCL no errors are generated either in the command window.

I've tried many things including using back ticks and without single ticks (as shown above).

Seems to me when the command string is passed to the environment it doesnt get executed.

RLE (2012-01-15)

  • What I do is assemble the entire command string in a single variable name $commandEXE and the run it as follows

This is the source of your problem. The exec command expects multiple arguments, each being an individual argument to the underlying system. You are passing it a single argument, which it interprets as the program to run. A little experimentation in the tcl shell would show you the trouble:

$ ls -l
total 0
-rw-r--r-- 1 noone noone 0 2012-01-15 13:03 A-File

$ tclsh 
% exec "ls -l A-File"
couldn't execute "ls -l A-File": no such file or directory

% exec ls -l A-File
-rw-r--r-- 1 noone noone 0 2012-01-15 13:03 A-File

In the first exec above, with all of "ls -l A-File" in quotes, exec is trying to run a program named "ls -l A-File". In the second exec, it is trying to run a program named "ls".

Had you checked for an error return from catch, and then examined the returned error message, you probably would have found the could not execute message.

What you need to do is either change your code so you run the call to exec directly with the proper args, or you need to build up your command line as a list using lappend, and then insert the list elements onto the exec call like so: "exec {*}$commandEXE" (this assumes you are using Tcl 8.5).

dmk - 2012-01-15 20:48:14

RLE Thank you for responding!

I understnad what you are demonstrating. Yes I'm using 8.5. And I have used [lappend] before but isnt that the same as a string? Well sort of a list concatinated. Are the newline of linefeed in a list allow for the concatinated to be interpreted separately?

When I merge string components I use the following technique:

set echoCmd "echo "
set scriptCMD "/usr/local/scripts/myScript.ksh | "
set part1 [set a $echoCmd][set b $scriptCmd]

set atCMD "/usr/bin/at now + "
$units (set by user from GUI)
$value (set by user from GUI)
set part2 [set a $atCmd][set b $value][set c " "][set d $value]

then finally...

set commandEXE [set a $part1][set b $part2]

So commandEXE yields

echo /usr/local/scripts/myScript.ksh | /usr/bin/at now + 3 days

Ok that said I am not familiar with the syntax {*}$commandEXE what does this syntax mean and can you cite a simple example.

When i use laapend there are 8 tokens -- so should I lappend 8 separate tokens or have three tokens:

  • The echo command
  • The Pipe (|)
  • The AT invocation

AMG: There are a few examples on the {*} page. Start at the bottom, there are two very simple ones. Basically {*} means to chop up the rest of the word (after substitution) into separate arguments to your command, rather than leaving it all as a single argument.

RLE (2012-01-15):

  • And I have used [lappend] before but isnt that the same as a string?

No, lappend creates a list not a string. A list has a string representation, but internally it is not the same thing as a string. Rather it has more in common with an array from other programming languages.

I don't understand your question regarding new lines of line feeds, so I can't answer that one.

I don't follow all your [set a ...] [set b ...] uses. Why are variables a, b, c, etc. being set when they never seem to be used.

One way to accomplish what it appears you really want would be to do:

lappend commandEXE echo /usr/local/scripts/myScript.ksh | /usr/bin/at now + $value $units

(I am assuming that $value is the number of things, and $units is the size (seconds, minutes, hours)).

Then "exec {*}$commandEXE" would work.

But, assuming you have properly filtered $value and $units for injection attacks, you could also just directly use exec like so:

exec echo /usr/local/scripts/myScript.ksh | /usr/bin/at now + $value $units

And it would also just work properly.

AMG: Regarding list versus string... In Tcl, everything is a string, meaning that everything can be represented as a string, e.g. you can print it. So take the case of numbers. Every number has a string representation, but that doesn't mean every possible string is a number. "5" is the fifth counting number, but "boron" isn't a number, though it certainly is a string. The same goes for lists. "a b c" is a list, and so is "boron" (a single element list) or "" (empty list). But "abc {def" isn't a list, since it lacks a closing brace for its second element. Yet "abc {def" is a valid string.