0% found this document useful (0 votes)
12 views26 pages

TCLTK

Uploaded by

Ruboto Boto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views26 pages

TCLTK

Uploaded by

Ruboto Boto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Tcl/Tk Reference Guide

Tcl/Tk Reference Guide Conventions


for Tcl 8.0 / Tk 8.0 fixed denotes literal text.
Tk/Tcl program designed and created by this means variable text, i.e. things you must fill in.
John Ousterhout <[email protected]> word is a keyword, i.e. a word with a special meaning.
Reference guide contents written by [. . . ] denotes an optional part.
Paul Raines <[email protected]>
Jeff Tranter <[email protected]> 1. Basic Tcl Language Features
Reference guide format designed and created by
Johan Vromans <[email protected]> ; or newline statement separator


statement continuation if last character in line
Contents # comments out rest of line (if first non whitespace character)


var simple variable
1. Basic Tcl Language Features 2 var(index) associative array variable
2. Tcl Special Variables 2 var(i,j) multi-dimensional array variable
3. Operators and Expressions 3 $var variable substitution (also ${var}xyz)
4. Regular Expressions 3 [expr 1+2] command substitution
5. Pattern Globbing 4


char backslash substitution (see below)
6. Control Statements 4 "hello $a" quoting with substitution
7. File Information 5 {hello $a} quoting with no substitution (deferred substitution)
8. Tcl Interpreter Information 6
9. Lists 7 The only data type in Tcl is a string. However, some commands will interpret
10. Arrays 8 arguments as numbers/boolean in which case the formats are
11. Strings and Binary Data 8 Integer: 123 0xff (hex) 0377 (octal).
Floating Point: 2.1 3. 6e4 7.91e+16
12. System Interaction 10
Boolean: true false 0 1 yes no
13. File Input/Output 11
14. Multiple Interpreters 13 Tcl makes the following backslash substitutions:
15. Packages 14


a audible alert (0x7) space space


16. Namespaces 14 b backspace (0x8) newline space


17. Other Tcl Commands 15 f form feed (0xC) ddd octal value (d=0-7)


18. General Tk Widget Information 18 n newline (0xA) xdd hexadecimal value (d=0-9, a-f)


r carriage return (0xD) c replace ‘ c’ with ‘c’
19. Tk Special Variables 20


t horizontal tab (0x9) a backslash
20. Widget Scroll Commands 20


v vertical tab (0xB)
21. The Canvas Widget 21
22. The Entry Widget 26 2. Tcl Special Variables
23. The Listbox Widget 27
24. The Menu Widget 28 argc Number of command line arguments.
25. The Text Widget 30 argv Tcl list of command line arguments.
26. Other Standard Widgets 33 arg0 Name of script or command interpreter.
27. Images 38 env Array where each element name is an enviroment variable.
28. Window Information 40 errorCode Error code information from the last Tcl error.
29. The Window Manager 42 errorInfo Describes the stack trace of the last Tcl error.
30. Binding and Virtual Events 43 tcl_library Location of standard Tcl libraries.
31. Geometry Management 45 tcl_patchLevel Current patchlevel of Tcl interpreter.
32. Fonts 47 tcl_pkgPath List of directories to search for package loading.
33. Other Tk Commands 47 tcl_platform Array with elements byteOrder, osVersion,
Rev. 8.0.3 machine, platform, and os.

2
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
tcl_precision Number of significant digits to retain when converting ( ) group expressions
floating-point numbers to strings (default 12).
tcl_traceCompile 5. Pattern Globbing
Level of tracing info output during bytecode compilation.
tcl_traceExec Level of tracing info output during bytecode execution. ? match any single character
tcl_version Current version of Tcl interpreter. * match zero or more characters
[abc] match set of characters
3. Operators and Expressions
[a-z] match range of characters


The expr command recognizes the following operators, in decreasing order of c match character c
precedence: {a,b,...} match any of strings a, b, etc.
- ˜ ! unary minus, bitwise NOT, logical NOT ˜ home directory (for glob command)
* / % multiply, divide, remainder
˜user match user’s home directory (for glob command)
+ - add, subtract
<< >> bitwise shift left, bitwise shift right Note: for the glob command, a “.” at the beginning of a file’s name or just after “/”
< > <= >= boolean comparisons must be matched explicitly and all “/” characters must be matched explicitly.
== != boolean equals, not equals
& bitwise AND 6. Control Statements
bitwise exclusive OR
| bitwise inclusive OR break Abort innermost containing loop command.
&& logical AND
|| logical OR case Obsolete, see switch.
x ? y : z if x != 0, then y, else z continue
All operators support integers. All support floating point except ˜, %, <<, >>, &, , Skip to the next iteration of innermost containing loop command.
and |. Boolean operators can also be used for string operands, in which case string exit [ returnCode ]
comparison will be used. This will occur if any of the operands are not valid Terminate the process, returning returnCode (an integer which defaults to
numbers. The &&, ||, and ?: operators have “lazy evaluation”, as in C. 0) to the system as the exit status.
Possible operands are numeric values, Tcl variables (with $), strings in double for start test next body
quotes or braces, Tcl comands in brackets, and the following math functions: Looping command where start, next, and body are Tcl command strings
abs ceil floor log10 sinh and test is an expression string to be passed to expr command.
acos cos fmod pow sqrt foreach varname list body
asin cosh hypot rand srand The Tcl command string body is evaluated for each item in the string list
atan double int round tan where the variable varname is set to the item’s value.
atan2 exp log sin tanh
foreach varlist1 list1 [varlist2 list2 ...] body
Same as above, except during each iteration of the loop, each variable in
4. Regular Expressions varlistN is set to the current value from listN.
if expr1 [ then ] body1 [ elseif expr2 [ then ] body2 ... ] [ [ else ] bodyN ]
regex|regex match either expression If expression string expr1 evaluates true, Tcl command string body1 is
regex* match zero or more of regex evaluated. Otherwise if expr2 is true, body2 is evaluated, and so on. If
none of the expressions evaluate to true then bodyN is evaluated.
regex+ match one or more of regex
return [-code code] [-errorinfo info] [-errorcode code] [string]
regex? match zero or one of regex
Return immediately from current procedure with string as return value.
. any single character except newline
switch [options] string {pattern1 body1 [ pattern2 body2 ...] }
match beginning of string
The string argument is matched against each of the pattern arguments in
$ match end of string order. The bodyN of the first match found is evaluated. If no match is


c match character c even if special found and the last pattern is the keyword default, its bodyN is
[abc] match set of characters evaluated. Possible options are -exact, -glob, and -regexp.
[ abc] match characters not in set while test body
[a-z] match range of characters Evaluates the Tcl command string body as long as expression string test
[ a-z] match characters not in range evaluates to true.

3 4
Tcl/Tk Reference Guide Tcl/Tk Reference Guide

7. File Information file size fileName


Returns size of fileName in bytes.
file atime fileName file split fileName
Time fileName was last accessed as seconds since Jan. 1, 1970. Returns list whose elements are the path components of fileName.
file attributes fileName [option [value ... ] ] file stat fileName varName
Query or set platform-specific attributes of fileName. Options are for UNIX: Place results of stat kernel call on fileName in variable varName as an array
-group, -owner, -permissions; for Windows -archive, with elements atime, ctime, dev, gid, ino, mode, mtime, nlink,
-hidden, -longname, -readonly, -shortname, -system; and for size, type, and uid.
MacOS: -creator, -hidden, -readonly, -type. file tail fileName
file copy [-force] [- -] source [source ...] target Return all characters in fileName after last directory separator.
Makes a copy of source under name target. If multiple sources are given, file type fileName
target must be a directory. Use -force to overwrite existing files. Returns type of fileName. Possible values are file, directory,
file delete [-force] [- -] fileName [fileName ...] characterSpecial, blockSpecial, fifo, link, or socket.
Removes given files. Use -force to remove non-empty directories. file volume
file dirname fileName Returns just “/” on UNIX, list of local drives on Windows, and list of local
Returns all directory path components of fileName. and network drives on MacOS.
file executable fileName file writable fileName
Returns 1 if fileName is executable by user, 0 otherwise. Returns 1 if fileName is writable by current user, 0 otherwise.
file exists fileName
Returns 1 if fileName exists (and user can read its directory), 0 otherwise. 8. Tcl Interpreter Information
file extension fileName
Returns all characters in fileName after and including the last dot. info args procName
Returns list describing in order the names of arguments to procName.
file isdirectory fileName
info body procName
Returns 1 if fileName is a directory, 0 otherwise.
Returns the body of procedure procName.
file isfile fileName
info cmdcount
Returns 1 if fileName is a regular file, 0 otherwise.
Returns the total number of commands that have been invoked.
file join name [name ...]
info commands [pattern]
Joins file names using the correct path separator for the current platform.
Returns list of Tcl commands (built-ins and procs) matching glob pattern. If
file lstat fileName varName no pattern is given, returns all commands in current namespace.
Same as file stat except uses the lstat kernel call.
info complete command
file mkdir dirName [dirName ...] Returns 1 if command is a complete Tcl command, 0 otherwise. Complete
Creates given directories. means having no unclosed quotes, braces, brackets or array element names
file mtime fileName info default procName arg varName
Time fileName was last modified as seconds since Jan. 1, 1970. Returns 1 if procedure procName has a default for argument arg and places
file nativename fileName the value in variable varName. Returns 0 if there is no default.
Returns the platform-specific name of fileName. info exists varName
file owned fileName Returns 1 if the variable varName exists in the current context, 0 otherwise.
Returns 1 if fileName owned by the current user, 0 otherwise. info globals [pattern]
file pathtype fileName Returns list of global variables matching glob pattern (default *).
Returns one of absolute, relative, or volumerelative. info hostname
file readable fileName Returns name of computer on which interpreter was invoked.
Returns 1 if fileName is readable by current user, 0 otherwise. info level
file readlink fileName Returns the stack level of the invoking procedure.
Returns value of symbolic link given by fileName. info level number
file rename [-force] [- -] source [source ...] target Returns name and arguments of procedure invoked at stack level number.
Renames file source to target. If target is an existing directory, each source info library
file is moved there. The -force option forces overwriting of existing files. Returns name of library directory where standard Tcl scripts are stored.
file rootname fileName info loaded [interp]
Returns all the characters in fileName up to but not including last dot. Returns list describing packages loaded into interp.

5 6
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
info locals [pattern] -real floating-point comparison
Returns list of local variables matching glob pattern (default *). -increasing sort in increasing order (default)
info nameofexecutable -decreasing sort in decreasing order
Returns full pathname of binary from which the application was invoked. -command cmd Use cmd which takes two arguments and returns an
info patchlevel integer less than, equal to, or greater than zero
Returns current patch level for Tcl. split string [splitChars]
info procs [pattern] Returns a list formed by splitting string at each character in splitChars.
Returns list of Tcl procedures in current namespace matching glob pattern Note: list indices start at 0 and the word end may be used to reference the last
(default *). element in the list.
info script
Returns name of Tcl script currently being evaluated. 10. Arrays
info sharedlibextension
Returns extension used by platform for shared objects. array anymore arrayName searchId
info tclversion Returns 1 if anymore elements are left to be processed in array search
Returns version number of Tcl in major.minor form. searchId on arrayName, 0 otherwise.
info vars [pattern] array donesearch arrayName searchId
Returns list of currently-visible variables matching glob pattern (default *). Terminates the array search searchId on arrayName.
array exists arrayName
9. Lists Returns 1 if arrayName is an array variable, 0 otherwise.
array get arrayName
concat [arg arg ...] Returns a list where each odd element is an element name and the following
Returns concatenation of each list arg as a single list. even element its corresponding value.
join list [joinString] array names arrayName [pattern]
Returns string created by joining all elements of list with joinString. Returns list of all element names in arrayName that match glob pattern.
lappend varName [value value ...] array nextelement arrayName searchId
Appends each value to the end of the list stored in varName. Returns name of next element in arrayName for the search searchId.
lindex list index array set arrayName list
Returns value of element at index in list. Sets values of elements in arrayName for list in array get format.
linsert list index element [element ...] array size arrayName
Returns new list formed by inserting given new elements at index in list. Return number of elements in arrayName.
list [arg arg ...] array startsearch arrayName
Returns new list formed by using each arg as an element. Returns a search id to use for an element-by-element search of arrayName.
llength list parray arrayName [pattern]
Returns number of elements in list. Print to standard output the names and values of all element names in
lrange list first last
arrayName that match glob pattern.
Returns new list from slice of list at indices first through last inclusive.
lreplace list first last [value value ...]
11. Strings and Binary Data
Returns new list formed by replacing elements first through last in list with
given values. append varName [value value ...]
lsearch [mode] list pattern
Appends each of the given values to the string stored in varName.
Returns index of first element in list that matches pattern (-1 for no match). binary format formatString [arg arg ...]
Mode may be -exact, -glob (default), or -regexp. Returns a binary string representation of argss composed according to
lsort [switches] list
formatString, a sequence of zero or more field codes each followed by an
Returns new list formed by sorting list according to switches. These are optional integer count. The possible field codes are:
a chars (null padding) c 8-bit int f float
-ascii string comparison (default)
A chars (space padding) s 16-bit int (little) d double
-dictionary like -ascii but ignores case and is number smart. b binary (low-to-high) S 16-bit int (big) x nulls
-index ndx treats each elements as a sub-list and sorts on the B binary (high-to-low) i 32-bit int (little) X backspace
ndxth element h hex (low-to-high) I 32-bit int (big) @ absolute position
-integer integer comparison H hex (high-to-low)

7 8
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
string last string1 string2
binary scan string formatString varName [varName ...] Return index in string2 of last occurance of string1 (-1 if not found).
Extracts values into varName’s from binary string according to string length string
formatString. Returns the number of values extracted. Field codes are the Returns the number of characters in string.
same as for binary format except for: string match pattern string
a chars (no stripping) A chars (stripping) x skip forward Returns 1 if glob pattern matches string, 0 otherwise.
string range string first last
format formatString [arg arg ...] Returns characters from string at indices first through last inclusive.
Returns a formated string generated in the ANSI C sprintf-like manner. string tolower string
Placeholders have the form %[argpos$][flag][width][.prec][h|l]char Returns new string formed by converting all chars in string to lower case.
where argpos, width, and prec are integers and possible values for char are: string toupper string
d signed decimal X unsigned HEX E float (0E0) Returns new string formed by converting all chars in string to upper case.
u unsigned decimal c int to char g auto float (f or e) string trim string [chars]
i signed decimal s string G auto float (f or E) Returns new string formed by removing from string any leading or trailing
o unsigned octal f float (fixed) % plain % characters present in the set chars (defaults to whitespace).
x unsigned hex e float (0e0)
string trimleft string [chars]
Same as string trim for leading characters only.
and possible values for flag are: string trimright string [chars]
- left-justified 0 zero padding # alternate output Same as string trim for trailing characters only.
+ always signed space space padding string wordend string index
Returns index of character just after last one in word at index in string.
regexp [switches] exp string [matchVar] [subMatchVar ...] string wordstart string index
Returns 1 if the regular expression exp matches part or all of string , 0 Returns index of first character of word at index in string.
otherwise. If specified, matchVar will be set to all the characters in the match
subst [-nobackslashes] [-nocommands] [-novariables] string
and the following subMatchVar’s will be set to matched parenthesized
Returns result of backslash, command, and variable substitutions on string.
subexpressions. The -nocase switch can be specified to ignore case in
Each may be turned off by switch.
matching. The -indices switch can be specified so that matchVar and
subMatchVar will be set to the start and ending indices in string of their
corresponding match. 12. System Interaction
regsub [switches] exp string subSpec varName
Replaces the first portion of string that matches the regular expression exp cd [dirName]
with subSpec and places results in varName. Returns count of number of Change working directory to dirName.
replacements made. The -nocase switch can be specified to ignore case in clock clicks
matching. The -all switch will cause all matches to be substituted for. Returns hi-res system-dependent integer time value.
scan string formatString varName [varName ...] clock format clockVal [-format string] [-gmt boolean]
Extracts values into given variables using ANSI C sscanf behavior. Returns Convert integer clockVal to human-readable format defined by string which
the number of values extracted. Placeholders have the form %[*][width]char recognizes (at least) the following placeholders:
where * is for discard, width is an integer and possible values for char are: %% % %H hour (00 – 23) %U week (01 – 52)
d decimal e float s string (non-whitespace) %a weekday (abbr) %h hour (00 – 12) %w weekday (0 – 6)
o octal f float [chars] chars in given range %A weekday (full) %j day (001 – 366) %x locale date
x hex g float [ chars] chars not in given range %b month (abbr) %m month (01 – 12) %X locale time
c char to int %B month (full) %M minute (00 – 59) %y year (00 – 99)
%c locale date & time %p AM/PM %Y year (full)
%d day (01 – 31) %S seconds (00 – 59) %Z time zone
string compare string1 string2
Returns -1, 0, or 1, depending on whether string1 is lexicographically less The default format is ”%a %b %d %H:%M:%S %Z %Y”.
than, equal to, or greater than string2. clock scan dateString [-base clockVal] [-gmt boolean]
string first string1 string2 Convert dateString to an integer clock value. If dateString contains a 24
Return index in string2 of first occurance of string1 (-1 if not found). hour time only, the date given by clockVal is used.
string index string charIndex clock seconds
Returns the charIndex’th character in string. Return current date and time as system-dependent integer value.

9 10
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
exec [-keepnew] arg [arg ...] -peername
Execute subprocess using each arg as word for a shell pipeline and return For client and accepted sockets, three element list of peer socket.
results written to standard out, optionally retaining the final newline char. For serial device channels:
The following constructs can be used to control I/O flow.
-mode baud,parity,data,stop
| pipe (stdout) Set baud rate, parity, data bits, and stop bits of channel.
|& pipe (stdout and stderr)
fcopy inId outId [-size size] [-command callback]
<fileName stdin from file Transfer data to outId from inId until eof or size bytes have been transferred.
<@ fileId stdin from open file If -command is given, copy occurs in background and runs callback when
<<value pass value to stdin finished appending number of bytes copied and possible error message as
>fileName stdout to file arguments.
2>fileName stderr to file fileevent fileId readable|writable [script]
>& fileName stdout and stderr to file Evaluate script when channel fileId becomes readable/writable.
>>fileName append stdout to file flush fileId
Flushes any output that has been buffered for fileId.
2>>fileName append stderr to file
>>& fileName stdout and stderr to file gets fileId [varName]
Read next line from channel fileId, discarding newline character. Places
>@ fileId stdout to open file
characters of line in varName if given, otherwise returns them.
2>@ fileId stderr to open file
open fileName [access] [perms]
>&@ fileId stdout and stderr to open file Opens filename and returns its channel id. If a new file is created, its
& run in background permission are set to the conjuction of perms and the process umask. The
glob [-nocomplain] pattern [pattern ...] access may be
Returns list of all files in current directory that match any of the given r Read only. File must exist.
csh-style glob patterns, optionally suppressing error on no match.
r+ Read and write. File must exist.
pid [fileId]
Return process id of process pipeline fileId if given, otherwise return process w Write only. Truncate if exists.
id of interpreter process. w+ Read and write. Truncate if exists.
pwd Returns the current working directory. a Write only. File must exist. Access position at end.
a+ Read and write. Access position at end.
13. File Input/Output puts [-nonewline] [fileId] string
Write string to fileId (default stdout) optionally omitting newline char.
close fileId
read [-nonewline] fileId
Close the open file channel fileId.
Read all remaining bytes from fileId, optionally discarding last character if it
eof fileId is a newline.
Returns 1 if an end-of-file has occurred on fileId, 0 otherwise.
read fileId numBytes
fblocked fileId Read numBytes bytes from fileId.
Returns 1 if last read from fileId exhausted all available input.
seek fileId offset [origin]
fconfigure fileId [option [value]]
Change current access position on fileId to offset bytes from origin which
Sets and gets options for I/O channel fileId. Options are:
may be start, current, or end.
-blocking boolean Whether I/O can block process.
socket [option ...] host port
-buffering full|line|none How to buffer output. Open a client-side TCP socket to server host on port. Options are:
-buffersize byteSize Size of buffer.
-myaddr addr Set network address of client (if multiple available).
-eofchar char | {inChar outChar}
-myport port Set connection port of client (if different from server).
Sets character to serve as end-of-file marker.
-async Make connection asynchronous.
-translation mode | {inMode outMode}
Sets how to translate end-of-line markers. socket -server command [-myaddr addr] port
Modes are auto, binary, cr, crlf, and lf. Open server TCP socket on port invoking command once connected with
For socket channels (read-only settings): three arguments: the channel, the address, and the port number.
-sockname tell fileId
Returns three element list with address, host name and port number. Return current access position in fileId.

11 12
Tcl/Tk Reference Guide Tcl/Tk Reference Guide

14. Multiple Interpreters break fileevent join pid switch


case flush lappend proc tell
catch for lindex puts trace
interp alias srcPath srcCmd clock foreach linsert read unset
Returns list whose elements are the targetCmd and args associated with the close format list rename update
concat gets llength return uplevel
alias srcCmd in interpreter srcPath. continue global lower scan upvar
interp alias srcPath srcCmd eof history lrange seek vwait
Deletes the alias srcCmd in interpreter srcPath. error if lreplace set while

interp alias srcPath srcCmd targetPath targetCmd [arg ...] A safe interpreter is created with the following commands hidden:
Creates an alias srcCmd in interpreter srcPath which when invoked will run cd fconfigure load pwd source
targetCmd and args in the interpreter targetPath. exec file open socket vwait
exit glob
interp aliases [path]
Returns list of all aliases defined in interpreter path.
interp create [-safe] [- -] [path] 15. Packages
Creates a slave interpreter (optionally safe) named path.
interp delete path [path ...] package forget package
Deletes the interpreter(s) path and all its slave interpreters. Remove all info about package from interpreter.
interp eval path arg [arg ...] package ifneeded package version [script]
Evalutes concatenation of args as command in interpreter path. Tells interpreter that if version version of package, evaluating script will
interp exists path provide it.
Returns 1 if interpreter path exists, 0 otherwise. package names
interp expose path hiddenCmd [exposedCmd] Returns list of all packages in the interpreter that are currently provided or
Make hiddenCmd in interp path exposed (optionally as exposedCmd). have an ifneeded script available.
interp hide path exposedCmd [hiddenCmd] package provide package [version]
Make exposedCmd in interp path hidden (optionally as hiddenCmd). Tells interpreter that package version is now provided. Without version, the
interp hidden path currently provided version of package is returned.
Returns list of hidden commands in interp path. package require [-exact] package [version]
interp invokehidden path [-global] hiddenCmd [arg ...] Tells interpreter that package must be provided. Only packages with
Invokes hiddenCmd with specified args in interp path (at the global level if versions equal to or later than version (if provided) are acceptable. If
-global is given). -exact is specified, the exact version specified must be provided.
interp issafe [path] package unknown [command]
Returns 1 if interpreter path is safe, 0 otherwise. Specifies a last resort Tcl command to provide a package which have append
interp marktrusted [path] as its final two arguments the desired package and version.
Marks interp path as trusted. package vcompare version1 version2
interp share srcPath fileId destPath Returns -1 if version1 is earlier than version2, 0 if equal, and 1 if later.
Arranges for I/O channel fileId in interpreter srcPath to be shared with package versions package
interpreter destPath. Returns list of all versions numbers of package with an ifneeded script.
interp slaves [path] package vsatisfies version1 version2
Returns list of names of all slave interpreters of interpreter path. Returns 1 if version2 scripts will work unchanged under version1, 0
interp target path alias otherwise.
Returns Tcl list describing target interpreter of alias in interpreter path.
interp transfer srcPath fileId destPath 16. Namespaces
Moves I/O channel fileId from interpreter srcPath to destPath.
For each slave interpreter created, a new Tcl command is created by the same name namespace children [namespace] [pattern]
in its master. This command has the alias, aliases, eval, expose, hide, hidden, Returns list of child namespaces belonging to namespace (defaults to
invokehidden, issafe, and marktrusted subcommands like interp, but without current) which match pattern (default *).
the srcPath and path arguments (they default to the slave itself) and without the namespace code script
targetPath argument (it defaults to the slave’s master). Returns new script string which when evaluated arranges for script to be
A safe interpreter is created with the following commands exposed: evaluated in current namespace. Useful for callbacks.
after eval incr lsearch split
append expr info lsort string namespace current
array fblocked interp package subst Returns fully-qualified name of current namespace.

13 14
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
namespace delete [namespace ...] auto_execok execFile
Each given namespace is deleted along with their child namespaces, Returns full pathname if an executable file by the name execFile exists in
procedures, and variables. user’s PATH, empty string otherwise.
namespace eval namespace arg [arg ...] auto_load command
Activates namespace and evaluates concatenation of args’s inside it. Attempts to load definition for cmd by searching $auto_path and
namespace export [-clear] [pattern ...] $env(TCLLIBPATH) for a tclIndex file which will inform the interpreter
Adds to export list of current namespace all commands that match given where it can find command’s definition.
pattern’s. If -clear is given, the export list is first emptied. auto_mkindex directory pattern [pattern ...]
Generate a tclIndex file from all files in directory that match glob patterns.
namespace forget [namespace::pattern ...]
Removes from current namespace any previously imported commands from auto_reset
namespace that match pattern. Destroys cached information used by auto_execok and auto_load.
namespace import [-force] [namespace::pattern ...] bgerror message
Imports into current namespace commands matching pattern from User defined handler for background Tcl errors. Default exists for Tk.
namespace. The -force option allows replacing of existing commands. catch script [varName]
namespace inscope namespace listArg [arg ...] Evaluate script and store results into varName. If there is an error, a
Activates namespace (which must already exist) and evaluates inside it the non-zero error code is returned and an error message stored in varName.
result of lappend of arg’s to listArg. error message [info] [code]
namespace origin command
Interrupt command interpretation with an error described in message. Global
Returns fully-qualified name of imported command. variables errorInfo and errorCode will be set to info and code.
eval arg [arg ...]
namespace parent [namespace]
Returns result of evaluating the concatenation of args’s as a Tcl command.
Returns fully-qualified name of parent namespace of namespace.
expr arg [arg ...]
namespace qualifiers string
Returns result of evaluating the concatenation of arg’s as an operator
Returns any leading namespace qualifiers in string.
expression. See Operators for more info.
namespace tail string
global varName [varName ...]
Returns the simple name (strips namespace qualifiers) in string.
Declares given varName’s as global variables.
namespace which [-command|-variable] name history add command [exec]
Returns fully-qualified name of the command (or as variable, if -variable Adds command to history list, optionally executing it.
given) name in the current namespace. Will look in global namespace if not
history change newValue [event]
in current namespace.
Replaces value of event (default current) in history with newValue.
variable [name value ...] name [value]
history clear
Creates one or more variables in current namespace (if name is unqualified)
Erase the history list and reset event numbers.
initialized to optionally given values. Inside a procedure and outsize a
namespace eval, a local variable is created linked to the given namespace history event [event]
variable. Returns value of event (default -1) in history.
history info [count]
17. Other Tcl Commands Returns event number and contents of the last count events.
history keep [count]
after ms [arg1 arg2 arg3 ...] Set number of events to retain in history to count.
Arrange for command (concat of args) to be run after ms milliseconds have history nextid
passed. With no args, program will sleep for ms milliseconds. Returns the id Returns number for next event to be recorded in history.
of the event handler created. history redo [event]
after cancel id|arg1 arg2 ... Re-evaluates event (default -1).
Cancel previous after command either by command or the id returned. incr varName [increment]
after idle [arg1 arg2 arg3 ...] Increment the integer value stored in varName by increment (default 1).
Arrange for command (concat of args) to be run later when Tk is idle. load file [pkgName [interp]]
Returns the id of the event handler created. Load binary code for pkgName from file (dynamic lib) into interp.
after info [id] proc name args body
Returns information on event handler id. With no id, returns a list of all Create a new Tcl procedure (or replace existing one) called name where args
existing event handler ids. is a list of arguments and body Tcl commmands to evaluate when invoked.

15 16
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
rename oldName newName 18. General Tk Widget Information
Rename command oldName so it is now called newName. If newName is the
empty string, command oldName is deleted. All widget are created with
set varName [value] widget pathname [ option1 value1 [ option2 ... ] ]
Store value in varName if given. Returns the current value of varName.
where widget is the Tcl command corresponding to the class of widget desired (eg.
source fileName button) and pathname is a string which will be used to identify the newly created
Read file fileName and evaluate its contents as a Tcl script. widget. In general, a widget name is the concatenation of its parent’s name
time script [count] followed by a period (unless the parent is the root window “.”) and a string
Call interpreter count (default 1) times to evaluate script. Returns string of containing no periods (eg. .mainframe.btnframe.btn1).
the form “503 microseconds per iteration”. Widget configuration options may be passed in the creation command. Options
trace variable varName ops command begin with a “-” and are always followed by a value string. After creation, options
Arrange for command to be evaluated whenever varName is accessed in one may be changed using the configure widget command
of the ways specified with ops. Possbile values are r for read, w for written, pathname configure option1 value1 [ option2 ... ]
u for unset, and any combination of the three.
and queried using the cget command
trace vdelete varName ops command
pathname cget option
Remove any previous trace specified with the given arguments.
trace vinfo varName
Some of the widget options which multiple widgets support are described here for
Returns list describing each trace on varName. brevity. For options that take screen units, values are in pixels unless an optional
one letter suffix modifier is present — c (cm), i (inch), m (mm), or p (points).
unknown cmdName [arg arg ...]
Called when the Tcl interpreter encounters an undefined command name. -activebackground color
Background color of widget when it is active.
unset varName [varName ...]
Removes the given variables and arrays from scope. -activeborderwidth width
update [idletasks]
Width in screen units of widget border when it is active.
Handle pending events. If idletasks is specified, only those operations -activeforeground color
normally deferred until the idle state are processed. Foreground color of widget when it is active.
uplevel [level] arg [arg ...] -anchor anchorPos
Evaluates concatenation of arg’s in the variable context indicated by level, How information is positioned inside widget. Valid anchorPos values are n,
an integer that gives the distance up the calling stack. If level is preceded by ne, e, se, s, sw, w, nw, and center.
“#”, then it gives the distance down the calling stack from the global level. -background color
upvar [level] otherVar myVar [otherVar myVar ...] Background color of widget in normal state (Abbrev: -bg).
Makes myVar in local scope equivalent to otherVar at context level (see -bitmap bitmap
uplevel) so they share the same storage space. Bitmap to display in the widget (error, gray12, gray25,
vwait varName gray50, gray75, hourglass, info, questhead,
Enter Tcl event loop until global variable varName is modified. question, warning, @filename).
-borderwidth width
Width in screen units of widget border in normal state (Abbrev: -bd).
-command tclCommand
Tcl command to run when widget is invoked.
-cursor cursor
Cursor to display when mouse pointer is in widget. Valid formats:
name [fgColor [bgColor]
Name of cursor from /usr/include/X11/cursorfont.h.
@sourceName maskName fgColor bgColor
Get source and mask bits from files sourceName and maskName.
@sourceName fgColor
Get source bits from file sourceName (background transparent).
-disabledforeground color
Foreground color of widget when it is disabled.
-exportselection boolean
Whether or not a selection in the widget should also be the X selection.

17 18
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
-font font -setgrid boolean
Font to use when drawing text inside the widget. Whether this widget controls the resizing grid for its toplevel window.
-foreground color -state normal|disabled (|active for button-type widgets)
Foreground color of widget in normal state (Abbrev: -fg). Current state of widget.
-height width|textChars -takefocus focusType
Height of widget. Units depend on widget. If 0 or 1, signals that the widget should never or always take the focus. If
-highlightbackground color empty, Tk decides. Otherwise, evaluates focusType as script with the widget
Color of the rectangle drawn around the widget when it does not have the name appended as argument. The return value of the script must be 0, 1 or
input focus. empty.
-highlightcolor color -text string
Color of the rectangle drawn around the widget when it has the input focus. Text to be displayed inside the widget.
-highlightthickness width -textvariable variable
Width in screen units of highlight rectangle drawn around widget when it Variable which contains a text string to be displayed inside the widget.
has the input focus. -troughcolor color
-image image Color to use for the rectangular trough areas in widget.
Image to display in the widget (see Images). -underline index
-insertbackground color Integer index of a character to underline in the widget.
Color to use as background in the area covered by the insertion cursor. -width width|textChars
-insertborderwidth width Width of widget. Units depend on widget.
Width in screen units of border to draw around the insertion cursor. -wraplength length
-insertofftime milliseconds Maximum line length in screen units for word-wrapping.
Time the insertion cursor should remain “off” in each blink cycle. -xscrollcommand cmdPrefix
Prefix for a command used to communicate with horizontal scrollbars.
-insertontime milliseconds
Time the insertion cursor should remain “on” in each blink cycle. -yscrollcommand cmdPrefix
Prefix for a command used to communicate with vertical scrollbars.
-insertwidth width
Width in screen units of the insertion cursor.
-jump boolean
19. Tk Special Variables
Whether to notify scrollbars and scales connected to the widget to delay
tk_library
updates until mouse button is released.
Directory containing library of standard Tk scripts.
-justify left|center|right
tk_patchLevel
How multiple lines line up with each other.
Integer specifying current patch level for Tk.
-orient horizontal|vertical
tkPriv
Which orientation widget should use in layout.
Array containing information private to standard Tk scripts.
-padx width
tk_strictMotif
Extra space in screen units to request for the widget in X-direction.
When non-zero, Tk tries to adhere to Motif look-and-feel as closely as
-pady height possible.
Extra space in screen units to request for the widget in Y-direction.
tk_version
-relief flat|groove|raised|ridge|sunken Current version of Tk in major.minor form.
3-D effect desired for the widget’s border.
-repeatdelay milliseconds 20. Widget Scroll Commands
Time a button or key must be held down before it begins to auto-repeat.
-repeatinterval milliseconds The Canvas, Listbox and Text widgets support the following scrolling commands.
Time between auto-repeats once action has begun. The Entry widget supports the xview command and the scan command with the y
-selectbackground color coordinate dropped.
Background color to use when displaying selected items. widget scan mark x y
-selectborderwidth width Records x and y as widget’s current view anchor.
Width in screen units of border to draw around selected items. widget scan dragto x y
-selectforeground color Shift the view by 10 times the difference between the coordinates x and y
Foreground color to use when displaying selected items. and the current view anchor coordinates.

19 20
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
widget xview -yscrollincrement distance
Return a two element list specifying the fraction of the horizontal span of the Specifies the increment for vertical scrolling in screen units.
widget at the left and right edges of the window.
Coordinate examples: 5 (pixel), 2.2i (inch), 4.1c (cm), 3m (mm), 21p (pts)
widget xview moveto fraction
Adjust the view in the window so that fraction of the total width of the Larger y-coordinates refer to points lower on the screen.
widget is off-screen to the left. Larger x-coordinates refer to points farther to the right.
widget xview scroll number units|pages Character positions: charIndex, end, insert, sel.first, sel.last, @x,y
Shift the view by number one-tenths (unit) or nine-tenths (pages) the
window’s width in the horizontal direction.
widget yview Canvas Commands
Return a two element list specifying the fraction of the vertical span of the
widget at the top and bottom edges of the window. canvas addtag tag searchSpec [arg arg ...]
Add tag to the list of tags associated with each item that satisfy searchSpec.
widget yview moveto fraction
See Canvas Search Specs below.
Adjust the view in the window so that fraction of the total height of the
widget is off-screen to the top. canvas bbox tagOrId [tagOrId ...]
Returns a list with four elements giving an approximate bounding box for all
widget yview scroll number units|pages
the items named by the tagOrId arguments.
Shift the view by number one-tenths (unit) or nine-tenths (pages) the
window’s height in the vertical direction. canvas bind tagOrId [sequence [command]]
Associates command to be invoked on events specified with sequence with
The Text Widget also supports the following: the items given by tagOrId.
text yview [-pickplace] index canvas canvasx screenx [gridspacing]
Changes view of widget’s window to make character at index visible. If Returns the canvas x-coordinate that is displayed at screen x-coordinate
-pickplace is specified, index will appear at the top of the window. screenx possibly rounding to nearest multiple of gridspacing units.
The Entry (xview only) and Listbox Widget also supports the following: canvas canvasy screeny [gridspacing]
listbox xview index Returns the canvas x-coordinate that is displayed at screen y-coordinate
Adjusts view so that character position index is at left edge. screeny possibly rounding to nearest multiple of gridspacing units.
listbox yview index canvas coords tagOrId [x0 y0 ...]
Adjusts view so that element at index is at top of window. Query or modify the coordinates that define an item.
canvas create type x y [x y ...] [option value ...]
21. The Canvas Widget Create a new item of type type at specified coordinates and with list options.
canvas dchars tagOrId first [last]
Canvas Options For items given by tagOrId, delete the characters in the range given by first
and last (defaults to first), inclusive.
-background -insertbackground -selectborderwidth
canvas delete [tagOrId ...]
-borderwidth -insertborderwidth -selectforeground
Delete each of the items given by each tagOrId.
-cursor -insertofftime -takefocus
-height -insertontime -width canvas dtag tagOrId [tagToDelete]
-highlightbackground -insertwidth -xscrollcommand Remove tag tagToDelete from the taglist of items given by tagOrId.
-highlightcolor -relief -yscrollcommand canvas find searchSpec [arg arg ...]
-highlightthickness -selectbackground Returns a list of the items that satisfy the specification searchSpec. See
Canvas Search Specs below.
-closeenough float canvas focus tagOrId
How close the mouse cursor must be to an item before it is considered to be Set the focus to the first textual item given by tagOrId.
“inside” the item. canvas gettags tagOrId
-confine boolean Return a list of the tags associated with the first item given by tagOrId.
Whether it is allowable to set the canvas’s view outside the scroll region. canvas icursor tagOrId index
-scrollregion corners Set the insertion cursor for the item(s) given by tagOrId to just before the
List of four coordinates describing the left, top, right, and bottom of a character position index .
rectangular scrolling region. canvas index tagOrId index
-xscrollincrement distance Returns a decimal string giving the numerical index within tagOrId
Specifies the increment for horizontal scrolling in screen units. corresponding to character position index.

21 22
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
canvas insert tagOrId beforeThis string enclosed x1 y1 x2 y2
Insert string just before character position beforeThis in items given by Selects all the items completely enclosed within x1 y1 x2 y2.
tagOrId that support textual insertion. overlapping x1 y1 x2 y2
canvas itemcget tagOrId option Selects all the items that overlap or are enclosed within x1 y1 x2 y2.
Returns the value option for the item given by tagOrId. withtag tagOrId
canvas itemconfigure tagOrId [option value ...] Selects all the items given by tagOrId.
Modifies item-specific options for the items given by tagOrId.
canvas lower tagOrId [belowThis] Canvas Item Types
Move the items given by tagOrId to a new position in the display list just
before the first item given by belowThis. canvas create arc x1 y1 x2 y2 [option value ...]
canvas move tagOrId xAmount yAmount -fill color -stipple bitmap -width outlineWidth
Move the items given by tagOrId in the canvas coordinate space by adding -outline color -tags tagList
xAmount and yAmount to each items x and y coordinates, respectively.
-extent degrees
canvas postscript [option value ...]
Size of the angular range occupied by arc.
Generate a Encapsulated Postscript representation for part or all of the
canvas. See Canvas Postscript Options below. -outlinestipple bitmap
Bitmap stipple to use to draw arc’s outline.
canvas raise tagOrId [aboveThis]
Move the items given by tagOrId to a new position in the display list just -start degrees
after the first item given by aboveThis. Starting angle measured from 3-o’clock position.
canvas scale tagOrId xOrigin yOrigin xScale yScale -style pieslice|chord|arc
Rescale items given by tagOrId in canvas coordinate space to change the How to “complete” the region of the arc.
distance from xOrigin,yOrigin by a factor of xScale,yScale respectively. canvas create bitmap x y [option value ...]
canvas scan args -anchor anchorPos -bitmap bitmap -tags tagslist
See Widget Scroll Commands above. -background color -foreground color
canvas select adjust tagOrId index
Adjust nearest end of current selection in tagOrId to be at index and set the canvas create image x y [option value ...]
other end to be the new selection anchor.
-anchor anchorPos -image image -tags tagslist
canvas select clear
Clear the selection if it is in the widget.
canvas create line x1 y1 ... xN yN [option value ...]
canvas select from tagOrId index
-fill color -stipple bitmap -width outlineWidth
Set the selection anchor in tagOrId to just before the character at index.
-smooth boolean -tags tagList
canvas select item
Return id of the selected item. Returns a empty string if there is none. -arrow none|first|last|both
Specify on which ends of the line to draw arrows.
canvas select to tagOrId index
Set the selection to extend between index and anchor point in tagOrId. -arrowshape shape
canvas type tagOrId Three element list which describes shape of arrow.
Returns the type of the first item given by tagOrId. -capstyle butt|projecting|round
canvas xview|yview args How to draw caps at endpoints of the line. Default is butt.
See Widget Scroll Commands above. -joinstyle bevel|miter|round
How joints are to be drawn at vertices. Default is miter.
-splinesteps number
Canvas Search Specifications
Degree of smoothness desired for curves.
above tagOrId
canvas create oval x1 y1 x2 y2 [option value ...]
Selects the item just after the one given by tagOrId in the display list.
-fill color -stipple bitmap -width outlineWidth
all Selects all the items in the canvas. -outline color -tags tagList
below tagOrId
Selects the item just before the one given by tagOrId in the display list.
canvas create polygon x1 y1 ... xN yN [option value ...]
closest x y [halo] [start]
-fill color -smooth boolean -tags tagList
Select the topmost, closest item to @x,y that is below start in the display list.
-outline color -stipple bitmap -width outlineWidth
Any item closer than halo to the point is considered to overlap it.

23 24
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
-splinesteps number -rotate boolean
Degree of smoothness desired for curved perimeter. Whether the printed area is to be rotated 90 degrees. (“landscape”).
-width size
canvas create rectangle x1 y1 x2 y2 [option value ...]
Specifies the width of the area of the canvas to print. Defaults to the width of
-fill color -stipple bitmap -width outlineWidth the canvas window
-outline color -tags tagList
-x position
Set the x-coordinate of the left edge of canvas area to print.
canvas create text x y [option value ...]
-y position
-anchor anchorPos -font font -tags tagList Set the y-coordinate of the top edge of canvas area to print.
-fill color -stipple bitmap -text string
-justify left|right|center 22. The Entry Widget
How to justify text within its bounding region.
-width lineLength Entry Widget Options


Maximum line length for the text. If zero, break only on n.
-background -highlightcolor -relief
canvas create window x y [option value ...] -borderwidth -highlightthickness -selectbackground
-anchor anchorPos -tags tagList -cursor -insertbackground -selectborderwidth
-exportselection -insertborderwidth -selectforeground
-height height Height in screen units to assign item’s window.
-font -insertofftime -state
-width width Width in screen units to assign item’s window. -foreground -insertontime -takefocus
-window pathName Window to associate with item. -highlightbackground
-insertwidth -textvariable
-justify -width
Canvas Postscript Options
-show char
-colormap varName Show char rather than actual characters for each character in entry.
Specifies a color mapping to use where varName is an array variable whose Entry Indices: number, anchor, end, insert, sel.first,
elements specify Postscript code to set a particular color value. sel.last, @x-coord
-colormode color|grey|mono
Specifies how to output color information.
Entry Widget Commands
-file fileName
Specifies the name of the file in which to write the Postscript. If not entry bbox index
specified, the Postscript is returned as the result of the command. Returns bounding box of character given by index.
-fontmap varName entry delete first [last]
Specifies a font mapping to use where varName is an array variable whose Delete characters from first through character just before last.
elements specify the Postscript font and size to use as a two element list. entry get
-height size Returns the entry’s string.
Specifies the height of the area of the canvas to print. Defaults to the height entry icursor index
of the canvas window Display insertion cursor just before character at index.
-pageanchor anchor entry index index
Specifies which point of the printed area should be appear over the Returns the numerical index corresponding to index.
positioning point on the page. Defaults to center. entry insert index string
-pageheight size Insert string just before character at index.
Specifies that the Postscript should be scaled in both x and y so that the entry scan option args
printed area is size high on the Postscript page. See Widget Scroll Commands above.
-pagewidth size entry selection adjust index
Specifies that the Postscript should be scaled in both x and y so that the Adjust nearest end of current selection to be at index and set the other end to
printed area is size wide on the Postscript page. the anchor point.
-pagex position entry selection clear
Set the x-coordinate of the positioning point on the page to position. Clear the selection if currently in the widget.
-pagey position entry selection from index
Set the y-coordinate of the positioning point on the page to position. Set the anchor point to be at index.

25 26
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
entry selection present listbox selection set first [last]
Returns 1 is any characters are selected, 0 otherwise. Add all elements between first and last inclusive to selection.
entry selection range start end listbox see index
Select the characters from start through character just before end. Adjust the view in window so element at index is completely visible.
entry selection to index listbox size
Set the selection to extend between index and anchor point. Returns number of elements in listbox.
listbox xview|yview args
23. The Listbox Widget See Widget Scroll Commands above.

Listbox Widget Options 24. The Menu Widget


-background -height -selectborderwidth Menu Widget Options
-borderwidth -highlightbackground-selectforeground
-cursor -highlightcolor -setgrid -activebackground -borderwidth -font
-exportselection -highlightthickness -takefocus -activeborderwidth -cursor -foreground
-font -relief -width -activeforeground -disabledforeground -relief
-foreground -selectbackground -xscrollcommand -background
-yscrollcommand
-postcommand tclCommand
-selectMode single|browse|multiple|extended Specify Tcl command to invoke immediately before the menu is posted.
-selectcolor color
Listbox Indices: number (starts at 0), active, anchor, end, @x,y Specifies indicator color for checkbutton and radiobutton entries.
-tearoff boolean
Listbox Widget Commands Whether to include a tear-off entry at top of menu.
-tearoffcommand tclCmd
listbox activate index Specifies command to be run when menu is torn off. The name of the menu
Sets the active element to index. and the new torn-off window will be appended on invocation.
listbox bbox index -title string
Returns a list {x y width height} bounding element at index. Uses string for title of window used when the menu is torn off.
listbox curselection -type type
Returns list of indices of all elements currently selected. Used at creation where type is one of menubar, tearoff, or normal.
listbox delete index1 [index2] Entry Types: cascade, checkbutton, command, radiobutton,
Delete range of elements from index1 to index2 (defaults to index1). separator
listbox get index1 [index2] Menu Indices: number, active, last, none, @y-coord, matchPattern
Return as a list contents of elements from index1 to index2.
listbox index index
Menu Widget Commands
Returns position index in number notation.
listbox insert index [element ...] menu activate index
Insert specified elements just before element at index. Change state of entry at index to be sole active entry in menu.
listbox nearest y menu add type [option value ...]
Return index of element nearest to y-coordinate. Add new entry of type type to bottom of menu. See below for options.
listbox scan args menu clone newMenuName [cloneType]
See Widget Scroll Commands above. Clones menu as a new menu newMenuName of type cloneType (see -type).
listbox selection anchor index menu delete index1 [index2]
Set the selection anchor to element at index. Delete all entries between index1 and index2 inclusive.
listbox selection clear first [last] menu entrycget index option
Deselect elements between first and last inclusive. Return current value of option for entry at index.
listbox selection includes index menu entryconfigure index [option value ...]
Returns 1 if element at index is selected, 0 otherwise. Set option values for entry at index.

27 28
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
menu index index -variable variable
Returns the numerical index corresponding to index. Name of global variable to set when checkbutton or radiobutton is selected.
menu insert index type [option value ...]
Same as add but inserts new entry just before entry at index. 25. The Text Widget
menu invoke index
Invoke the action of the menu entry at index. Text Widget Options
menu post x y
-background -highlightthickness -selectbackground
Display menu on screen at root-window coordinates given by x y.
-borderwidth -insertbackground -selectborderwidth
menu postcascade index -cursor -insertborderwidth -selectforeground
Post submenu associated with cascade entry at index.
-exportselection -insertofftime -setgrid
menu type index -font -insertontime -state
Returns type of menu entry at index. -foreground -insertwidth -takefocus
menu unpost -height -padx -width
Unmap window so it is no longer displayed. -highlightbackground-pady -xscrollcommand
menu yposition index -highlightcolor -relief -yscrollcommand
Returns the y-coordinate within the menu window of the topmost pixel in
the entry specified by index. -spacing1 size Space in screen units above paragraphs.
-spacing2 size Space in screen units between paragraph lines.
Menu Entry Options -spacing3 size Space in screen units below paragraphs.
The following options work for all cascade, checkbutton, command, and -tabs tabList
radiobutton entries unless otherwise specified. Set of tab stops as a list of screen distances giving their positions. Each stop
may be followed by one of left, right, center, or numeric.
-activebackground -bitmap -image
-activeforeground -font -state -wrap none|char|word How to wrap lines.
-background -foreground -underline
Text Indices
-accelerator string
Syntax: base [modifier ... ]
Specifies string to display at right side of menu entry.
Base: line.char, @x,y, end, mark, tag.first, tag.last, pathName
-command tclCommand
(embedded window), imageName (embedded image)
TCL command to evaluate when entry is invoked.
Modifier: count chars, count lines, linestart, lineend,
-columnbreak value
wordstart, wordend
When value is 1, entry appears at top of a new column in menu.
Ranges: Ranges include all characters from the start index up to but not
-hidemargin value
including the character at the stop index.
When value is 1, the standard margins are not drawn around entry.
-indicatoron boolean
Whether indictor for checkbutton or radiobutton entry should be displayed. Text Tag Options
-label string -background -justify -spacing2
Textual string to display on left side of menu entry. -borderwidth -relief -spacing3
-menu pathName -font -spacing1 -wrap
Pathname to a menu to post when cascade entry is active. -foreground
-offvalue value -bgstipple bitmap Stipple pattern for background.
Value to store in checkbutton entry’s associated variable when deselected.
-fgstipple bitmap Stipple pattern for foreground.
-onvalue value
-lmargin1 size Left margin of first line of a paragraph.
Value to store in checkbutton entry’s associated variable when selected.
-lmargin2 size Left margin of wrapped lines of a paragraph.
-selectcolor color
Color for indicator in checkbutton and radiobutton entries. -offset size Offset of baseline from normal baseline.
-selectimage image -overstrike boolean Whether to overstrike text.
Image to draw in indicator for checkbutton and radiobutton entries. -rmargin size Right margin of all lines.
-value value -tabs tabList Set of tab stops (see -tabs above).
Value to store in radiobutton entry’s associated variable when selected. -underline boolean Whether to underline text.

29 30
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
Text Embedded Window Options text image create index [option value ...]
Create a new embedded image at position index with specified options.
-align top|center|bottom|baseline
text image names
How window is vertically aligned with its line.
Returns list of names of all images embedded in text widget.
-create script
text index index
Script to create and return window pathname if no -window option is
Returns position index in line.char notation.
given.
-padx width text insert index [string [tagList string tagList ...]]
Extra space in screen units to leave on the left and right side of window. Insert string into text at index applying tags from tagList.
-pady height text mark gravity markName [left|right]
Extra space in screen units to leave on the top and bottom of window. Returns (or sets) which adjacent character a mark is attached to.
-stretch boolean text mark names
Whether window should be stretched vertically to fill line. Returns a list of the names of all marks currently set.
-window pathName text mark next | previous index
Name of window to display. Return name of next/previous mark at or after/before index.
text mark set markName index
Text Embedded Image Options Set mark markName to position just before character at index.
text mark unset markName [markName ...]
-align top|center|bottom|baseline Remove each mark specified so they are no longer usable as indices.
Where image is displayed on the line. text scan args
-image image See Widget Scroll Commands above.
Specifies Tk image to use for embedded image. text search [switches] pattern index [stopIndex]
-name imageName Returns index of first character matching pattern in text range index to
Specifies name which may be used to reference the embedded image. stopIndex. Switches: -forwards, -backwards,
-padx width -exact, -regexp, -count var, -nocase
Extra space in screen units to leave on the left and right side of image. text see index
-pady height Adjust the view in window so character at index is completely visible.
Extra space in screen units to leave on the top and bottom of image. text tag add tagName index1 [index2]
Apply tag tagName to characters in given range.
Text Widget Commands text tag bind tagName [sequence [script]]
Arrange for script to be run whenever event sequence occurs for a character
text bbox index with tag tagName.
Returns a list {x y width height} bounding character at index.
text tag cget tagName option
text compare index1 op index2
Return current value of option for tag tagName.
Compares indices index1 and index2 according to relational operator op.
text tag configure tagName [option [value [option value ...]]]
text delete index1 [index2]
Modifies tag-specific options for the tag tagName.
Delete range of given text range.
text tag delete tagName [tagName ...]
text dlineinfo index
Delete all tag information for given tags.
Returns a list {x y width height baseline} describing the screen area taken
by display line at index. text tag lower tagName [belowThis]
text dump [switches] index1 [index2] Change priority of tag tagName so it is just below tag belowThis.
Returns detailed info on text widget contents in given text range. Switches text tag names [index]
include -all, -mark, -tag, -text, -window for specifying type of Returns a list of the names of all tags associated with character at index. If
info returned. The switch -command command exists to invoke a procedure index is not given, returns list of all tags defined in widget.
on each element type in the range. text tag nextrange tagName index1 [index2]
text get index1 [index2] Searches character range index1 to index2 (default end) for the first region
Returns string of characters in given range. tagged with tagName. Returns character range of region found.
text image cget index option text tag prevrange tagName index1 [index2]
Return current value of option for embedded image at index. Like nextrange but searches backwards from index1 to index2 (default 1.0).
text image configure index [option [value [option value ...]]] text tag raise tagName [aboveThis]
Modifies embedded image-specific options for the image at index. Change priority of tag tagName so it is just above tag aboveThis.

31 32
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
text tag ranges tagName -offvalue value
Returns a list describing all character ranges tagged with tagName. Value given to variable specified with -variable option when the
text tag remove tagName index1 [index2] checkbutton is deselected.
Remove tag tagName for all characters in range index1 to index2. -onvalue value
text window cget index option Value given to variable specified with -variable option when the
Return current value of option for embedded window at index. checkbutton is selected.
text window configure index [option [value [option value ...]]] -selectcolor color
Modifies embedded window-specific options for the window at index. Color used to fill in indicator when selected.
text window create index [option value ...] -selectimage image
Create a new embedded window at position index with specified options. Image displayed in indicator when selected.
text window names -variable variable
Returns list of names of all windows embedded in text widget. Variable to associate with checkbutton.
text xview|yview args checkbutton deselect
See Widget Scroll Commands above. Deselect the checkbutton.
checkbutton flash
26. Other Standard Widgets Alternate checkbutton between active and normal colors.
checkbutton invoke
Button Toggle the selection state of the checkbutton and invoke the Tcl command
specified with -command, if any.
-activebackground -font -pady
checkbutton select
-activeforeground -foreground -relief
Select the checkbutton.
-anchor -height -state
-background -highlightbackground -takefocus checkbutton toggle
-bitmap -highlightcolor -text Toggle the selection state of the checkbutton.
-borderwidth -highlightthickness -textvariable
-command -image -underline Frame
-cursor -justify -width
-borderwidth -highlightbackground -relief
-disabledforeground-padx -wraplength
-cursor -highlightcolor -takefocus
-height -highlightthickness -width
-default state
Set state of default ring, one of active, normal, or disabled.
-background color
button flash Same as standard expect it may be the empty string to preserve colormap.
Alternate checkbutton between active and normal colors. -class name
button invoke Class name to use in querying the option database and for bindings.
Toggle the selection state of the checkbutton and invoke the Tcl command -colormap colormap
specified with -command, if any. Colormap to use for the window if different from parent.
-container boolean
Checkbutton Whether the frame will be a container to embed another application.
-visual visual
-activebackground -font -pady
Visual info to use for the window if different from parent.
-activeforeground -foreground -relief
-anchor -height -state
-background -highlightbackground -takefocus Label
-bitmap -highlightcolor -text
-anchor -height -pady
-borderwidth -highlightthickness -textvariable
-background -highlightbackground -relief
-command -image -underline
-bitmap -highlightcolor -takefocus
-cursor -justify -width
-borderwidth -highlightthickness -text
-disabledforeground-padx -wraplength
-cursor -image -textvariable
-font -justify -underline
-indicatoron boolean -foreground -padx -width
Whether or not the indicator should be drawn. -wraplength

33 34
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
-selectimage image
Image displayed in indicator when selected.
-value value
Menubutton
Value given to variable specified with -variable option when the
-activebackground -foreground -relief radiobutton is selected.
-activeforeground -height -state -variable variable
-anchor -highlightbackground-takefocus Variable to associate with radiobutton.
-background -highlightcolor -text
-bitmap -highlightthickness -textvariable radiobutton deselect
-borderwidth -image -underline Deselect the radiobutton.
-cursor -justify -width radiobutton flash
-disabledforeground -padx -wraplength Alternate radiobutton between active and normal colors.
-font -pady radiobutton invoke
Toggle the selection state of the radiobutton and invoke the Tcl command
-direction direction specified with -command, if any.
Where to pop up menu where direction is one of above, below, left, radiobutton select
right, and flush. Select the radiobutton.
-indicatoron boolean
If true then a small indicator will be displayed on the button’s right side and
Scale
the default menu bindings will treat this as an option menubutton.
-menu pathName -activebackground -highlightbackground -repeatdelay
Pathname of menu widget to post when button is invoked. -background -highlightcolor -repeatinterval
-borderwidth -highlightthickness -state
-cursor -orient -takefocus
Message -foreground -relief -troughcolor
-font
-anchor -highlightbackground -relief
-background -highlightcolor -takefocus
-borderwidth -highlightthickness -text -bigincrement number
-cursor -justify -textvariable A real value to use for large increments of the scale.
-font -padx -width -command tclCommand
-foreground -pady Specified a TCL command to invoke when scale’s value is changed. The
scale’s value will be appended as an additional argument.
-aspect integer -digits integer
Ratio of text width to text height times 100 to use to display text. An integer specifying how many significant digits should be retained.
-from number
A real value corresponding to left or top end of the scale.
Radiobutton
-label string
-activebackground -font -pady A string to display as label for the scale.
-activeforeground -foreground -relief
-length size
-anchor -height -state
Specifies the height (width) for vertical (horizontal) scales.
-background -highlightbackground -takefocus
-bitmap -highlightcolor -text -resolution number
-borderwidth -highlightthickness -textvariable Real value to which scale’s value will be rounded to an even multiple of.
-command -image -underline -showvalue boolean
-cursor -justify -width Whether or not scale’s current value should be displayed in side label.
-disabledforeground-padx -wraplength -sliderlength size
Size of the slider, measured along the slider’s long dimension.
-indicatoron boolean -sliderrelief relief
Whether or not the indicator should be drawn. Specify the relief used to display the slider.
-selectcolor color -tickinterval number
Color used to fill in indicator when selected. A real value to specify the spacing between numerical tick marks displayed.

35 36
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
-to number Toplevel
A real value corresponding to the right or bottom end of the scale.
-borderwidth -highlightbackground -relief
-variable variable -cursor -highlightcolor -takefocus
Name of a global variable to link to the scale. -height -highlightthickness -width
-width width
Narrow dimension of scale (not including border).
-background color
scale coords [value] Same as standard but my be empty to preserve colormap space.
Returns x and y coordinates of point corresponding to value. -class string
scale get [x y] Class name for the window to be used by option database.
If x y is given, returns scale value at that coordinate position. Otherwise, -colormap colormap
scale’s current value is returned. Color map to use for window. May be the word new, pathname of other
scale identify x y toplevel, or empty for the default colormap of screen.
Returns string indicating part of scale at position x y. Maybe one of -container boolean
slider, trough1, trough2 or empty. Whether toplevel is a container used to embed another application.
scale set value -menu pathName
Changes the current value of scale to value. Menu widget to be used as a menubar.
-use windowID
Scrollbar Toplevel should be embedded inside window identified by windowID (see
winfo id) which was created as a container.
-activebackground -highlightcolor -relief
-background -highlightthickness -repeatdelay -screen screen
-borderwidth -jump -repeatinterval Screen on which to place the window.
-cursor -orient -takefocus -visual visual
-highlightbackground -troughcolor Specifies visual to use for window.

-activerelief number 27. Images


Relief to use when displaying the element that is active.
-command tclCommandPrefix image create type [name] [options value ...]
Prefix of a Tcl command to invoke to change the view in the widget Creates new image of type with options and returns name.
associated with the scrollbar. image delete name
-elementborderwidth width Deletes the image name.
Width of borders around internal elements (arrows and slider). image height name
-width width Returns pixel height of image name.
Narrow dimension of scrollbar (not including border). image names
Elements: arrow1, trough1, slider, trough2, arrow2 Returns a list of the names of all existing images.
image type name
scrollbar activate [element]
Returns the type of image name.
Display element with active attributes.
image types
scrollbar delta deltaX deltaY
Returns a list of valid image types.
Returns fractional position change for slider movement of deltaX deltaY.
image width name
scrollbar fraction x y
Returns pixel width of image name.
Returns a real number between 0 and 1 indicating where the point given by
pixel coords x y lies in the trough area of the scrollbar. When an image is created, Tk creates a new command with the same name as the
scrollbar get image. For all image types, this command supports the cget and configure
Returns current scrollbar settings as the list {first last}. methods in the same manner as widgets for changing and querying configuration
options.
scrollbar identify x y
Returns name of element under pixel coords x y.
scrollbar set first last The bitmap Image Type
Describes current view of associated widget where first last are the -background color
percentage distance from widget’s beginning of the start and end of the view. Set background color for bitmap.

37 38
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
-data string -shrink
Specify contents of bitmap in X11 bitmap format. Will clip image so copied region is in bottom-right corner.
-file fileName -to x y
Gives name of file whose contents define the bitmap in X11 bitmap format. Specifies coords of the top-left corner in image to copy into.
-foreground color imageName redither
Set foreground color for bitmap. Redither the image.
-maskdata string imageName write fileName [option value ...]
Specify contents of mask in X11 bitmap format. Writes image data from image into file fileName.
-maskfile fileName -format format-name
Gives name of file whose contents define the mask in X11 bitmap format. Specifies image format for the file.
-from x1 y1 x2 y2
The photo Image Type Specifies a rectangular region of the image to copy from.
-data string
Specify contents of image in a supported format. 28. Window Information
-format formatName
Specify format for data specified with the -data or -file options. In winfo allmapped window
standard Tk, the GIF/PGM/PPM formats are supported. Returns 1 if window and all its ancestors are mapped, 0 otherwise.
-file fileName winfo atom [-displayof window] name
Specifies image data should be read from file fileName. Returns integer identifier for atom given by name on window’s display.
-height number winfo atomname [-displayof window] id
Fixes the height of the image to number pixels. Returns textual name of atom given by integer id on window’s display.
-palette paletteSpec winfo cells window
Set the resolution of the color cube to be allocated for image. Returns number of cells in the colormap for window.
-width number winfo children window
Fixes the width of the image to number pixels. Returns list containing path names of window’s children in stacking order.
imageName blank winfo class window
Blanks the image so has no data and is completely transparent. Returns the class name of window.
imageName copy sourceImage [option value ...] winfo colormapfull window
Copy a region from sourceImage to imageName using given options. Return 1 if the colormap for window is full, 0 otherwise.
-from x1 y1 x2 y2 winfo containing [-displayof window] rootX rootY
Specifies rectangular region of source image to be copied. Returns path name of window containing the point rootX rootY on window’s
-to x1 y1 x2 y2 display..
Specifies rectangular region of target image to be affected. winfo depth window
-shrink Returns the depth (bits per pixel) of window.
Will clip target image so copied region is in bottom-right corner. winfo exists window
-zoom x y Returns 1 if window exists, 0 if it doesn’t.
Magnifies source region by x y in respective direction. winfo fpixels window number
-subsample x y Returns floating-point value giving the number of pixels in window
Reduces source image by using only every x yth pixel. corresponding to the distance given by number.
imageName get x y winfo geometry window
Returns RGB value of pixel at coords x y as list of three integers. Returns the pixel geometry for window, in the form widthxheight+x+y.
imageName put data [-to x1 y1 x2 y2] winfo height window
Sets pixels values for the region x1 y1 x2 y2 for 2-D array data. Returns height of window in pixels.
imageName read fileName [option value ...] winfo id window
Reads image data from file fileName into image using given options. Returns a hexadecimal string indicating the platform identifier for window.
-format format-name winfo interps [-displayof window]
Specifies image format of file. Returns a list of all Tcl interpreters registered on window’s display.
-from x1 y1 x2 y2 winfo ismapped window
Specifies a rectangular region of the image file to copy from. Returns 1 if window is currently mapped, 0 otherwise.

39 40
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
winfo manager window winfo screenwidth window
Returns the name of the geometry manager currently responsible for Returns the width in pixels of window’s screen.
window. winfo toplevel window
winfo name window Returns the pathname of the top-level window containing window.
Returns window’s name within its parent, as opposed to its full path name. winfo visual window
winfo parent window Returns the visual class of window (see winfo screenvisual).
Returns the path name of window’s parent. winfo visualsavailable window
winfo pathname [-displayof window] id Returns a list whose elements describe the visuals available for window’s
Returns the path name of the window whose X identifier is id on window’s screen including class and depth..
display. winfo vrootheight window
winfo pointerx window Returns the height of the virtual root window associated with window.
Returns mouse pointer’s x coordinate on window’s screen.
winfo vrootwidth window
winfo pointerxy window Returns the width of the virtual root window associated with window.
Returns mouse pointer’s x and y coordinates on window’s screen.
winfo vrootx window
winfo pointery window Returns the x-offset of the virtual root window associated with window.
Returns mouse pointer’s y coordinate on window’s screen.
winfo vrooty window
winfo pixels window number Returns the y-offset of the virtual root window associated with window.
Returns the number of pixels in window corresponding to the distance given
winfo width window
by number, rounded to nearest integer.
Returns window’s width in pixels.
winfo reqheight window
winfo x window
Returns a decimal string giving window’s requested height, in pixels.
Returns x-coordinate of the upper-left corner of window in its parent.
winfo reqwidth window
Returns a decimal string giving window’s requested width, in pixels. winfo y window
Returns y-coordinate of the upper-left corner of window in its parent.
winfo rgb window color
Returns a list of the three RGB values that correspond to color in window.
winfo rootx window
29. The Window Manager
Returns the x-coordinate, in the root window of the screen, of the upper-left
corner of window (including its border). wm aspect window [minNumer minDenom maxNumer maxDenom]
winfo rooty window
Inform window manager of desired aspect ratio range for window.
Returns the y-coordinate, in the root window of the screen, of the upper-left wm client window [name]
corner of window (including its border). Store name in window’s WM_CLIENT_MACHINE property. Informs
winfo server window window manager of client machine on which the application is running.
Returns server information on window’s display. wm colormapwindows window [windowList]
winfo screen window Store windowList in window’s WM_COLORMAP_WINDOWS property
Returns the name of the screen associated with window, in the form which identifies the internal windows within window with private colormaps.
displayName.screenIndex. wm command window [value]
winfo screencells window Store value in window’s WM_COMMAND property. Informs window
Returns the number of cells in the default color map for window’s screen. manager of command used to invoke the application.
winfo screendepth window wm deiconify window
Returns the depth (bits per pixel) of window’s screen. Arrange for window to be mapped on the screen.
winfo screenheight window wm focusmodel window [active|passive]
Returns the height in pixels of window’s screen. Specifies the focus model for window.
winfo screenmmheight window wm frame window
Returns the height in millimeters of window’s screen. Returns the platform window identifier for the outermost decorative frame
winfo screenmmwidth window containing window. If window has none, returns platform id of window itself.
Returns the width in millimeters of window’s screen. wm geometry window [newGeometry]
winfo screenvisual window Changes geometry of window to newGeometry.
Returns the visual class of window’s screen. Maybe one of: wm grid window [baseWidth baseHeight widthInc heightInc]
directcolor, grayscale, pseudocolor, staticcolor, Indicates that window is to be managed as a gridded window with the
staticgray, or truecolor. specified relation between grid and pixel units.

41 42
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
wm group window [pathName] bindtags window [tagList]
Gives path name for leader of group to which window belongs. Sets the current precedence order of tags for window to tagList. If tagList is
wm iconbitmap window [bitmap] an empty list, the tags are set back to the defaults.
Specifies a bitmap to use as icon image when window is iconified. event add <<virtual>> sequence [sequence ...]
wm iconify window Arrange for virtual event <<virtual>>to be triggered when anyone of given
Arrange for window to be iconified. sequences occur.
wm iconmask window [bitmap] event delete <<virtual>> [sequence ...]
Specifies a bitmap to use to mask icon image when window is iconified. Deletes given sequences (or all if none given) from list that triggers the
virtual event <<virtual>>.
wm iconname window [newName]
Specifies name to use as a label for window’s icon. event generate window event [-when when] [option value ...]
Generate event in window as if it came from window system. Possible
wm iconposition window [x y]
options are listed in the Event Field table below. The -when option sets
Specifies position on root window to place window’s icon.
when the event will be processed. Possible values for when are:
wm iconwindow window [pathName]
now process immediately (default)
Sets path name of window to use as the icon when window is iconified.
tail place at end of event queue
wm maxsize window [width height]
head place at beginning of event queue
Specifies maximum size window may be resized to in each direction.
mark same as head but behind previous generated events
wm minsize window [width height]
event info [<<virtual>>]
Specifies minimum size window may be resized to in each direction.
Returns list of sequences that trigger virtual event <<virtual>>(if not given,
wm overrideredirect window [boolean] returns list of defined virtual events).
Set or unset the override-redirect flag of window commonly used by window
manager to determine whether window should decorative frame. The sequence argument is a list of one or more event patterns. An event pattern
wm positionfrom window [program|user] may be a single ASCII character, a string of the form
Indicate from whom the window’s current position was requested. <modifier-modifier-type-detail> , or <<name>>(virtual event).
wm protocol window [name] [command] Modifiers:
Specify a Tcl command to be invoked for messages of protocol name. Any Triple Button5, B5 Mod3, M3
wm resizable window [widthBoolean heightBoolean] Control Button1, B1 Meta, M Mod4, M4
Specifies whether window’s width and/or height is resizable. Shift Button2, B2 Mod1, M1 Mod5, M5
Lock Button3, B3 Mod2, M2 Alt
wm sizefrom window [program|user] Double Button4, B4
Indicate from whom the window’s current size was requested.
wm state window Types:
Returns current state of window: normal, icon, iconic, or Activate Enter Motion
withdrawn. ButtonPress, Button Expose Leave
ButtonRelease FocusIn Map
wm title window [string] Circulate FocusOut Property
Set title for window’s decorative frame to string. Colormap Gravity Reparent
wm transient window [master] Configure KeyPress, Key Unmap
Informs window manager that window is a transient of the window master. Deactivate KeyRelease Visibility
Destroy
wm withdraw window
Arranges for window to be withdrawn from the screen.
Details: for buttons, a number 1-5
for keys, a keysym (/usr/include/X11/keysymdef)
30. Binding and Virtual Events
Tags: internal window (applies to just that window)
bind tag toplevel window (applies to all its internal windows)
Returns list of all sequences for which a bindings exists for tag. window class name (applies to all widgets in class)
bind tag sequence all (applies to all windows)
Returns the script bound to the given sequence for tag. Event Fields:
bind tag sequence script Generate Option Code Valid Events
Binds script to the given sequence for tag. If script is the empty string, the -above window %a Configure
binding is deleted. If the first character of script is a +, then it is appended to -borderwidth size %B Configure
the currently associated script. -button number %b ButtonPress, ButtonRelease

43 44
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
-count number %c Expose
-detail detail %d Enter, Leave, Focus place forget window
-focus boolean %f Enter, Leave Unmanages window.
-height size %h Configure place info window
-keycode number %k KeyPress, KeyRelease Returns list containing current place configuration of window.
-keysym name %K KeyPress, KeyRelease
place slaves window
-mode notify %m Enter, Leave, Focus
Returns lists of slaves in the window master.
-override boolean %o Map, Reparent, Configure
-place where %p Circulate
-root window %R The grid Command
-rootx coord %X grid [configure] slave [slave ...] [option value ...]
-rooty coord %Y Sets how slave windows should be managed by grid geometry master.
-sendevent boolean %E all events
-column n -ipady amount -row n
-serial number %# all events
-columnspan n -padx amount -rowspan n
-state state %s all events
-in other -pady amount -sticky [n][s][e][w]
-subwindow window %S
-ipadx amount
-time integer %t , Property


-x coord %x ,
grid bbox master [column row [column2 row2]]


-y coord %y ,
Returns bounding box in pixels of space occupied by whole grid (no args),
the cell (2 args), or area spanning between given cells (4 args).
KeyPress, KeyRelease, ButtonPress, ButtonRelease,
Enter, Leave, Motion grid columnconfigure master columnList [options]
Set/query column properties of given columns in grid master.


Expose, Configure, Gravity, Reparent


-minsize size Minimum size of column.
-pad amount Padding to add to sides of largest slave.
31. Geometry Management -weight int Relative weight for apportioning extra space.
grid forget slave [slave ...]
The pack Command
Removes (and unmaps) each slave from grid forgetting its configuration.
pack [configure] slave [slave ...] [options] grid info slave
Sets how slave windows should be managed by pack geometry master. Returns list describing configuration state of slave.
-after sibling -in master -pady pixels grid location master x y
-anchor anchor -ipadx pixels -fill none|x|y|both Returns column and row containing screen units x y in master. If x y is
-before sibling -ipady pixels -side top|bottom|left|right outside grid, -1 is returned.
-expand boolean -padx pixels grid propagate master [boolean]
Set/query whether master tries to resize its ancestor windows to fit grid.
pack forget slave [slave ...] grid remove slave [slave ...]
Unmanages the given slave windows. Removes (and unmaps) each slave from grid remembering its configuration.
pack info slave
grid rowconfigure master rowList [options]
Returns list containing current pack configuration of window slave. Set/query row properties of given rows in grid master. Same options as for
pack propagate master [boolean] columnconfigure but for rows.
Enables or disables propagation for the window master. grid size master
pack slaves master Returns size of grid (as columns rows) for master.
Returns lists of slaves in the window master. grid slaves master [-row row] [-column column]
With no options, a list of all slaves in master is returned. Otherwise, returns
The place Command a list of slaves in specified row or column.
place [configure] window option value [option value ...]
Sets how given windows should be placed inside their master. Grid Relative Placement
-anchor anchor -relheight size -rely location
- Increases columnspan of slave to the left.
-height size -relwidth size -x location
-in master -relx location -y location x Leave an empty column.
-width size -bordermode inside|outside|ignore Extends the rowspan of slave above.

45 46
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
32. Fonts destroy [window window ...]
Destroy the given windows and their descendents.
font actual fontDesc [-displayof window] [option] focus [-force] window
Returns actual value for option used by fontDesc on window’s display. If Sets the input focus for window’s display to window. The -force option
option is not given, the complete option/actual value list is returned. cause the focus to be set even if another application has it.
font configure fontname [option [value option value ...]] focus [-displayof window]
Query/set font options for application created font fontname. Returns name of focus window on window’s display.
font create [fontname [option value ...]] focus -lastfor window
Create new application font fontname with given font options. Returns the window which most recently had focus and is a descendent of
window’s toplevel .
font delete fontname [fontname ...]
Delete given application created fonts. grab current [window]
Returns name of current grab window on window’s display. If window is
font families [-displayof window]
omitted, returns list of all windows grabbed by application.
Returns list of know font families defined on window’s display.
grab release window
font measure fontDesc [-displayof window] text
Releases grab on window.
Returns width in pixels used by text when rendered in fontDesc on window.
grab [set] [-global] window
font metrics fontDesc [-displayof window] [metric]
Sets a grab on window which will be local unless -global specified.
Query font metrics of fontDesc on window’s display where metric maybe be
grab status window
one of -ascent, -descent, -linespace, or -fixed. If metric is not
given, the complete metric/value list is returned. Returns none, local, or global to describe grab state of window.
lower window [belowThis]
font names
Places window below window belowThis in stacking order.
Returns list of application created fonts.
option add pattern value [priority]
Font Description: Adds option with pattern value at priority (0-100) to database.
1. fontname option clear
Name of font created by the application with font create. Clears option database and reloads from user’s Xdefaults.
2. systemfont option get window name class
Name of platform-specific font interpreted by graphics server. Obtains option value for window under name and class if present.
3. family [size [style ...]] option readfile fileName [priority]
A Tcl list with first element the name of a font family, the optional second Reads options from Xdefaults-style file into option database at priority.
element is desired size, and additional elements chosen from normal or raise window [aboveThis]
bold, roman or italic, underline and overstrike. Places window above window aboveThis in stacking order.
4. option value [option value ...] selection clear [-displayof window] [-selection selection]
A Tcl list of option/values as valid for font create. Clears selection (default PRIMARY) on window’s display.
Font Options: selection get [-displayof window] [-selection selection] [-type type]
-family name Font family (e.g. Courier, Times, Helvetica). Retrieves selection from window’s display using representation type.
-size size Size in points (or pixels if negative). selection handle [-selection sel] [-type type] [-format fmt] win cmd
Arranges for cmd to be run whenever sel of type is owned by win.
-weight weight Either normal (default) or bold.
selection own [-displayof window] [-selection selection]
-slant slant Either roman (default) or italic.
Returns path name of window which owns selection on window’s display.
-underline boolean Whether or not font is underlined. selection own [-selection selection] [-command command] window
-overstrike boolean Whether or not font is overstriked. Causes window to become new owner of selection and arranges for
command to be run when window later loses the selection.
33. Other Tk Commands send [-displayof window] [-async] interp cmd [arg arg ...]
Evaluate cmd with args in the Tk application interp on window’s display. If
bell [-displayof window] -async is specified, the send command will return immediately.
Ring the X bell on window’s display. tk appname [newName]
clipboard clear [-displayof window] Set the interpreter name of the application to newName.
Claim ownership of clipboard on window’s display, clearing its contents. tk scaling [-displayof window] [floatNumber]
clipboard append [-displayof win] [-format fmt] [-type type] data Set scaling factor for conversion between physical units and pixels on
Append data to clipboard on win’s display. window’s display where floatNumber is pixels per point (1/72 inch).

47 48
Tcl/Tk Reference Guide Tcl/Tk Reference Guide
tkwait variable varName -type buttonSet
Pause program until global variable varName is modified. One of abortretryignore, ok, okcancel,
tkwait visibility window retrycancel, yesno or yesnocancel.
Pause program until window’s visibility has changed. tk_optionMenu w varName value [value ...]
tkwait window window Creates option menu with name w consisting of the given values. The current
Pause program until window is destroyed. value is stored in global variable varName. Returns internal menu name.
tk_bisque tk_popup menu x y [entry]
Set default color palette to old bisque scheme. Post popup menu so that entry is positioned at root coords x y.
tk_chooseColor [option value ...] tk_setPalette color
Pops up dialog for user to choose color and returns choice. Options are: Changes the color scheme for Tk so the default background color is color
and other default colors are computed.
-initialcolor color Makes default choice color. tk_setPalette name color [name color ...]
Set the default color for the named options in the color scheme explicitly.
-parent window Makes window parent of dialog. Possible options are:
-title string Makes string title of dialog window. activeBackground highlightColor
tk_dialog topw title text bitmap default string [string ...] activeForeground insertBackground
Pops up dialog using toplevel window topw with a button for each string background selectColor
argument. Returns index of button user presses, starting from 0 for the disabledForeground selectBackground
foreground selectForeground
leftmost button. The index default specifies the default button. highlightBackground troughColor
tk_focusNext window
Returns the next window after window in focus order.
tk_focusPrev window
Returns the previous window before window in focus order.
tk_focusFollowsMouse
Change focus model of application so focus follows the mouse pointer.
tk_getOpenFile [option value ...]
Pops up dialog for user to choose an existing filename and returns choice.
Options are:
-defaultextension extension
String to append to filename if no extensions exists on chosen
filename.
-filetypes filePatternList
List of filepattern elements of the form
typeName {extension [extension ...]} [{macType ...}]
-initialdir directory Display files in directory.
-initialfile fileName Make default choice fileName.
-parent window Makes window parent of dialog.
-title string Makes string title of dialog window.
tk_getSaveFile [option value ...]
Pops up dialog for user to choose a filename and returns choice. Options are
same as for tk_getOpenFile.
tk_messageBox [option value ...]
Displays a message dialog and returns the unique symbolic name of button
pressed by user. Options are:
-default name Make button name the default.
-message string Display string as dialog’s message.
-parent window Makes window parent of dialog.
-title string Makes string title of dialog window.
-icon error|info|question|warning
Adds specified icon to dialog.

49 50
Tcl/Tk Reference Guide
Notes

Tk/Tcl Reference Guide Revision 8.0.3 c 1989,1997

51

You might also like