TCL TK Reference Guide
TCL TK Reference Guide
TCL TK Reference Guide
Applicable Versions:
Starting
TCL
TK
8.0p2
8.0p2
Contents
Fundamentals
Sect #
Section Title
1.1 Shells
1.2 System Variables
1.3 Syntax
1.4 Operators and Expressions
1.5 Pattern Globbing
1.6 Regular Expressions
1.7 Advanced Regular
Expressions
TCL
Sect #
Section Title
2.1 Arrays
2.2 Clock
2.3 Command Evaluation
2.4 Control Loops
2.5 Dictionary
2.6 Encodings
2.7 Event Loop Handlers
2.8 File Attributes
2.9 History
2.10 Input/Output
2.11 Interpreter Information
2.12 Interpreters
2.13 Lists
2.14 Namespaces
2.15 Packages
2.16 Procedures
2.17 Strings
2.18 Variables
TK
Sect #
Section Title
Sect #
3.1 Bindings and Events
4.1
4.2
3.2 Button Widget
3.3 Canvas Widget
4.3
3.4 Checkbutton
4.4
3.5 Clipboard and Selection 4.5
3.6 Console
4.6
3.7 Dialogs
Package
dde
http
msgcat
registry
resource
tcltest
Frame Widget
Geometry Management
Images
Label Widget
Labelframe Widget
Listbox Widget
Menu Widget
Menubutton Widget
Message Widget
Options and Resources
Panedwindow
Radiobutton Widget
Scale Widget
Scrollbar
Spinbox
Text Widget
Toplevel Window
Window Information
Index
Command Index
References:
1.
2.
3.
4.
Conventions
bold
italic
Denotes variable text such as files, variables, etc. Generally variable refers to the variable contents while
variableName refers to the name of the variable.
1 Fundamentals
1.1 Shells
Command
tclsh options
?fileName? ?arg
...?
Description
Tclsh is the non-graphical shell used to evaluate fileName. Without fileName, it runs interactively,
reading Tcl commands from stdin and printing command results and error messages to stdout. For
interactive sessions, .tclshrc (or tclshrc.tcl on the Windows) in the home directory of the user is
sourced before evaluating fileName. Valid options are:
-encoding name (Tcl 8.5+) Encoding of fileName.
wish options
?fileName? ?--?
?arg ...?
Wish is the Tk graphical shell for Tcl, which creates a widow at startup then evaluates fileName.
Without fileName or if the first arg is "--", it runs interactively, reading Tcl commands from stdin and
printing command results and error messages to stdout. For interactive sessions, .wishrc (or wishrc.tcl
on the Windows) in the home directory of the user is sourced before evaluating fileName.
-colormap new Use new private colormap instead of using the default colormap for the screen.
-display display Display and screen on which to display window
-encoding name (Tcl 8.5+) Encoding of fileName.
-geometry
geometry
-help
-name name
-sync
-use id
-visual visual
Description
Number of command line arguments not including the name of the script file.
argv
argv0
geometry
tcl_interactive
TCL Variables
Variable
auto_execs
auto_index
Description
(8.4+) Array of cmd locations as defined by auto_execok.
Array of procedures taken from package require commands for auto_load.
auto_noexec
auto_noload
auto_path
List of directories in which package looks for pkgIndex.tcl files when loading packages. Default
paths are: $env(TCLLIBPATH),$TCL_LIBRARY, $TCL_LIBRARY/.., and $tcl_pkgPath.
Search will also include all immediate subdirectories. Application specific directories can be
appended if necessary.
env(var)
Array where each element name is an enviroment variable. Typical env vars:
HOME
Users home directory
HOSTNAME
Name of machine
TZ
env(TCL_LIBRARY) If set, specifies the location of the directory containing library scripts.
env(TCLLIBPATH) If set, it must contain a valid Tcl list giving directories in Tcl format with "/" path separators to
search during auto-load operations. Used to initialize the auto_path variable.
errorCode
Set to contain a list of one or more elements based on the last Tcl error. Possible values are:
ARITH code msg
errorInfo
CHILDKILLED pid
sigName msg
CHILDSTATUS pid
Child process has exited with a non-zero exit status.
exitCode
CHILDSUSP pid
Child process has been suspended because of a signal.
sigName msg
NONE
No additional information is available.
POSIX errName msg
Error occurred during a POSIX kernel call.
Set to the lines of nested code (stack trace) that were being executed when the most recent error
occurred.
TCL_LIBRARY
Location of standard Tcl libraries used for auto loading procedures. Set to first dir the Tcl startup
script is found in from $env(TCL_LIBRARY ), compiled in default, location of app, or current
dir.
tcl_nonwordchars
(8.4+) Set to regular expression for control what are considered "nonword" characters (default is
anything but Unicode word character or Unicode space on Windows). Auto loaded by use of
tcl_endOfWord, etc.
Current patch level of Tcl interpreter.
tcl_patchLevel
tcl_pkgPath
List of directories to search for package loading. Typically it contains two directory entries for the
location of the platform-dependent and platform independent packages.
tcl_platform
tcl_precision
tcl_prompt1
Script to output a prompt. Tcl will call script instead of outputting normal prompt.
tcl_prompt2
Used in a similar way to tcl_prompt1 when a newline is typed but the current command isnt yet
complete. If tcl_prompt2 isnt set then no prompt is output for incomplete commands.
(8.4+) Startup Resouce filename.
(8.4+) Mac startup resource filename.
Level of tracing info (default is 0 or none) output during bytecode compilation. 1 is 1 line per
command, and 2 is detailed listing of bytecodes.
tcl_rcFileName
tcl_rcRsrcName
tcl_traceCompile
tcl_traceExec
Level of tracing info (default is 0 or none) output during bytecode execution. 1 is 1 line per
procedure call, 2 is 1 line per command, and 3 is detailed listing (per instruction).
tcl_version
tcl_wordchars
(8.4+) Set to regular expression for control what are considered "word" characters (default is
Unicode word character or anything but Unicode space on Windows). Auto loaded by use of
tcl_endOfWord, etc.
unknown_pending
TK Variables
Variable
Description
env(TK_LIBRARY) If set, specifies the location of the directory containing library scripts.
Location of standard Tk libraries used for auto loading procedures. Set to first dir the Tk startup
tk_library
script is found in from $env(TK_LIBRARY), compiled in default, location of Tcl library,
location of app, or current dir.
tk_patchLevel
tkPriv
tk::Priv
tk_strictMotif
tk_textRedraw
tk_textRelayout
tk_version
(8.4+) Set by text widgets when they have debugging turned on.
(8.4+) Set by text widgets when they have debugging turned on.
Current version of Tk interpreter in major.minor form.
1.3 Syntax
The following rules define the syntax and semantics of the Tcl language. There may be any number of variable
substitutions within a single word but each character is processed only once by the Tcl interpreter as part of creating the
words of a command. Substitutions will not affect the word boundaries of a command except for argument expansion. Any
well-formed list is also a well-formed command; where if evaluated, each element of the list will become exactly one word
of the command with no further substitutions. A Tcl script consists of one or more commands or comments.
Syntax
; or <newline>
Description
Command statement separator except within quotes or braces.
\<newline>
<white-space>
#
"$var"
Quoting with substitutions (command, backslash, and variable). Contents of quotes are
considered one word and substitutions will be performed by the interpreter. Requires a
space between groupings of quotes.
(Tcl 8.5+) Argument expansion. Removes {expand} then parses and substitutes the rest of
{expand}<non-whitespace> the word as any other other command word. After substitution, the word is parsed again
without substitutions, and its words are added to the command being substituted.
{$var}
[expr 2+3]
Command substitution. Evaluate the command and substitute the result. Interpreter does not
perform backslash or variable substitutions before evaluating the command or on the
results. Substitutions will occur during the command evaluation. Can be nested.
var
Simple variable. Variable name can consist of letters, digits, underscores, but cannot start
with a digit. Can include namespace qualifiers "::".
Associative array variable where index is element of array var. Same naming standards as
var.
Pseudo multi-dimensional array variable. Same naming standards as var.
Variable substitution. Replaces variable name with contents of variable without further
evaulation by the interpreter. Can include namespace qualifiers "::". Variable names are
case sensitive.
var(index)
var(a,b)
$var, $var(index)
${var}, ${var}($indexVar)
\<char >
\<space> space
\b backspace (0x08)
\\
backslash
\ooo
\n newline (0x0a)
\xhh
\r carriage return
(0x0d)
\uhhhh
\t horizontal tab
(0x09)
Type
Integer
Description
123 (dec with no preceeding zero), 0xff (hex), 0377 (octal has preceeding zero)
Floating
Point
Boolean
False = 0, false, no, off; True = true, 1, yes, on (All versions of expr, only Tcl 8.4+ supports non-values
for the Tcl parser)
Operators
The expr command recognizes the following operators, in decreasing order of precedence. Possible operands are numeric
values, Tcl variables (with $), strings in double quotes or braces, Tcl comands in brackets, and mathematical functions.
Operators Description
Validity
-+~!
unary minus, unary plus (Tcl 8.4+), bitwise NOT, logical NOT int, fp (except ~)
**
int, fp
*/%
int, fp (except %)
+-
add, subtract
int, fp
<< >>
int
== !=
eq ne
string
in ni
string, list
&
int
int
int
&&
||
x?y:z
int, fp
Math Functions
Math functions wil return an error if the result would cause an overflow.
Fn
abs(x)
Description
Absolute value
Fn
int(x)
Description
Integer portion of float
acos(x)
log(x)
asin(x)
atan(x)
Arc tangent
cos(x)
Cosine
sin(x)
Sine
cosh(x)
Hyperbolic cosine
sinh(x)
Hyperbolic sine
sqrt(x)
exp(x)
Exponential function
floor(x)
tan(x)
Tangent
tanh(x)
Hyperbolic tangent
wide(x)
Applicability
All
[abc]
All
[a-z]
All
\x
match character x used for *?[]\ (Tcl 8.1+ understands the special meaning of \a, \b, \f, \n, \r, \t, \v,
etc.)
All
All
glob only
~/
glob only
~user
glob only
Note: For the glob command, on UNIX a "." at the beginning of a files name or just after "/" must be matched explicitly
and all "/" characters must be matched explicitly.
Pattern
Description
regex|regex match either expression
regex*
regex+
regex?
\c
[abc]
[^abc]
[a-z]
[^a-z]
()
group expressions
Quantifiers
Quantifiers restrict the atom match to a subset of possible matches. The nominal qualifiers perfer the largest number of
matches and the non-greedy qualifiers perfer the smallest match. The forms using { and } are known as bounds. The
numbers m and n are unsigned decimal integers with permissible values from 0 to 255 inclusive.
Quantifier Non-Greedy Quantifier What Quantified Atom Matches
*
*?
+?
??
{m}
{m}?
{m,}
{m ,}?
{m,n}
{m,n}?
Atoms
Atom
Description
Greedy
Preference
(re)
(where re is any regular expression) matches a match for re, with the match noted for possible
reporting
same as RE
(?:re)
same as RE
()
same as RE
(?:)
same as RE
[chars] a bracket expression, matching any one of the chars (see BRACKET EXPRESSIONS for more
detail)
.
matches any single character
none
\k
none
\c
{
x
none
none
none
none
Simple Constraints
A constraint matches an empty string when specific conditions are met. A constraint may not be followed by a quantifier.
The lookahead constraints may not contain back references, and all parentheses within them are considered non-capturing.
An RE may not end with \.
Constraint Description
Greedy
Preference
none
$
(?=re)
none
(?!re)
Bracket Expressions
none
none
Expression
[abc]
[^abc]
[a-z]
[^a-z]
[.ch.]
Description
match set of characters such as [][{}-]
match characters not in set such as [^][{}-]
match range of characters. A character class may not be used as an endpoint of a range.
match characters not in range
a collating element (a character, a multi-character sequence that collates as if it were a single character, or a
collating-sequence name for either) (Note: Tcl currently has no multi-character collating elements.)
[[.ch.]]
a collating element within a set
[=e=]
equivalence class, standing for the sequences of characters of all collating elements equivalent to that one,
including itself. (Note: Tcl currently implements only the Unicode locale. It doesnt define any equivalence
classes.)
[=e=]
equivalence class within a set.
[:class:]
Any character in class. See Character Classes below.
[[:class:]] A character class within a set.
[[:<:]]
constraint matching empty strings at the beginning of word (word is [[:alnum:]_])
[[:>:]]
constraint matching empty strings at the end of a word (word is [[:alnum:]_])
Character Classes
Character classes are used to define a set of characters in a cross platform way. Tcl only supports Unicode classes.
Class
alnum
alpha
ascii
blank
Description
Unicode alphabet or digit characters
[[:alpha:][:digit:]]
Unicode alphabet characters
[[:lower:][:upper:]]
Characters [\u0000-\u007f]
(7-bit ASCII) (machine specific)
Space or tab characters (not used by string
is)
Class
integer
Description
Valid Tcl form of integer (string is only)
lower
punct
space
true
upper
false
wordchar
graph
xdigit
Character-Entry Escapes
Character-entry escapes (AREs only) exist to make it easier to specify non-printing and otherwise inconvenient characters
in REs.
Char Description
\a
alert or bell (0x07)
Char
\t
\b
backspace (0x08)
\uhhhh
\B
\f
\0
\n
newline (0x0A)
\oo
\r
\ooo
\cX
\e
Description
horizontal tab (0x09)
Class-Shorthand Escapes
Class-shorthand escapes (AREs only) provide shorthands for certain commonly-used character classes. Within bracket
expressions, \d, \s, and \w lose their outer brackets, and \D, \S, and \W are illegal.
Char
\d
\s
\w
Description
[[:digit:]]
[[:space:]]
[[:alnum:]_] (note underscore)
Char
\D
\S
\W
Description
[^[:digit:]]
[^[:space:]]
[^[:alnum:]_] (note underscore)
Constraint Escapes
A constraint escape (AREs only) is a constraint, matching the empty string if specific conditions are met. A word is defined
as in the specification of [[:<:]] [[:>:]]. Constraint escapes are illegal within bracket expressions. A back reference (AREs
only) matches the same string matched by the parenthesized subexpression specified by the number. The subexpression
must entirely precede the back reference in the RE. Subexpressions are numbered in the order of their leading parentheses.
Non-capturing parentheses do not define subexpressions.
Char Description
Char Description
\A matches only at the beginning of the
\Y matches only at a point that is not the beginning or end of a word
string whereas ^ also matches empty
string after a newline
\m matches only at the beginning of a word \Z
matches only at the end of the string whereas $ also matches empty
string before a newline
\M
\y
Metasyntax
Normally the flavor of RE being used is specified by application-dependent means. However, this can be overridden by a
director. An ARE may begin with embedded options: a sequence (?xyz) (where xyz is one or more alphabetic characters)
specifies options affecting the rest of the RE. These can supplement and/or override any options specified by the
application. Embedded options take effect at the ")" terminating the sequence. They are available only at the start of an
p
q
s
t
w
x
At the start of a RE, then the rest of the RE is to be taken to be a literal string, with all characters considered
ordinary characters.
rest of RE is a BRE
case-sensitive matching (usual default)
rest of RE is an ERE
case-insensitive matching (x becomes [xX] and [^x] becomes [^xX])
historical synonym for n
newline-sensitive matching ("." and bracket expressions using ^ will never match the newline character. $ and ^
will match the empty string before and after a newline in addition to at the end and beginning of a string
respectively)
partial newline-sensitive matching ("." and bracket expressions using ^ will never match the newline character.)
rest of RE is a literal ("quoted") string, all ordinary characters
non-newline-sensitive matching (usual default)
tight syntax (usual default; all characters are significant)
inverse partial newline-sensitive ("weird") matching ($ and ^ will match the empty string before and after a
newline in addition to at the end and beginning of a string respectively)
expanded syntax (see below)
Expanded Syntax
When selected by the -expanded switch or x option, white-space (blank, tab, newline, and [[:space:]]) and all characters
between a # and the following newline or end of RE are ignored. Exceptions are: when preceeded by a \, within a bracket
expression, and within multi-character symbols (illegal).
Comments
Outside bracket expressions, the sequence "(?#ttt)" (where ttt is any text not containing a ")") is a comment and will be
ignored. This syntax is deprecated in favor of the expanded syntax.
Matching
In the event that an RE could match more than one substring of a given string, the RE matches the one starting earliest in
the string. If the RE could match more than one substring starting at that point, its choice is determined by its preference:
either the longest substring, or the shortest. A branch has the same preference as the first quantified atom in it which has a
preference. An RE consisting of two or more branches connected by the | operator prefers longest match. Subject to the
constraints imposed by the rules for matching the whole RE, subexpressions also match the longest or shortest possible
substrings, based on their preferences, with subexpressions starting earlier in the RE taking priority over ones starting later.
Note that outer subexpressions thus take priority over their component subexpressions. Match lengths are measured in
characters, not collating elements. An empty string is considered longer than no match at all.
2 Tcl Commands
2.01 Arrays
Tcl arrays are associative arrays based on a hash table data structure. Elements of an array can consist of any string or
number unlike traditional array elements which are integers only. For the array commands below, arrayName is the name
of the array not the array contents (dont use variable substitution).
Command
array anymore
arrayName searchId
Description
Returns 1 if more elements are left to be processed in searchId of arrayName , 0 if none.
array donesearch
arrayName searchId
array exists
arrayName
Returns a list of all element and value pairs in arrayName or those matching pattern using
Pattern Globbing. The first is the element name and the second is the element value. If no match
then an empty string is returned.
array names
arrayName ?mode?
?pattern?
Returns a list of all element names in arrayName or those matching pattern. In Tcl 8.4+, mode
can be -exact (same string), -glob (default, using Pattern Globbing), or -regexp (using Regular
Expressions). If no match then an empty string is returned.
array nextelement
arrayName searchId
Returns name of next element inarrayName for the search searchId . Returns an empty string if
no more elements exist.
Sets values of one or more elements in arrayName from list in array get format.
array size arrayName Return number of elements in arrayName. If not an array then 0 is returned.
array startsearch
arrayName
array statistics
arrayName
array unset
arrayName ?pattern?
(Tcl 8.4+) Returns number of entries in the table, the number of buckets, and the utilization of the
buckets of the hash table that represents arrayName .
(Tcl 8.3+) Unsets all of the elements in arrayName or matching pattern using Pattern Globbing .
If arrayName is not an array or no match is found, an error is returned.
parray arrayName
?pattern?
Print to standard output the names and values of all elements in arrayName or matching pattern
using Pattern Globbing.
2.02 Clock
Tcl does not include any leap seconds in clock values, seconds are counted as if each UTC day has exactly 86400 seconds.
Tcl responds to leap seconds by speeding or slowing its clock by a tiny fraction for some minutes until it is back in sync
with UTC; its data model does not represent minutes that have 59 or 61 seconds.
UNIX and Windows NT Epoch is 1 January 1970, 00:00 UTC. This is the epoch for all systems in Tcl 8.5+.
Julian Epoch is 1 January, 4713 BCE of the proleptic Julian calendar
Command
Description
(Tcl 8.5+) Add all count unit (can be negative) conversions to integer clockValin the
specified order. Count is an integer of type unit. Unit is seconds, minutes, hours, days,
weeks, months, or years, or any of their unique prefixes. While leap days and Daylight
Savings Time are accounted for in the conversions, leap seconds are not. For ambiguious
times where the same local time occurs twice on the same day, the earlier time is used.
For impossible times (skipped hour for Daylight Savings Time, etc.), the time is
converted as if the clock had not changed.
-gmt boolean
-locale name
-timezone timeZone
clock clicks ?-option?
-microseconds
-milliseconds
If true, use GMT/UTC time zone, if false (default) use local time zone.
Specifies that conversions should be done according to the rules of locale name. Valid
names are: any valid locale supported by msgcat, "system" to use the current system
locale (from LC_TIME env var or Control Panel date/time on MS Windows), or {} to use
Tcls default locale (default for no -locale).
Specifies that conversions should be done according to the rules of Time Zone timeZone.
See Time Zones below for the valid time zones. The time zone preference order is:
-timezone or -gmt options, TCL_TZ env var, TZ env var, Control Panel time zone on MS
Windows, or the C language local time as defined by the localtime and mktime functions.
Returns hi-res system-dependent integer time value. In Tcl 8.5+, returned value is a wide
int. Options are:
(Tcl 8.5+) Return current time as system-dependent integer value of microsecondssince
"epoch".
(Tcl 8.3+) Return current time as system-dependent integer value of milliseconds since
"epoch".
Specifies the output format. See Clock Formats below for valid format fields. The default
format is "%a %b %d %H:%M:%S %Z %Y" prior to Tcl 8.5 and "%a %b %d
%H:%M:%S %z %Y" for Tcl 8.5+.
-gmt boolean
If true, use GMT/UTC time zone, if false (default) use local time zone.
clock microseconds
(Tcl 8.5+) Specifies that conversions should be done according to the rules of locale
name. Valid names are: any valid locale supported by msgcat, "system" to use the current
system locale (from LC_TIME env var or Control Panel date/time on MS Windows), or
{} to use Tcls default locale (default for no -locale). The current locale can be used with
-locale current.
(Tcl 8.5+) Specifies that conversions should be done according to the rules of Time Zone
timeZone. See Time Zones below for the valid time zones. The time zone preference
order is: -timezone or -gmt options, TCL_TZ env var, TZ env var, Control Panel time
zone on MS Windows, or the C language local time as defined by the localtime and
mktime functions.
(Tcl 8.5+) Return current time as system-dependent integer value of microsecondssince
"epoch".
clock milliseconds
-locale name
-timezone timeZone
Use integer clockVal (in seconds) as the base for date-relative conversions in dateString.
-format string
(Tcl 8.5+)Specifies the input format. See Clock Formats below for valid format fields.
-gmt boolean
If true, use GMT/UTC time zone, if false (default) use local time zone.
-locale name
-timezone timeZone
(Tcl 8.5+) Specifies that conversions should be done according to the rules of locale
name. Valid names are: any valid locale supported by msgcat, "system" to use the current
system locale (from LC_TIME env var or Control Panel date/time on MS Windows), or
{} to use Tcls default locale (default for no -locale).
(Tcl 8.5+)Specifies that conversions should be done according to the rules of Time Zone
timeZone. See Time Zones below for the valid time zones. The time zone preference
order is: %z or %Z formats, -timezone or -gmt options, TCL_TZ env var, TZ env var,
Control Panel time zone on MS Windows, or the C language local time as defined by the
localtime and mktime functions.
clock scan "dateString" ?-base Convert dateString to an integer clock value. If only a time is specified, current date is
clockVal? ?-gmt boolean?
assumed. Without time, midnight is assumed. Without time zone uses local zone unless
-gmt is specified. If -base is used, the date in clockVal is used for determining the time
on a specific day or other date-relative conversions (like daylight savings time for day or
greater units). Allowed range of years is 1902 to 2037. DateString consists of zero or
more specifications of the following forms:
time
Time of day form: "hh?:mm?:ss?? ?meridian? ?zone?" or "hhmm ?meridian?" ?zone? .
Without meridian, hh is interpreted on a 24-hour clock.
date
Month, day, year forms: "mm/dd?/yy?", "monthname dd?, yy?", "dd monthname ?yy?",
"day, dd monthname yy", "?CC?yymmdd" (Tcl 8.3+), "?CC?yy-mm-dd" (Tcl 8.3+),
"dd-monthname-?CC?yy" (Tcl 8.3+). Default yy is current year. If yy< 100, 00-38 is
2000-2038 (prior to Tcl 8.3), 00-68 is 2000-2068 (Tcl 8.3+), 69-99 is 1969-1999.
ISO-8601-point-in-time
(Tcl 8.3+) ISO 8601 format: "CCyymmddThhmmss", "CCyymmdd hhmmss", or
"CCyymmdd Thh:mm:ss".
relative time
Relative to current time. Format is number unit. Units are: year,fortnight, month, week,
day, hour, minute (or min ), and second (or sec) and their plurals, with modifiers:
tomorrow,yesterday, today, now, last, this, next, and ago. Daylight savings time
correction is applied only for day, week, fortnight, month, or year.
stardate float
(Tcl 8.3+) Returns time in Star Trek stardate floating point format.
now
Use current time
clock seconds
Return current time as system-dependent integer value of seconds since "epoch". In Tcl
8.5+, returned value is a wide int.
Clock Formats
Field
Description
Field
Description
Field
Description
%%
%j
%t
%a
Weekday (abbr)
%J
%T
%A
Weekday (full)
%k
%u
%b
Month (abbr)
%l
%U
%B
Month (full)
%m
Month (01-12)
%V
%c
%M
Minute (00-59)
%w
%C
%n
%W
%d
Day (01-31)
%N
%x
%D
%X
%e
%E#
%g
%G
for
%V (00-99)
(Tcl 8.4.7+) Year
for
%V (full)
%y
Year (00-99)
%Y
Year (full)
%Q
%z
%r
%p
Locale AM/PM
%P
%h
%R
%H
Hour (00-23)
%s
%I
Hour (01-12)
%S
Seconds (00-59)
where locale defaults are based on the environment variables LC_ALL and LC_TIME.
Time Zones
ahst - Alaska-Hawaii
Standard Time
ut - Universal (Coordinated)
bt - BaghdadTime, USSR
Zone 2
nft - NewfoundlandTime
wet - Western
EuropeanTime
nst - Newfoundland
StandardTime
nt - Nome Time
jt - Java Time
Description
Time Zone Acronym (see table above)
Locale Time Zone. Special case of :localtime (local time per C library).
For a complete listing, see:
"/no_backup/tools/lib/tcl8.5/clock/tzdata" for Non-UNIX or
"/usr/share/zoneinfo" for UNIX.
Examples
UTC, CDT
:UTC,
:America/New_York
+/-####
+/-######
Time Zone Offset in hours, minutes, and seconds (if six digits are present)
from UTC.
+0500, -063000
Use a plus sign for east of GMT and a minus sign for west of GMT.
Description
auto_execok cmd
Returns full pathname of cmd for use by exec if it exists in the dirs specified by
$env(PATH) or is built-in, otherwise returns an empty string. Only finds files with execute
bits set.
auto_import pattern
(Tcl 8.0.3+) Search auto_index array and forcably load procedures matching pattern. In
Tcl 8.3.4+, uses namespace import style matching.
auto_load cmd
Attempts to load the definition for cmd by searching $auto_path then
$env(TCLLIBPATH) for a tclIndex file which defines the location and script to loadcmd.
Returns 1 if successful, 0 if not.
auto_mkindex dir pattern
(Tcl 8.3+) Generate a tclIndex file from all files in the specified directory matching glob
?pattern ...?
patterns for use by auto_load.
auto_mkindex_old dir args (Tcl 8.3+, was auto_mkindex prior to 8.3) Generate a tclIndex file from all files in the
specified directory. Only procedures with "proc" at the beginning of a line (no leading
spaces) are included.
auto_reset
Destroys cached information used by auto_execok and auto_load.
bgerror message
(Undefined for TCL) User defined handler for background Tcl errors. Default for Tk is to
post dialog box with error message and ask if stack trace should be shown. The errorInfo
and errorCode variables are set to their values at the time the error occurred before calling
bgerror.
catch script
?resultVarName?
?optionsVarName?
Evaluate script and trap any errors. If there is an error, the non-zero error code (see return)
is returned and the error message is stored in resultVarName. If not, 0 (TCL_OK) is
returned with resultVarNameset to the value returned from the script. Within script,break
can be used to terminate the script. In Tcl 8.5+, optionsVarName is set to a dictionary of the
return options returned by evaluation of script. If the error code is TCL_RETURN, the
options dict will set -code and -level to values set by the return command. For all other
errors, -code will be set to the error code and -level will be 0. For TCL_ERROR, the dict
will also include -errorinfo (contents of ::errorInfo), -errorcode (contents of ::errorCode),
and -errorline (line of script where error occurred).
error message ?info? ?code? Interrupt command interpretation and pass back the error described in message. Global
variables errorInfo and errorCode will be set to info and code if defined.
exit ?returnCode?
Terminate the process, returningreturnCode (default is 0) to the system as the exit status.
UNIX limits range from 0 to 255.
Concatenates args with separators, evaluates the result as a Tcl expression, and returns the
value. See Operators and Math Functions for more info. Tcl 8.3.3+ allows for setting
variables via command substution within an expression. To do numeric comparisons, all
values must be numeric. To return a result in floating point format, at least one value must
be in floating point format. The precision is determined by the contents of the tcl_precision
variable. In TCL 8.0+, it is more efficient to group expressions within braces {} to let expr
perform substitutions. To compare strings, use quotes around the strings. In TCL 8.4+,
"nan" is recognized as Not a Number and "inf" or "infinity" is recognized as infinite.
Load binary code (shared library) for pkgName from fileName into interp (default is
current). If fileName is an empty string, Tcl uses pkgName to find matching statically
linked then dynamic library. Without pkgName, Tcl guesses the name.
Rename command oldName to newName. If newName is the empty string, command
oldName is deleted. Can include namespace qualifiers.
(Tk UNIX only) Evaluates command with args in the Tk application app (set with tk
appname command) on the same display and returns the result or command execution
error. Options are:
-async
-displayof window
source fileName
source
-encodingencodingName
fileName
Read file fileName and evaluate its contents as a Tcl script. Returns the return value of last
comand in script or error if one occurs. For MS Windows and all platforms in Tcl 8.4+, the
EOF is set to \x1a.
(Tcl 8.5+) Read file fileName in encoding encodingName (defult is system encoding) and
evaluate its contents as a Tcl script. Returns the return value of last comand in script or
error if one occurs. Default EOF is set to \x1a.
subst ?-nobackslashes?
?-nocommands?
?-novariables? string
tcl_findLibrary basename
version patch initScript
envVarName varName
Call interpreter count times (default is 1) to evaluate script. Returns string of the form "#
microseconds per iteration".
unknown cmdName ?arg
Called when the Tcl interpreter encounters an undefined cmdName. Default unknown calls
...?
auto_load then auto_exec to load or exec cmdName with args. If not successful and called
from top-level but outside of a script, it checks for csh like-history substitution forms of !!,
!event , or ^old^new?^?. If found it performs the history substitution. Lastly it checks if
cmdName is a unique abbreviation of an existing Tcl command and if so expands the
command name and executes it. If none were successful, an error is returned.
(Tcl 8.5+) Unload package pkgName from shared library filename previously loaded with
unload fileName ?pkgName? load from interp interp.Without interp, the current interp is used. Without pkgName, Tcl
?interp?
guesses the name in the same manner as load.
-nocomplain
-keeplibrary
Command
Description
break
Abort innermost loop (for, foreach, while, catch) or tag for a Tk binding script containing
command.
case
continue
Skip to the next iteration of innermost loop (for, foreach, while) or tag for a Tk binding
script containing command.
First evaluate start then repeatedly evaluate body then next if expr test returns a non-zero
result. If strings are used as operands in the expression, they must be quoted or in braces.
For each item in list, set varname to the items value and evaluate body.
If expr1 evaluates true, body1 is evaluated, otherwise if expr2 is true, body2 is evaluated,
etc. If none of the expressions evaluate to true then bodyN is evaluated. If strings are used
as operands in the expression, they must be quoted or in braces.
switch ?options? ?--? string For the first pattern that matches string , evaluate the corresponding body and return result.
pattern1 {body1} ?pattern2 If no pattern is matched and default is the last pattern, then its body is evaluated, otherwise
{body2} ...?
an empty string is returned. If body is set to " -", the body for the next pattern that isnt "-"
will be used. Options are:
-exact
-glob
-regexp
String must contain exactly the same string as pattern. This is the default option.
Compare patterns to string using Pattern Globbing.
Compare patterns to string using Regular Expression pattern matching.
(Tcl 8.5+) Used with -regexp, to specify the variable name to store the list of the matches
-matchvar varName
found by the regular expression engine. List args are same as the results stored to matchVar
and subMatchVars in regexp command. Will be set to empty list for default case.
(Tcl 8.5+) Used with -regexp, to specify the variable name to store the list of indices (same
-indexvar varName
form as regexp -indicies) referring to matching substrings found by the regular expression
engine (see -matchvar).Will be set to empty list for default case.
switch ?options? ?--? string Same as above except patterns and bodies are evaluated as a concatenated list of all patterns
{pattern1 body1 ?pattern2
and commands with no command or variable substitutions performed.
body2 ...?}
while {test} {body}
As long as expression test evaluates to true, evaluate Tcl command string body. If strings
are used as operands in the expression, they must be quoted or in braces.
2.05 Dictionary
Dictionaries are values that contain an efficient (but not order-preserving) mapping from arbitrary keys to arbitrary values.
They have a textual format that is exactly that of any list with an even number of elements (a.k.a. keyed list), with each
mapping in the dictionary being represented as two items in the list. In the commands below, dict is the contents of a
dictionary (variable substitution, etc.) and dictName is the name of a dictionary variable.
Command
Description
Appends string or strings to keys value in dictionary dictName. Non-existent keys are treated
as {}.
key pattern
script {keyVar
valueVar} script
value pattern
dict for {keyVar
valueVar}dict body
dict get dict ?key ...?
dict incr dictName key
?increment?
dict info dict
dict keys dict ?pattern?
dict lappend dictName
key ?value ...?
dict merge ?dict ...?
dict remove dict ?key
...?
dict replace dict ?key
value ...?
dict set dictName key
?key ...? value
dict size dict
Returns a new dictionary that contains each of the specified key and value mappings.
Returns 1 if dict contains key (or path of keys through a set of nested dictionaries) , or 0 if it
does not.
Returns a new dictionary that only contains the key/value pairs that match filterType in dict.
Valid filterTypes are:
Include elements where the key matches pattern using Pattern Globbing.
Include elements where the result of evaluating script is 1. Filtering is performed by looping
through each dict element and setting keyVar to the key and valueVar to the value then
evaluating script.If script returns TCL_BREAK, no further key/value pairs are checked or
included. TCL_CONTINUE is equivalent to a false result.
Include elements where the value matches pattern using Pattern Globbing.
Loop through each dict element and set keyVar to the key and valueVar to the value then
evaluating body. If body returns TCL_BREAK, no further key/value pairs will be iterated over.
TCL_CONTINUE is equivalent to TCL_OK.
Returns the value for key (or path of keys through a set of nested dictionaries) in dict. Without
key, a list of all key/value pairs in dict is returned. Non-existant keys return an error.
Increments the value of key by value (defaults to 1) in dictionary dictName.Non-existent keys
are treated as if they map to 0. An error is returned if keys value is not an integer.
Returns implementation specific info about dict.
Returns a list of all keys in dict matching pattern using Pattern Globbing. The keys are in an
arbitrary order. Without pattern, all keys are returned in the same arbitrary order as dict values.
Appends each value to keys list value in dictionary dictName.Non-existent keys are treated as
if they map to an empty list. An error is returned if keys value can not be represented as a list.
Returns a dictionary containing the contents of all dicts. For duplicate keys, only the value
from the last dictionary with key is used.
Returns a dictionary without keys.
Returns a dictionary that adds to or replaces each key and value pair in dict.
Sets (add or replace) the key (or path of keys through a set of nested dictionaries) in dictionary
dictName with value.
Returns the number of key/value mappings in dict.
Unsets (removes) the key (or path of keys through a set of nested dictionaries) in dictionary
dictName. At least one key must be specified, but the last key on the key-path need not exist.
Map each varName to key then evaluate and return the result of body. If a key does not exist,
then varName is unset.When done evaluating body, any changes made to the varNames are
reflected in dictionary dictName.
Returns a list of all values in dict matching pattern using Pattern Globbing. The values are in an
dict values dict ?pattern?
arbitrary order. Without pattern, all values are returned in the same arbitrary order as dict keys.
Map each key in dictionary dictName (or chain of nested dictionaries if one or more keys are
dict with dictName ?key
used) to a variable with the same name then evaluate and return the result of body. When done
...? body
evaluating body, any changes made to the variables are reflected in dictionary dictName.
2.06 Encodings
Command
Description
encoding convertfrom
?encoding? data
encoding convertto ?encoding?
string
encoding names
encoding system ?encoding?
(Tcl 8.1+) Convert data to Unicode from the specified encoding. Uses current system
encoding if not specified.
(Tcl 8.1+) Convert string from Unicode to the specified encoding. Uses current system
encoding if not specified.
(Tcl 8.1+) Return list of all available encodings.
(Tcl 8.1+) Set the system encoding to encoding. Returns current encoding if encoding
is not specified.
Common Encodings
Type:
Single Byte:
Double Byte:
unicode
big5 (chinese)
Variable Byte:
shiftjis
euc-jp
3 or more bytes:
Invalid
iso8859-1
symbol
utf-8
Description
after ms
after ms?arg1
arg2 ...?
after cancel ID
after cancel
arg1 arg2 ...
after idle ?arg1 Arrange for command (concat of args) to be evaluated later as an idle callback (TK is idle). Returns the
arg2 ...?
ID of the event handler created. Do not call another after idle from an after idle callback. Use after 0
instead.
after info ?ID? Returns information on event handler ID. With no ID, returns a list of all existing event handler IDs.
Each list entry contains two elements consisting of the script and event handler type.
tkwait variable (Tk only) Wait for global variable varName to be modified before proceeding. Does not block while
varName
waiting, but nested tkwaits must complete before outer wait can complete.
(Tk only) Waits for a change in the visibility state of window before proceeding. Can be used to wait for
tkwait visibility
a window to be created before taking action. Does not block while waiting, but nested tkwaits must
window
complete before outer wait can complete.
tkwait window
window
(Tk only) Waits for window to be destroyed before proceeding. Can be used to wait for a dialog to be
closed before taking action. Does not block while waiting, but nested tkwaits must complete before
outer wait can complete.
update
?idletasks?
Handle pending events including idle callbacks. If idletasks is specified, only those operations normally
deferred (idle callbacks, display updates, and window layout calcs) until the idle state are processed.
vwait varName
Enter Tcl event loop until global or fully qualified namespace variable or array varName is modified.
Will block if no events are ready and nested vwaits must complete before outer wait can complete.
Description
file atime
fileName?time?
Returns the time that fileName was last accessed as seconds since system epoch time. In Tcl 8.3+,
time sets last accessed time. On Windows, FAT file systems do not support access time.
file attributes
fileName ?option?
?option value? ...
Sets platform-specific attribute option to value for fileName. Without value, returns current value.
Without option, returns all options and values. Valid options are:
-archive boolean
-creator type
-group name
(UNIX) Group Name. Group ID can be used for set, but only names are returned.
-hidden boolean
(UNIX) Owner name. Owner ID can be used for set, but only names are returned.
(UNIX) Permissions in octal format. Tcl 8.3+ adds limited support for symbolic attributes like
chmod or an ls style string of the form rwxrwxrwx (must be 9 characters). Symbolic attribitutes
syntax is: [ugoa][+-=][rwxst],?...? where the comma separates multiple attributes.
Field
User,
Group,
Others
-permissions code
Set UID
Set GID
Sticky
File
r = view file contents, w =
modify file contents, x = execute
file
set user to files owner at
runtime
(s if x, S if no x)
Set group to files group at
runtime
(s if x, S if no x)
Directory
-readonly boolean
(Mac, Mac OS X (8.5+), BSD UNIX, MS Windows) Read-only or UNIX user immutable flag
-rsrclength length
(Tcl 8.5+ Mac. Mac OS X) Length of the resource fork of a file, can only be set to 0
-shortname
filename
-system boolean
-type type
file channels
?pattern?
file copy ?-force?
?--? source target
Copies each source file or directory to targetDir directory. If source is a directory, all files in
source will be recursively copied to targetDir. Will not overwrite existing files unless -force is
specified. Will stop at first error. Invalid operations are: overwrite non-empty directory, overwrite
directory with file, or overwrite file with directory.
Removes given files or directories. Use -force to remove non-empty directories. For symbolic
links, only the link will be deleted. Deleting a non-existent file is not considered an error. Args are
processed in the order specified, halting at the first error, if any.
file dirname
fileName
file executable
fileName
Returns 1 if fileName exists (and user can read its directory), 0 if not.
file extension
fileName
Returns all characters in fileName after and including the last dot.
file isdirectory
fileName
(Tcl 8.4+) Creates a link from linkName to target. Returns link filename without target. Options
are -symbolic or -hard.
Creates given directories with any needed parent directories. Trying to overwrite an existing file
with a directory will result in an error. Args are processed in the order specified, halting at the first
error, if any.
Returns the time that fileName was last modified as seconds since system epoch time. In Tcl 8.3+,
time option sets last modified time.
file nativename
fileName
file normalize
fileName
file owned fileName
(Tcl 8.4+) Returns a unique normalized (".." and "." are removed, symbolic links removed from
dirname but not tail) file-system absolute path representation of fileName .
Returns 1 if fileName owned by the user, 0 if not.
file pathtype
fileName
Returns path type of fileName: absolute (specific file on a specific volume), relative (relative to
the current working directory), or volumerelative (relative to the current working directory on a
specified volume or specific file on the current working volume).
Same as file stat except if fileName is a link, the status of the link is returned.
file readable
fileName
file readlink
fileName
Returns target filename of symbolic link given by fileName or an error if fileName is not a link or
can not be read.
file rename ?-force ? Renames source file or directory to target, moving it if the target pathname specifies a name in
?--? source target
another directory. The -force option forces overwriting of existing files.
Moves each source file or directory to targetDir directory. Will not overwrite existing files unless
file rename ?-force ?
-force is specified. Trying to overwrite a non-empty directory, overwrite a directory with a file, or
?--? source ?source
a file with a directory will all result in errors. Args are processed in the order specified, halting at
...? targetDir
the first error, if any.
file rootname
fileName
Returns all the characters in fileName up to but not including last dot (".").
file separator
?fileName?
file size fileName
(Tcl 8.4+) Without arg returns the char used to separate path segments for native files on this
platform. With arg does same for file system fileName is on.
Returns size of fileName in bytes.
Place results of stat kernel call on fileName in array varName with elements atime (last accessed
time), ctime (properties last updated time), dev (device),gid (group ID), ino (inode), mode
(permissions),mtime (last modified time), nlink (number of hard links), size (total size in
bytes),type (device type), and uid (user ID). All are decimal numbers except type, which is the
same as file type. For links, returns status on linked to file.
(Tcl 8.4+) Returns a two element list for fileName with the name of file system and nature or type.
Returns type of fileName. Possible values are file, directory, characterSpecial, blockSpecial,fifo,
link, or socket.
file volumes
Returns list of absolute paths of mounted volumes on system. Returns just "/" on UNIX, list of
local drives on Windows, and list of local and network drives on MacOS.
file writable
fileName
2.09 History
When specifying an event to the history command, event may be either:
1. A number: if positive, it refers to the event with that number (all events are numbered starting at 1). If the number is
negative, it selects an event relative to the current event (-1 refers to the previous event, -2 to the one before that, and
so on). Event 0 refers to the current event.
2. A string: selects the most recent event that matches the string. An event is considered to match the string either if the
string is the same as the first characters of the event, or match pattern using Pattern Globbing.
Command
Description
history
history add command ?exec?
history clear
Returns event number and contents of the last count events. Without count all events are
returned.
Set number of events to retain in history to count. Without count, returns current limit.
history nextId
Description
Repeats the previous command
Repeats command number n. If n is negative, it counts backward from the current command. The previous
command is -1.
Repeat the last command that starts with prefix.
Repeat the last command that matches pattern.
^old^new Replace all occurances of ols with new in the last command.
2.10 Input/Output
By default channelIDs stdin, stdout, and stderr are open. These channels are not available on all platforms since they are
not supported by the console.
Command
Description
cd ?dirName?
close channelId
eof channelID
exec
?-keepnewline?
?--? arg ?arg ...?
Redirection
|
Description
Pipe (stdout)
Redirection
>> fileName
Description
Append stdout to file
|&
2>> fileName
< fileName
>>&fileName
<@
channelID
>@channelID
<< value
> fileName
Stdout to file
2> fileName
Stderr to file
2>@1
&
// or \\
fblocked
Returns 1 if channelID does not have data available for reading, or 0 if it does.
channelID
fconfigure
Sets and retrieves options for channelID. Sockets are read-only. Options are:
channelID ?option
value ...? ?option
value ...?
Option:
Type:
all
Description:
-blocking
boolean
-buffering arg
all
-buffersize size
-encoding name
all
all
-eofchar char
-eofchar {inChar
outChar}
-error
all
all
-translation mode
all
-translation
{inMode
outMode}
-peername
all
socket
-sockname
socket
-handshake type
serial
-lasterror
serial
-mode baud,
parity, data, stop
-pollinterval
msec
-queue
serial
serial
-sysbuffer inSize
serial
(Tcl 8.4+ MS Windows) Change size of serial channel buffer. Default is 4096
bytes.
(Tcl 8.4+ MS Windows) Change size of input and output serial channel buffers.
Default is 4096 bytes.
-timeout msec
serial
-ttycontrol
{signal boolean
signal boolean ...}
-ttystatus
serial
(Tcl 8.4+ UNIX and MS Windows only) Set the timeout for blocking reads only.
For Unix systems the granularity is 100 milliseconds.
(Tcl 8.4+ UNIX and MS Windows only) Setup the handshake output lines or
send BREAK. Cannot be queried.
-xchar {xonChar
xoffChar}
serial
all
serial
fcopy inChID
outChID ?-size
size? ?-command
callback ?
fileevent
channelID option
?script?
serial
Whether I/O can block process. Default is to block. For MS Windows prior to
Tcl 8.4, serial I/O always blocks.
Arg is full, line, or none for buffer output. Default is full, except for channels
that connect to terminal-like devices where its line. stdin and stdout are initially
set to line, and stderr is set to none.
Size of buffer in bytes. Range is 10 to 1,000,000 bytes. Default is 4096 bytes.
(Tcl 8.1+) Channel encoding. See Encodings. (ASCII, UNICODE, UTF-8,
binary, etc.)
Sets read EOF marker. \x1a for DOS.
Sets read and write EOF marker. No args returns a two element list with the
current markers.
(Tcl 8.0.5+) Returns last POSIX error message associated with channel or empty
string if none.
Sets EOL marker. Modes are auto (default is native newline), binary (no EOL),
cr, crlf, and lf. Using binary implies -encoding binary.
Sets read and write EOLmarkers. Modes are auto (default is native newline),
binary (no EOL), cr, crlf, and lf. No args returns a two element list of in and out
modes.
For client or accepted sockets, returns a three element list with address, host
name, and port number to which the peer socket is connected or bound
Returns a three element list with address, host name, and port number for the
socket.
(Tcl 8.4+ UNIX and MS Windows only) Setup automatic handshake control
(none, rtscts, xonxoff, dtrdsr (MS Windows only)). Cannot be queried.
(Tcl 8.3+ MS Windows) Returns a list of error details. Can only be queried.
Set baud rate, parity (n, o, e, m, s), data bits (5 to 8), and stop bits (1 or 2) of
channel.
(Tcl 8.2+ Windows) Max time between polling for fileevents. Default is 10
msec.
(Tcl 8.4+ UNIX and MS Windows only) Returns a two element list of bytes in
input and output buffers. Can only be queried.
(Tcl 8.4+ UNIX and MS Windows only) Returns a list of modem status and
handshake input signals as a list of signal,value pairs.Can only be queried.
(Tcl 8.4+ UNIX and MS Windows only) Query or change the software
handshake chars. Default should be DC1 (0x11) (XON) and DC3 (0x13)
(XOFF).
Copy data from inChID to outChID until eof or size bytes are transferred. With -command, the copy
runs in background and calls callback with args of bytes copied and an error message, if applicable,
when done. Blocks without -command. In Tcl 8.4+, respects channel encodings.
Create handler to evaluate script at global level when channelID becomes option (readable or
writable). Replaces the existing handler if present. The handler is deleted if script is an empty string,
when the channelID is closed, or if the handler returns an error (bgerror will be called). Script needs
to account for eof. Returns current script if script is not specified.
flush channelID
gets channelID
?varName?
pid ?channelID?
puts ?-nonewline
? ?channelID?
string
pwd
Description
Read only
WRONLY
Write only.
APPEND
CREAT
EXCL
NOCTTY
w+
Read/write. Truncate
fileName, if exists.
a+
POSIX
Read/write.
TruncatefileName if it exists.
Return a list of process IDs, in order, for pipeline process channelID. Without channelID, returns
process ID of interpreter process.
Write string to channelID (default is stdout). Omit newline with -nonewline. Newline is based on
fconfigure -translation for channelID.
Returns the current working directory. Guaranteed to be the unique normalized string representation
of the path in Tcl 8.4+.
read ?-nonewline? Read all remaining data from channelID, optionally discarding last character if it is a newline.
?channelID?
read channelID
numChars
seek channelID
offset ?origin?
Read numChars (byte size depends on encoding) or remaining if less available from channelID. For
serial ports, if numChars is not specified will read until EOF.
Change current access position for channelID to offset bytes from origin. Origin options are: start
(default), current, or end.
Open a read/write client-side TCP socket to server host on port and returns the channel ID. The local
host can be specified with localhost. Options are:
Make connection asynchronous.
Set network address of client (if multiple available). Default is system specific.
Set connection port of client (if different from server). Default is random port.
Open server TCP socket on port. For each connection made, invoke command with three args: the
channel, client address, and client port number. If port is 0, the OS will use an unassigned port.
Sets the network address of server to addr.
Returns current access position for channelID in bytes.
Command
Description
info cmdcount
Returns the total number of commands that have been invoked in this interpeter.
info commands ?pattern? Returns list of all Tcl commands (built-ins and procs) in current namespace or those
matching pattern using Pattern Globbing.
info complete command
info default procName arg Returns 1 if procedure procName has a default for argument arg and places the value in
varName
variable varName. Returns 0 if there is no default.
info exists varName
(Tcl 8.4+) Returns list of all math functions or those matching pattern using Pattern
Globbing .
Returns list of all global variables or those matching pattern using Pattern Globbing.
info hostname
Returns the invoking procedure stack level or if number is specified, a list of the name and
args of procedure call at level number on the stack. info level 0 returns the curent proc name
and args.
Returns name of library directory where standard Tcl scripts are stored. Same as variable
TCL_LIBRARY.
info library
info loaded ?interp?
Returns list of all packages loaded or just those in interp if specified. Each list element
consists of the source filename and package name.
Returns list of all local variables or those matching pattern using Pattern Globbing.
info nameofexecutable
Returns full pathname of binary from which the application was invoked.
info patchlevel
Returns list of all Tcl procedures in current namespace or those matching pattern using
Pattern Globbing.
Returns name of Tcl script currently being evaluated (by source), if any. In Tcl 8.4+, if
filename is specified, the return value of info script is set to filename.
info sharedlibextension
info tclversion
Returns list of all currently-visible variables or those matching pattern using Pattern
Globbing.
(Tcl 8.4+) Allows control of the Tcl memory debugging capabilities. Tcl must be compiled
with memory debugging enabled. Options are:
Output a list of all currently allocated memory (with associated tags) to file.
break_on_malloc count
After count allocations, Tcl will output a break message and SIGINT to the C debugger.
info
init fn
Reurns the total number of allocations and frees, current packets allocated, current bytes
allocated, and the maximum number of packets and bytes allocated.
Turn on or off the pre-initialization of all allocated memory with bogus bytes.
onexit file
Output a list of all currently allocated memory (with associated tags)to file at Tcl exit.
tag string
Turn on or off the output to stderr of memory tracing info. Each ckalloc or ckfree outputs: fn,
address, size, C filename of calling procedure, and line in file.
trace_on_at_malloc count After count allocations, Tcl will enable memory tracing.
trace fn
validate fn
Turn on or off memory validation (if the ckalloc or free overwrite another allocated portion
of memory).
2.12 Interpreters
Command
Description
Returns list whose elements are the targetCmd and args associated with the alias
srcCmd in interpreter srcPath.
Creates an alias srcCmd in interpreter srcPath which when invoked will run
targetCmd and args in the interpreter targetPath . In targetPath , the current
interpeter is {}.
Returns a list of all alias source commands defined in the interpreter identified by
path .
(Tcl 8.5+) Sets the command (in list format) to handle background errors in the path
interp. Without cmdPrefix, the currently registered command, if any, or the
background error handler (defined by bgerror), will be returned. When an error
occurs in path interp and it cannot be reported up the procedure stack, the returned
error message and dictionary of return options (see catch) will be appended to
cmdPrefix and the new command will be evaluated by the Tcl Interpreter.
Creates a slave interpreter (optionally safe) identified by path with a slave name
obtained by removing the last component from path .
Deletes the interpreters defined by the path args and all their slave interpreters.
interp hide path exposedCmdName Make exposedCmd in interppath hidden (optionally as hiddenCmd Name).
?hiddenCmdName?
interp hidden path
interp invokehidden path ?options? Invokes hiddenCmdName with specified args in interp path at the current call frame
?--? hiddenCmdName ?arg ...?
and can access local variables in that and outer call frames.
-global
-namespace namespace
Invokes hidden command at the global level in the target interpreter. Overrides
-namespace.
(Tcl 8.5+) Invokes hidden command in the specified namespace in the target
interpreter
(Tcl 8.5+) Set or query the resource limit limitType for the interp path. Without
value, the current value is returned. Without option, the current config of limitType
is returned. The two kinds of limitTypes, command and time. Command restricts
the total the total number of Tcl commands that may be executed by an interpreter
(using info cmdcount) and time limits the total execution time (using time) of the
interpreter. When the limit for an interpreter is exceeded, the -command callback is
evaluated, if defined. If the limit is still in force, an error is generated to the
interpreters invoking command. Valid options are:
Specifis the Tcl script to eval in the global namespace of the interpreter reading and
writing the option when the particular limit in the limited interpreter is exceeded.
The callback may modify the limit to allow the interpreter to continue executing. If
the callback generates an error, it is reported through the background error
mechansism (see interp bgerror or bgerror)
-granularity
-milliseconds
-seconds
-value
interp issafe ?path?
Marks interp path as trusted. Does not expose the hidden commands.
(Tcl 8.4+) Returns the max allowable nesting depth for the interpreter path . If
newlimit is defined, the recursion limit is set to it.
Sets the I/O channel channelID in interpreter srcPath to be shared with interpreter
destPath .
Returns list of names of all slave interpreters of interpreter path. If path is omitted,
the invoking interpreter is used.
::safe::interpCreate ?slave?
?option arg...?
-accessPath directoryList
Creates a safe interpreter, installs the specified aliases, and initializes the
auto-loading and package mechanism. Without slave, returns the interpreter name.
Sets the list of directories from which the safe interpreter can source and load files.
For the default option or if set to an empty list, the safe interpreter will use the same
directories as its master for auto-loading.
-statics boolean
(Tcl 8.0p1+) Specifies if the safe interpreter will be allowed to load statically linked
packages. Default is true.
-noStatics
Convenience shortcut for -statics false.
-nested boolean
(Tcl 8.0p1+) Specifies if the safe interpreter will be allowed to load packages into
its own sub-interpreters. Default is false.
-nestedLoadOk
convenience shortcut for -nested true.
-deleteHook script
Evaluate script in the master just before deleting a safe interpreter. Passes name of
slave interpreter as arg to script. For the default option or if set to an empty string,
the current script is removed for current safe interpreter.
::safe::interpInit slave ?option
Similar to interpCreate except it that does not create the safe interpreter. slave
arg...?
must have been created by some other means, like interp create -safe. Uses same
options as ::safe::interpCreate.
::safe::interpConfigure slaveoption Sets option to specified arg for interpreter slave. Without args, returns setting
arg ...?
foroption. Without options, returns current interpreter settings. Uses same options
as ::safe::interpCreate.
?
::safe::interpDelete slave
::safe::interpAddToAccessPath
slave directory
Slave Interpreters
For each slave interpreter created with the interp command, a new Tcl command is created in the master interpreter with
the same name as the new interpreter. This command may be used to invoke various operations on the interpreter. The
following commands are used like interp, but without the srcPath or path (defaults to the slave itself) and the targetPath
arguments (defaults to the slaves master).
alias
aliases eval
hide
issafe marktrusted
eval
append
interp
package
string
pid
subst
expr
join
array
fblocked
lappend
proc
switch
binary
break
fcopy
lassign
puts
tell
fileevent
lindex
read
time
case
flush
linsert
regexp
trace
catch
for
list
regsub
unset
clock
foreach
llength
rename
update
close
concat
format
gets
return
scan
up level
upvar
continue
global
lrange
lrepeat
lreplace
seek
variable
if
lsearch
set
vwait
eof
incr
lsort
split
while
error
info
namespace
dict
exec
fconfigure
glob
open
socket
encoding
exit
file
load
pwd
source
auto_load
auto_qualify
auto_import
auto_load_index
unknown
auto_mkindex
::safe::interpAddToAccessPath
tcl_endOfWord
auto_mkindex_old
::safe::interpCreate
tcl_findLibrary
auto_reset
::safe::interpConfigure
tcl_startOfNextWord
history
::safe::interpDelete
tcl_startOfPreviousWord
parray
::safe::interpFindInAccessPath
tcl_wordBreakAfter
pkg_mkIndex
::safe::interpInit
tcl_wordBreakBefore
::pkg::create
::safe::setLogC
file ?subCmd
args ...?
encoding
?subCmd args
...?
exit
Description
Sources fileName into the safe interpreter. Only files in directories included in the virtual path for the
safe interpreter can be used. Requires the safe interpreter to use one of the token names in its virtual path
to denote the directory in which the file to be sourced can be found.
Loads a shared object file fileName into the safe interpreter. The filename must contain a token name
mentioned in the virtual path for the safe interpreter for it to be found successfully. The shared object file
must contain a safe entry point.
Provides access to a safe subset of the subcommands of the file command. Only dirname, join
,extension,root,tail,pathname, and split subcommands are accessible.
Provides access to a safe subset of the encodingsubcommands. The system encoding cannot be changed,
but all other subcommands are accessible.
The calling interpreter is deleted and its computation is stopped, but the Tcl process in which this
interpreter exists is not terminated.
2.13 Lists
A special case of string which consists of a series of elements which can be indexed like an array starting with 0. Elements
may contain strings, numbers, etc. If spaces or other special characters are used they must grouped within braces or use
backslash substitution as required. Elements may consist of nested sublists, which can contain more sub-lists, etc. to any
depth. Common definitions for strings as lists:
Definition
Well Formed List
Canonical List
Nested List
Input
Criteria
Result
string s
string equal "{$s}" [list $s] returns 1
well formed list s
string equal $s [split$s]
returns 1
list [list 1a 1b] [list 2a 2b] ...
The list arguments of index, first, and last can be replaced with end to use the index of the last element in list . For the list
commands below, list is the contents of the list (use variable substitution, i.e. $listName) and listName is the name of the
list.
Command
Description
Returns concatenation of args into a single list while trimming leading and trailing spaces. Removes
one level of grouping before forming list.
join list
?joinString?
Returns string created by joining all elements of list with joinString (default is space) separating each
element.
lappend
listName ?value
...?
lassign list
varName
?varName ...?
lindex list ?index
...?
(Tcl 8.5+) Assigns successive elements from list to the variables given by the varName args and
returns unassigned list elements. If ther are more var args then list elements, unused vars are set to {}.
Returns value of element at index in list. In Tcl 8.1.1+, index can be end-# (where # is an integer) for
the last element minus the specified number. In Tcl 8.4+, multiple indicies may be used (in list or
indivdual args format) for sub-lists (nested list) of list in highest to lowest depth order. Without index,
returns contents of list. Invalid indicies return {}.
linsert list index Returns new list by inserting elements at index in list. Inserts at beginning of list for index <= 0 and at
element ?element end of list for index of end or index > elements in list. In Tcl 8.1.1+, index can be end-# (where # is an
...?
integer) for the last element minus the specified number.
list ?arg arg ...?
Returns new list formed by using each arg as an element. Does not alter grouping. Prior to Tcl 8.5, list
does not quote leading #s in an eval safe manner.
llength list
Returns new list consiting of list elements first through last, inclusive. If first <= 0 then 0 is used and if
last > elements in list, then end is used. Returns empty list if first > last. In Tcl 8.1.1+, first and last
can be end-# (where # is an integer) for the last element minus the specified number.
lrepeat number
element
?element ...?
(Tcl 8.5+) Creates a list of elements repeated number of times where number is >= 0.
lreplace list first Returns new list formed by replacing elements first through last in list with elements. If first <= 0 then
last ?element ...? 0 is used and if last > elements in list, then end is used. If first < last < 0, then new elements will be
prepended to the list. If first > last, new elements are inserted before first. Without element args,
elements between first and last are deleted. If list is empty, elements are added to the end of the list. In
Tcl 8.1.1+, first and last can be end-# (where # is an integer) for the last element minus the specified
number.
lsearch
?options? list
pattern
Returns index of first element in list that matches pattern (-1 for no match). Mutually exclusive options
where last specified is used: -exact, -glob, -regexp , and -sorted; -ascii, -dictionary, -integer , and
-real; -increasing and -decreasing. Options are:
-all
(Tcl 8.4+) Returns list of all matching indices or all matching values if used with -inline. Returns
empty list if no matches are found.
-ascii
(Tcl 8.4+) Compare to elements as ASCII strings (alphabetical, case sensitive). Used with -exact or
-sorted.
-decreasing
(Tcl 8.4+) Elements are in decreasing order. Used with -sorted.
-dictionary
(Tcl 8.4+) Compare to elements using dictionary-style (alphabetical, case insensitive) comparisons.
Used with -exact or -sorted.
-exact
The list element must contain exactly the same string as pattern.
-glob
Compare to elements using Pattern Globbing. This is the default option.
-increasing
(Tcl 8.4+) Elements are in increasing order. Used with -sorted.
(Tcl 8.5+) Treat list elements as sublists (nested lists) and only searches in the sub-element specified
-index indexList
by indexList in highest to lowest depth order.
-inline
(Tcl 8.4+) Returns matching value instead of index or empty string if no match. If used with -all , a list
of all matched values is returned.
-integer
(Tcl 8.4+) Compare to elements as integers (numeric). Used with -exact or -sorted.
-not
-real
-regexp
-sorted
-start index
-subindicies
(Tcl 8.4+) Negates match criteria. Index of first non-matching element will be returned.
(Tcl 8.4+) Compare to elements as floating point values. Used with -exact or -sorted.
Compare to elements using Regular Expression pattern matching. Prepend (?i) to exp for case
insenstive.
(Tcl 8.4+) Specifies that the list elements are in sorted order, so use a more efficient search algorithm.
Default options are: -exact, -ascii, and -increasing . Can not be used with -all, -glob, -not or -regexp .
(Tcl 8.4+) Start search at index .
(Tcl 8.5+) Used with -index to return a listof subindicies for the matching element in highest to lowest
depth order.
lset listName
?index...?
newValue
lsort ?options?
list
-ascii
-command cmd
arg arg
-decreasing
-dictionary
(TCL 8.4+) Replaces element at index in list listName with newValue and returns the new list. Without
index replaces all of list with newValue. Index can be end-# (where # is an integer) for the last element
minus the specified number.Multiple indicies may be used (in list or indivdual args format) for
sub-lists (nested list) of list in highest to lowest depth order. An error is returned if index < 0 or index >
number of elements in list.
Returns new list formed by sorting list according to options:
2.14 Namespaces
Namespaces are used to partition a collection commands and variables from another collection so they dont interfere with
each other. Namespace variables resemble global variables in Tcl. They exist outside of the procedures in a namespace but
can be accessed in a procedure via the variable command. Namespaces are denoted by namespace :: variable where
variable can be a nested namespace and variable such as namespace :: namespace ::variable. The global namespace holds
all global variables and commands. The global namespace is "" (empty string) but is denoted by :: .
Command
Description
auto_qualify cmd namespace (Tcl 8.0p1+) Computes a list of fully qualified names for cmd in namespace then the
global namespace.
namespace children
Returns list of all child namespaces belonging to namespace (default is current) or match
?namespace? ?pattern?
pattern using Pattern Globbing.
namespace code script
Returns a new script, that when evaluated will cause script to be evaluated in the current
(where namespace code was invoked) namespace. Useful for callbacks. Additional args
can be passed to script by appending to the new script when evaluated.
namespace current
namespace delete
?namespace ...?
Each namespace is deleted along with any child namespaces, procedures, and variables. If
a procedure is currently executing in namespace, it will be deleted when the procedure
returns.
(Tcl 8.5+) Creates a new ensemble command linked to the current namespace, returning
the fully qualified name of the command created. Valid options are:
-command command
?arg...?
Specifies a dictionary to use for mapping from subcommand names to a list of prefix
words to use in place of the ensemble command and subcommand words. Default is to
map from the local name of the subcommand to its fully-qualified name.
Specifies whether the ensemble command recognizes unambiguous prefixes of its
-prefixes boolean
subcommands (default) or only exact matches.
Specifies valid ensemble subcommands. Default is to use the keys of the dictionary per the
-subcommands list
-map option or the exported commands of the linked namespace at the time of the
invocation of the ensemble command.
Specifies the command to append unknown ensemble sub-commands and eval in the scope
of the attempted call. Default is to generate an error like Tcl_GetIndexFromObj. The
-unknown command ?arg...? command must return either a list of command words to replace the ensemble command
and subcommand like -map, or an empty list. The latter will result in an attempt to eval the
ensemble sub-command again and if unsuccessful will generate an error like the default
case.
(Tcl 8.5+) Change the ensemble option to value. Without value, the current value is
namespace ensemble
configure command ?option? returned. Without option, a list of all available options for the ensemble is returned. Valid
options are:
?value ...?
-map dict
-map dict
-namespace
-prefixes boolean
-subcommands list
Specifies a dictionary to use for mapping from subcommand names to a list of prefix
words to use in place of the ensemble command and subcommand words. Default is to
map from the local name of the subcommand to its fully-qualified name.
Returns the fully-qualified name of the namespace in which the ensemble was created.
Specifies whether the ensemble command recognizes unambiguous prefixes of its
subcommands (default) or only exact matches.
Specifies valid ensemble subcommands. Default is to use the keys of the dictionary per the
-map option or the exported commands of the linked namespace at the time of the
invocation of the ensemble command.
Specifies the command to append unknown ensemble sub-commands and eval in the scope
of the attempted call. Default is to generate an error like Tcl_GetIndexFromObj. The
command must return either a list of command words to replace the ensemble command
-unknown command ?arg...?
and subcommand like -map, or an empty list. The latter will result in an attempt to eval the
ensemble sub-command again and if unsuccessful will generate an error like the default
case.
namespace ensembleexists
command
namespace eval namespace
arg ?arg ...?
namespace exists namespace (Tcl 8.4+) Returns 1 if namespace is valid in current context, 0 if not.
namespace export ?-clear? Appends commands matching pattern (without namepsace qualifiers)using Pattern
?pattern...?
Globbing to export list of current namespace. If -clear is given, the export list is first
emptied. Without any args, the current namespaces export list is returned.
namespace forget ?pattern
...? ?namespace::pattern ...?
Removes from current namespace any previously imported commands matching pattern
using Pattern Globbing or from exported namespace namespace.
namespace import ?-force? Imports into current namespace commands matching pattern using Pattern Globbing from
?namespace::pattern...?
namespace . The -force option allows replacing of existing commands.
namespace inscope
namespace listArg ?arg ...?
Activates namespace (which must already exist) and evaluates inside it the result of
lappend listArg args.
namespace origin command Returns fully-qualified name of original command that imported command refers to.
namespace parent
?namespace?
Returns the simple name (without leading namespace qualifiers) for string.
namespace which
?-command?
?-variable?name
Returns fully-qualified name of the command (default) or variable (if -variable used)
name in the current namespace. Will look in global namespace if not in current namespace.
Returns empty string if doesnt exist.
Creates name variables in current namespace (if unqualified) initialized to value (default is
to leave undefined for new vars or current value for existing vars). Name can reference an
array but not an element in an array. In this case value should not be used. Used inside a
procedure but outside of an namespace eval, a local variable is created linked to the given
namespace variable.
2.15 Packages
Packages are used to partition subroutines or entire programs into portable packages that can be used in other applications
or subroutines. Each package can contain a version in Major.Minor?.subreleases...? format where only versions with the
same major version are assumed to be compatible. Packages are indexed using the pkg_mkIndex command.
Command
Description
Tells interpreter that evaluating script will provide version of package. Without script,
current script for version of package is returned or empty string if none.
package names
Returns list of all packages in the interpreter that are currently provided or have an
ifneeded script available.
(Tcl 8.1+) Same as package require except does not try to load package if not
already loaded.
Tells interpreter that version of package is now present. Without version, the currently
provided version of package is returned or empty string if none.
Tells interpreter that version of package is needed. Only packages with versions equal
to or later than version (if provided) are acceptable, but must have same major
version. If -exact is specified, the exact version specified must be provided. Without
version or -exact, any version is acceptable. Returns version number loaded.
Returns 1 if version2 scripts will work unchanged under version1 (version1 >=
version2 and both samesame major version #), 0 if not.
::pkg::create -name
packageName -version
packageVersion ?-load filespec?
... ?-source filespec? ...
pkg_mkIndex ?options? ?--?
directory ?pattern ...?
-direct
-lazy
-load pkgPat
-verbose
Creates the pkgIndex.tcl file in the specified directory with all files matching pattern
using Pattern Globbing.
(Tcl 8.0.4+) A packages in index file will be loaded upon package require. (default
in Tcl 8.3+)
(Tcl 8.3+) A package in index file will be loaded when one of the provided commands
is used. (default up to Tcl 8.2.3)
(Tcl 8.0.4+) Packages that match pkgPat using Pattern Globbing in the current
interpreter will be pre-loaded into slave interpreter used to generate index. In Tcl
8.4.2+ match is case insensitive.
(Tcl 8.0.4+) Generate output to stderr during indexing process.
2.16 Procedures
Procedures are used to partition segments of code into subroutines so they can be called from other parts of an application
or recursively. Procedures behave just like built-in commands and can have variable length arg lists. Variables within a
procedure can be decalared as local (default) or global.
Command
Description
name ?args?
global varName
?varName ...?
Used with -code error, to set the global variable errorCode to error. Used for additional info about the
error (in list format for Tcl 8.5+ and defaults to NONE).
-errorinfo info
Used with -code error, to set the global variable errorInfo to info. Used for the procedure stack trace
(in list format for Tcl 8.5+).
-level level
(Tcl 8.5+) Number of levels (default is 1) up the calling stack to return code to (intermediate steps get
code return).
(See Variables)
upvar
(See Variables)
2.17 Strings
A string is an arbitrary series of bytes (including binary data with null characeters) of any size up to the amount of
available virtual memory. Character Strings are a special type of string kept in UTF-8 encoding by Tcl. Most Tcl
commands expect to work on character strings and may not be able to handle binary data. Each character in a string is
indexed like an array starting with index 0. The string command arguments of index , startIndex, charIndex, lastIndex, first,
and last can be replaced with end to use the index of the last character in string . In Tcl 8.1.1+, end-number (where number
an integer) can be used to specify an index of the last character minus the specified number.
Command
Description
append varName ?value ...? Appends each of the given values to the string stored in varName.
binary format formatString Returns the args converted to a binary string based on formatString. The formatString is a
?arg ...?
sequence of field specifiers and optional integer count pairs separated by 0 or more spaces.
The default count is 1. For strings and positions the count is the size and a count of "*"
indicates all bytes/chars in arg will be used, otherwise will truncate if too long or pad if too
sort. For ints and floating points it is the number of repetitions. Binary and hex types zero
pad to the byte boundary if count > num of bytes/chars or truncate if count < num of
bytes/chars. The field specifiers are:
Type
Binary (0 pad,
byte
1
boundary)
Hex (0 pad) 4
Char
8
Native
Little
Endian
Big
Endian
h
c
H
c
Short Int
16
t (8.5+) s
x Null (\0)
Int
32
n (8.5+) i
Wide Int
64
m
(8.5+)
w (8.4+)
W (8.4+)
Float (IEEE)
32
r (8.5+)
R (8.5+)
Double
(IEEE)
64
q (8.5+)
Q (8.5+)
@ Absolute position
(@* skip to end)
binary scan string
formatString varName
?varName ...?
Size
(bits)
String Types
Converts binary data into varName string variables based on formatString. Returns the
number of strings converted. Stores integers as signed ints. The format field specifiers are
the same as binary format except for:
a ISO 8859-1 chars (no pad
stripping)
x skip
Returns a formated string similar to the ANSI C sprintf. The format string is
%[argpos$][flag][width][.prec][len]char where argpos, width, and prec are integers.
Fields are:
Field Description
argpos Specifies arg to use for value with format {arg #}$. Argpos can be a variable by
using ${var}$ or if quoting "${var}\$". Uses successive args for * specifiers. If
any positional specifier is used, then all conversions must use them. Optional field.
flag
Conversion flag. See options below. Optional field.
width Minimum field width. Uses flag specified padding. A field width of * uses the next
arg as the field size. Optional field.
.prec Value is decimal places for e, E, and f; total digits for g and G; trunc size for ints;
and max chars for s. If precision is *, the next arg is used as the precision. Optional
field.
len
Use h to truncate numeric value to 16 bits before conversion and in Tcl 8.4+, use l
to insure value is 64 bits. Default is to use width of native machine word. Optional
field.
char Conversion type. See options below. Required field.
Possible values for flag are:
left-justified
d signed decimal
c int to char
always signed
u unsigned decimal
s string
zero pad
f float (fixed)
o unsigned octal
e float (0e0)
x unsigned hex
E float (0E0)
X unsigned HEX
g auto float (f
or e)
auto float (f
G
or E)
% plain %
regexp ?options? ?--? exp
string ?matchVar?
?subMatchVar ...?
Returns 1 if the regular expression exp matches part or all of string, 0 if not. If specified,
matchVar will be set to the matching characters and the subMatchVars will be set to
parenthesized subexpressions starting with the leftmost one. Unused subMatchVars will
contain "-1 -1" if -indices was used or to an empty string otherwise. See Regular
Expressions. Leave out vars if only matching is needed. To pre-compile use "set re {...};
regexp $re {}". Options are:
-about
-all
-expanded
-indicies
-inline
-line
-lineanchor
-linestop
-nocase
-start index
regsub ?options? ?--? exp
string subSpec ?varName?
-all
-expanded
-line
-lineanchor
-linestop
-nocase
-start index
(Tcl 8.2.3+) Instead of matchingexp, returns list with info on exp. First element is subexp
count and second is a list of property names of exp attributes.
(Tcl 8.3+) Match exp as many times as possible in the string, Vars will contain info on last
match.
(Tcl 8.2.3+) Use expanded regular expressions and ignore comments and white-space.
Instead of storing matching chars in subMatchVar, store start and ending indices of match
in string .
(Tcl 8.3+) Return list of data that would have been stored in matchVar and subMatchVar.
Used with -all, each iteration will have match data and each subexpression concatenated to
list.
(Tcl 8.2.3+) Enables newline-sensitive matching. Equivalent to using both -linestop and
-lineanchor or (?n) embedded option.
(Tcl 8.2.3+) Changes behavior of "^" and "$" anchors so they match the start and end of a
line, respectively. Same as (?w) embedded option.
(Tcl 8.2.3+) Changes behavior of "[^" bracket expressions and "." so that they stop at
newlines. Same as (?p) embedded option.
Ignore case in matching.
(Tcl 8.3+) Specifies char index offset to start matching exp at. With -indicies, the indices
will be in terms of the absolute beginning. "^" will not match line start.
Substitute first match of regular expression exp in string with subSpec and put in varName
(default is to return matched portion in Tcl 8.4+) if specified, and return a count of
replacements made. Subspecs "&" or "\0", are replaced with the matching string and "\#"
where # is [1-9], replaces the #th matched exp in string. See Regular Expressions. Options
are:
Substitute exp with subSpec as many times as possible in the string.
(Tcl 8.2.3+) Use expanded regular expressions and ignore comments and white-space.
(Tcl 8.2.3+) Enables newline-sensitive matching. Equivalent to using both -linestop and
-lineanchor or (?n) embedded option.
(Tcl 8.2.3+) Changes behavior of "^" and "$" anchors so they match the start and end of a
line, respectively. Same as (?w) embedded option.
(Tcl 8.2.3+) Changes behavior of "[^" bracket expressions and "." so that they stop at
newlines. Same as (?p) embedded option.
Ignore case in matching.
(Tcl 8.3+) Specifies char index offset to start matching exp at. "^" will not match line start.
scan string format varName Parse string using format conversions, store results in varNames, and return a count of
?varName ...?
conversions performed or -1 if none. Format is in the form of %[*][argpos$
][width][size]char. White-space in the data is skipped except for c or [ ] set conversions. In
Tcl 8.3+, will return a list if no variables are specifed. Fields are:
Field
*
Description
Indicates that the converted value is to be discarded instead of assigned to a
variable.
argpos Specifies arg to use for value with scan "{arg #}$". Argpos can be a variable by
using ${var}$ or if quoting "${var}\$". Uses successive args for * specifiers. If
any positional specifiers are used, then all conversions must use them. In Tcl
8.3.3+, if #$ is used after % then #varName is used instead. Optional field.
width Integer maximum field width. Optional field.
size
Field size modifier. In Tcl 8.4+, use l or L to insure value is stored as 64 bits.
Default is to truncate to width of native machine word. Optional field.
char Conversion type. See options below. Required field.
Character ConversionTypes:
char to int
o octal
e or f
x hex
auto float (f or e)
u unsigned int
(Tcl 8.1+)
i int (Tcl 8.1+)
dec,hex,oct
space
or tab
s
[abc], [a-c]
-nocase
-length number
string (non-whitespace)
chars in given range
(Tcl 8.1.1+) Compare string1 to string2 character by character and return 1 if they are
identical, 0 if not. Options are:
-nocase
Ignore case
-length number
Returns the index of the first char of the first occurance of the exact match of string1 in
string2, -1 if none. In Tcl 8.1.1+, startIndex specifies the offset of the first char to use in the
search and can be end or end-number .
Returns the character at index in string. If index < 0 or > end, returns empty string. In Tcl
8.1.1+, index can be end or end-number .
(Tcl 8.1.1+) Returns 1 if string is a valid member of class (see Regular Expression
Character Classes), 0 if not. Options are:
-strict
-failindex varName
If not a member, the index in the string where class is no longer valid will be stored in
varName.For boolean, true, and false, if 0 is returned, varName will also be set to 0. For
double, integer, or wide integer, an under/overflow will return 0 and varName will be set
to -1.
Return the index of first char in the last occurance of the exact match of string1 in string2,
-1 if none. In Tcl 8.1.1+, lastIndex specifies the offset of the last char to use in the search
and can be end or end-number.
Returns the number of characters in string based on the encoding or bytes for binary data.
(Tcl 8.1.1+) Replaces characters in string based on and in the order of the key/value pairs in
charMapList.CharMapList is a list of key/value pairs (can be multiple chars) as the
elements. Case is ignored if -nocase is used.
Returns 1 if pattern matches string using Pattern Globbing, 0 if not. In Tcl 8.1.1+, case will
be ignored with -nocase.
string range string first last Returns characters in string between indices first and last inclusive. If first < 0, then 0 is
used. If last > end, then end is used. If first > last, then empty string is returned. First and
last can be end. In Tcl 8.1.1+, first and last can also be end-number.
string repeat string count
string replace string first
last ?newString?
string tolower string ?first? Returns new string formed by converting all chars in string to lower case. In Tcl 8.1.1+, a
?last?
subset of the string between indicies first and last, inclusive, can be converted. First and
last can be end or end-number .
string totitle string ?first?
?last?
(Tcl 8.1+) Returns new string formed by converting the first char in string to title case (or
upper case if no title case equivalent) and the rest to lower case. If specified, a subset of the
string between indicies first and last, inclusive, can be converted. First and last can be end
or end-number.
string toupper string ?first? Returns new string formed by converting all chars in string to upper case. In Tcl 8.1.1+, a
?last?
subset of the string between indicies first and last, inclusive, can be converted. First and
last can be end or end-number .
string trim string ?chars?
Returns new string formed by removing from string any leading or trailing characters
present in the set chars (defaults to white-space).
string wordend string index Returns index in string of char just after last char in the word containing index.
string wordstart string
index
tcl_endOfWord string start Returns the index of the first end-of-word location that occurs after a starting index start in
the string string or -1 if none remain.
tcl_startOfNextWord
Returns the index of the first start-of-word location that occurs after a starting index start in
string start
the string string or -1 if none remain.
tcl_startOfPreviousWord Returns the index of the first start-of-word location that occurs before a starting index start
string start
in the string string or -1 if none remain.
tcl_wordBreakAfter string Returns the index of the first word boundary after the starting index start in the string string
start
or -1 if no more boundaries.
tcl_wordBreakBefore
Returns the index of the first word boundary before the starting index start in the string
string start
string or -1 if no more boundaries.
2.18 Variables
Command
global varName ?varName
...?
incr varName ?increment?
set varName ?value?
set arrayName(index)
?value?
trace add type name opList
command
command
Description
(See Procedures)
Increment the integer value stored in varName by increment (default is 1). Max increment
value is pow(2,32)
Store value in varName for current scope and namespace. Without value, returns the
current value of varName. Can use namespace qualifiers in varName to specify a
namespace or ::VarName for global variables. See Syntax for variable substitution forms.
Same as above except for array element.
(TCL 8.4+) Adds Tcl commands to be executed whenever certain operations are invoked.
Types are:
Arrange for command to be executed whenever command name is modified based on
opList (rename or delete). Args appended to command at execution are the oldCmdName,
newCmdName, and opList. For delete newName is empty string. In Tcl 8.4.2+, the
command name is fully qualified.
execution
Arrange for command to be executed whenever command name is executed based on
opList. Available opList options are: enter (before execution start), leave (after execution
completes), enterstep (before each command in name is executed), or leavestep (after each
command in name is executed). For enter and enterstep, args appended to command at
execution are the command-string (complete cmd being executed) and opList. For leave
and leavestep, appended to command at execution are the command-string (complete cmd
being executed), code (exec result code), result (exec result string), and opList .
variable
Arrange for command to be executed whenever variable name is accessed or modified
based on opList. Available opList options are: array (via array cmd), read (variable is
read), write (variable is written), or unset (variable is unset). Args appended to command
when executed are name1 (scalar var name or array name), name2 (empty string or array
index, if not whole array), and opList.
trace info type name
(TCL 8.4+) Returns list (where each element is a two element list of opList and command
pairs) of trace operations currently set for command or variable name. Options for type are
the same as trace add.
trace remove type name
(TCL 8.4+) Removes trace on Tcl commands or variables to be executed as defined in
opList command
trace add operation. Options for type, name, opList, and command are the same as trace
add except opList can be a list of opList to use.
trace variable varName ops Same as trace add variable varName ops command, except ops is not a list and can be a
command
string of: a for array, r for read, w for write, and/or u for unset.
trace vdelete varName ops
command
trace vinfo varName
Same as trace remove variable varName ops command, except ops is not a list and can be
a string of: a for array, r for read, w for write, and/or u for unset.
Same as trace info variable varName.
unset?-nocomplain??--?
name ?name ...?
Removes the variables or arrays name from scope. If name is an array(index) in an array,
only that element is removed. If its just an array name then the whole array is deleted. See
Syntax for variable substitution forms. In Tcl 8.4+, -nocomplain suppresses any possible
errors.
uplevel ?level? arg ?arg ...? Evaluates concatenation of args in the variable context indicated bylevel (default is 1).
Level is an integer that gives the distance up the calling stack or with a prefix of "#", the
absolute level number down the stack from global level #0. Returns result of evaluation.
There is a performance impact if level is not specified.
upvar ?level? otherVar
Links localVar in local scope to otherVar in the variable context indicated by level (default
localVar ?otherVar localVar is 1) so they share the same storage space. LocalVar must be scalar (Tcl 8.5+ will return an
...?
error for an array), but otherVar can be scalar, an array, or an array element. Level has the
same definition as uplevel. The unset operation affects the linked to variable otherVar and
not the upvared variable localVar. Traces on otherVar (except for entire arrays) will also
work for localVar, but the variable returned will be localVar.
variable
(See Namespaces )
3 Tk Commands
3.1 Bindings and Events
Command
Description
bind tag
Returns a list of all sequences for which there exist bindings for window tag. See Tags for tag format
options.
Returns the script bound to sequence for window tag or empty string if none. See Event
SequencePatterns for sequence format options.
Create a binding to evaluate script at global level by the same interpreter whenever event in sequence
occurs within window tag. If script is prefixed with "+" (within braces if used), it is appended to the
existing binding. If script is an empty string, the current binding is removed. See Event Generation
and Substitutions for script % substitutions. The script can contain continue to terminate current
script and break to terminate current script and skip remaining scripts. If an error occurs during the
script execution, bgerror will be executed at the global level.
bindtags window
?tagList?
Change tags and tag order for window to contents of list tagList. If tagList is an empty list, the tags
are set back to the default (window name, window class, toplevel window, and all). Without tagList,
the current set of binding tags is returned.
event add
<<virtual>>
sequence
?sequence ...?
Define a virtual event by triggering virtual event virtual whenever any one of the sequences occur.
See Event Sequence Patterns for sequence format options.
event delete
<<virtual>>
?sequence ...?
Deletes each sequence (or all without sequence) from the trigger list for virtual eventvirtual . Ignores
sequences not associated with virtual event virtual . See Event SequencePatterns for sequence format
options.
event generate
window event
?option value ...?
Generates a window event in window as if it had came from the window system. See Event Sequence
Patterns for event format options. See Event Generation and Substitutions for options. The -when
options are:
-when now
-when tail
-when head
-when mark
event info
?<<virtual>>?
Tags
Each window has an associated list of tags, and a binding applies to a particular window if its tag is among those specified
for the window. The supported tag formats are: .a.b.c format (path name for window) or an arbirtary string. When a
window or widget is destroyed, its bindings are also deleted but not bindings to the tags associated with the window. The
default binding tags behavior and order is:
Order Tag
Applicability
internal window name applies to just that window
1
2
toplevel window name applies to top level and all its internal windows
all
When used for items within a canvas or text widget, bindings for items will be invoked before bindings for the window as a
whole. The binding order is:
Order
1
2
3
Binding
all
item tag
item id
Description
binding associated with all tag
one binding for each of the items tags (in order)
binding associated with items id
Description
a single ASCII character (except space or "<") that matches a Keypress event
String with zero or more modifiers (see Modifiers below), an event type (see Event
Types below), and a detail field (see Details below) identifying a particular button or
<modifier-modifier-type-detail> keysym, separated by white space or dashes. Any field may be omitted as long as at least
one of type and detail is present. Shortcuts for keyboard events: <Keypress-x>, <Key-x>,
<x>, x. Shortcuts for mouse button events: <ButtonPress-1>, <Button-1>, <1>.
User-defined virtual event of name name . Modifiers may not be combined with a virtual
event. Binding to a virtual event may be performed before the virtual event is defined. If
the virtual event definition changes, all windows bound to that virtual event will respond
immediately to the new definition. See Default Virtual Events for default events.
<<name>>
Modifiers:
Modifiers are used to modify button or key events. Button is the associated mouse button. Mod is the associated modifier
key. Meta and M refer to whichever of the M1 through M5 modifiers is associated with the meta key(s) on the keyboard
(keysyms Meta_R and Meta_L) or none if no match. Double,Triple,Quadruple refer to multiple mouse clicks within the
time-out period or other repeating events. In Tk 8.5+ for MS Windows, the Extended modifier appears for events that are
associated with the keys on the "extended keyboard." On a US keyboard, the extended keys include the Alt and Control
keys at the right of the keyboard, the cursor keys in the cluster to the left of the numeric pad, the NumLock key, the Break
key, the PrintScreen key, and the / and Enter keys in the numeric keypad.
Command (Mac) Button-1 or B1 (left)
Control
Shift
Button-3 or B3 (right)
Lock
Button-4 or B4
Alt
Button-5 or B5
Mod4 or M4 (Extended,
Tk 8.5+ MS Windows)
Mod5 or M5
Event Types:
Double
Quadruple (Tk 8.3+)
Type
Description
Type
Toplevel window of sub-window has been FocusOut
activated (Mac, Windows)
Button is pressed
Gravity
Description
Window has lost keyboard focus
ButtonRelease
Button is released
Key is pressed
Circulate
KeyPress,
Key
KeyRelease
Leave
Map
Activate
ButtonPress,
Button
CirculateRequest
Colormap
Configure
Motion
MouseWheel
Destroy
Enter
Expose
FocusIn
MapRequest
Key is released
Details:
Event Type
ButtonPress,
ButtonRelease
KeyPress,
KeyRelease
Detail
button
number (1-5)
keysym
Result
If a button number is specified, only an event on that particular button will match
and type will default to ButtonPress, otherwise an event on any button will match.
Keysyms are textual specifications for the keys on the keyboard. See Keysyms
below. If specified, type will default to Keypress.
Keysyms:
Commonly used keysyms for the detail field are 0-9, A-Z, a-z, and those in the table below. Complete list is available in
/usr/include/X11/keysymdef.
Alt_L
Alt_R
ampersand
App
asciicircum
asciitilde
asterisk
at
backslash
BackSpace
bar
Begin
braceleft
braceright
bracketleft
bracketright
Break
Cancel
Caps_Lock
Clear
colon
comma
Control_L
Control_R
degree
Delete
diaeresis
dollar
Down
End
equal
Escape
exclam
Execute
F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
Find
greater
Help
Home
Hyper_L
Hyper_R
hyphen
Insert
KP_0
KP_1
KP_2
KP_3
KP_4
KP_5
KP_6
KP_7
KP_8
KP_9
KP_Add
KP_Decimal
KP_Divide
KP_Enter
KP_Equal
KP_F1
KP_F2
KP_F2
KP_F4
KP_Multiply
KP_Separator
KP_Space
KP_Subtract
KP_Tab
Left
less
Linefeed
Menu
Meta_L
Meta_R
minus
Multi_key
Next
nobreakspace
numbersign
Num_Lock
parenleft
parenright
Pause
percent
period
periodcentered
plus
plusminus
Print
Prior
question
quotedbl
quoteleft
quoteright
Redo
Return
Right
Scroll_Lock
Select
semicolon
Shift_L
Shift_Lock
Shift_R
slash
space
Super_L
Super_R
Sys_Req
Tab
underscore
Undo
Up
Win_L
Win_R
Event Pattern
(except text widget)
Text Widget
Unix
Windows
<Control-c>
<Meta-w>
<F16>
Mac
(Aqua)
<Clear>
<Control-Insert> <F3>
All
<<Cut>>
<Control-x>
<Control-w>
<F20>
<Shift-Delete>
<F2>
8.4+
All
<<Modified>>
<<Paste>>
<Control-v>
<Control-y>
<F18>
<Shift-Insert>
<F4>
<<Redo>>
8.4+
8.4+
8.5+
8.5+
<<Selection>>
<<Undo>>
<<TraverseIn>>
<<TraverseOut>>
<Control-Z> <Control-y>
<Control-z>
Binding Matches
<Control-underscore>
<Control-y>
Trigger
If several bindings to match a given X event
but have different tags
If several bindings match a given X event
and they have the same tag
If the matching sequences contain more than
one event
Action
Each binding is executed. The default order is: binding for the widget, class
binding, binding for its toplevel, and the all binding.
The most specific binding is chosen and its script is evaluated. See Order of
Tests below for criteria to determine most specific binding.
Tests 3 to 5 in Order of Tests below are applied in order from the most
recent event to the least recent event in the sequences. If these tests fail to
determine a winner, then the most recently registered sequence is the
winner.
Only one of the virtual events will be triggered and it will be picked at
random
The event is ignored. An unbound event is not considered to be an error.
Its script is executed whenever the recent events (leading up to and
including the current event) match the given sequence. (ex. Triple will also
match Double).
Order of Tests
Sequence
1
2
3
4
5
Test
pattern that specifies specific button or key
longer sequence of events matched
more matching modifiers
physical pattern not associated with a virtual event
undefined match for two or more virtual events
-above window
-borderwidth
size
%% Percent sign
%A Substitute ASCII (pre Tk 8.2) or
ISO Latin 1 (Tk 8.2+) char for
event or empty string {} if none
above field for event where
%a window is a path name or integer
window id
border_width field for event
%B
where size is distance
Valid Events
all events
KeyPress, KeyRelease
Configure
Configure, ConfigureRequest, Create
-button
number
%b
ButtonPress, ButtonRelease
-count number
%c
Expose, Map
-data string
%d
-delta number
-detail detail
MouseWheel
Enter, Leave, FocusIn, FocusOut
-focus boolean
%f
Enter, Leave
-height size
%h
%i
-keysym name
-keycode
number
-mode notify
-override
boolean
%P
PropertyNotify
-rootx coord
-rooty coord
-sendevent
boolean
%E
-serial number
%#
-state state
%s
-subwindow
window
%S
-place where
-root window
-time integer
-warp boolean
-width number
-x coord
-y coord
KeyPress, KeyRelease
Enter, Leave, FocusIn, FocusOut
Circulate, CirculateRequest
KeyPress, KeyRelease,ButtonPress, ButtonRelease, Enter,
Leave, Motion
KeyPress, KeyRelease,ButtonPress,ButtonRelease, Enter,
Leave, Motion
KeyPress, KeyRelease,ButtonPress,ButtonRelease, Enter,
Leave, Motion
all events
all events
all events
KeyPress, KeyRelease,ButtonPress,ButtonRelease, Enter,
Leave, Motion
For some of the above substitutions, the possible replacement strings are:
Code Event
%d Enter, Leave,FocusIn, FocusOut
%d
%m
%p
%s
%s
ConfigureRequest
Enter, FocusIn,FocusOut, Leave
Circulate,CirculateRequest
ButtonPress, ButtonRelease,Enter,
KeyPress, KeyRelease, Leave,
Motion
Visibility
Replacement String
NotifyAncestor, NotifyDetailNone,NotifyInferior,NotifyNonlinear,
NotifyNonlinearVirtual, NotifyPointer,NotifyPointerRoot, or
NotifyVirtual
Above, Below, BottomIf,Opposite, None, or TopIf
NotifyNormal, NotifyGrab,NotifyUngrab, or NotifyWhileGrabbed
PlaceOnTop or PlaceOnBottom
decimal integer
VisibilityUnobscured, VisibilityPartiallyObscured, or
VisibilityFullyObscured
Description
button
pathName
?options?
Creates a button pathName with options and returns the new widgets path name. When invoked,
pathName must not exist, but pathNames parent should. A button widget can display text, a bitmap, or
an image. Selecting a button will cause the associated command to be evaluated. Multiple fonts within a
button text field are not supported.
See Common Options and Resources in Options and Resources for full details.
-activebackground
-font
-relief
-activeforeground
-foreground
-anchor
-highlightbackground
-background
-highlightcolor
-takefocus
-bitmap
-highlightthickness
-text
-borderwidth
-image
-textvariable
-compound (8.4+)
-justify
-underline
-cursor
-padx
-wraplength
-disabledforeground
-pady
Configure
Option
-command
script
-default
state
-height
height
-overrelief
type
-state state
-width
width
Resource
Name
command
default
height
Resource
Description
Class
Command Tcl command to associate with the button. Script is invoked when mouse button
1 is released over the button window.
Default
Sets platform specific appearance state of default ring. Options are: active
(default button), normal (non-default button), or disabled (non-default button
without leaving space for default ring).
Height
Height of button in screen units for bitmaps/images and in lines for text. Default
is to auto size.
overRelief OverRelief (Tk 8.4+) Alternative relief for when mouse cursor is over button. Not used
when set to empty string (default). Options are: flat, raised, and sunken.
state
State
State of button. Options are: active (mouse pointer over button, use
activeforeground and activebackground),disabled (button is insensitive, use
disabledforeground and background), or normal (use foreground and
background ).
width
Width
Width of button in screen units for bitmaps/images and in characters for text.
Default is to auto size.
Description
Returns the current value of the configuration option for button pathName. See Button
Widget Options above for options.
pathName
Change the configuration option for the button pathName to value. Without value, a list
configure?option? ?value? describing the available options is returned. Without option, a list describing all of the
?option value ...?
available options for pathName is returned. For multiple options an empty string is returned.
See Button Widget Options above for options.
pathName flash
Flash checkbutton by toggling between active and normal colors several times. Button is left
is initial state of active or normal. Ignored if button is disabled.
pathName invoke
Toggle the selection state of the checkbutton and invoke the Tcl command specified with
-command, if any. Returns value of Tcl command or empty string if no -command .
Ignored if button is disabled.
pathName cget option
Description
When mouse passes over button, relief changes to sunken (Unix and MS Windows only) and state
becomes active.
<Leave>
When mouse leaves the button, relief changes to rasied (Unix and MS Windows only) and state
becomes normal.
<Button-1>
When button 1 is pressed, relief changes to sunken (Unix and MS Windows only) and state
becomesactive (Windows and Mac only).
<ButtonRelease-1> When button 1 is released, relief changes to rasied (Unix and MS Windows only) and state
becomesnormal (Windows and Mac only). If still over button, -command script is invoked.
<space>
If button has focus, relief changes tosunken, state becomes active, and command script is invoked.
Description
canvas
pathName
?options?
Creates a canvas widget pathName with options and returns the new widgets path name. When invoked,
pathName must not exist, but pathNames parent should. A canvas window can be used to show structured
graphics. Widgets created within the canvas are referred to as items and are displayed in the order they are
listed in the widget except for window items. Items are ordered from lowest (first) to highest (latest) in the
display list such that later items can obscure earlier items. New canvases are not given any default binding
behavior.
Canvas Options
Standard
See Common Options and Resources in Options and Resources for full details.
-background
-insertbackground
-selectbackground
-borderwidth
-insertborderwidth
-selectborderwidth
-cursor
-insertofftime
-selectforeground
-highlightbackground
-insertontime
-takefocus
-highlightcolor
-insertwidth
-xscrollcommand
-highlightthickness
-relief
-yscrollcommand
Canvas Specific
Resource Name
closeEnough
Resource Class
CloseEnough
Description
Value indicating how close the mouse cursor must be to
an item before it is considered to be "inside" the item.
Default is 1.0.
-confine boolean
confine
Confine
-height height
-scrollregion left top
right bottom
height
scrollRegion
Height
ScrollRegion
-state state
state
State
-width width
-xscrollincrement
distance
-yscrollincrement
distance
ID/Tag
unique id
tag
all
current
Description
Unique numeric identifier of item within a canvas. Items can only have one id.
String of characters that other than a numeric value used to group items. Items can have multiple tags.
Tag associated with all items in a canvas widget.
Tag set automatically by Tk to the current item (topmost item) under the mouse pointer, if any.
end
text, line,
polygon
insert text
sel.first text
sel.last text
@x,y
text, line,
polygon
Description
A decimal number giving the position of the desired character within the text item where 0 = first
character. Odd indicies for lines and polygons are decremented by 1. If number < 0, the 0 is used,
if number > length of text list, then end is used. For polygons, if number < 0 or > length, then
length is added or subtracted until number is in range.
Character or coordinate just after last one in item.
Character just after the insertion cursor.
First selected character in item.
Last selected character in item.
Character or coordinate at the point given by x and y using canvas coordinate system. If x or y are
outside the item coordinates, they are set to the first or last character in line closest to given point.
Canvas Commands
The following are the valid command operations that can be invoked on the canvas widget pathName created by the
canvas command. Widgets created within the canvas are referred to as items.
Command
Description
pathName addtag tag searchSpec For each item that matches searchSpec and arg in canvas pathName, add tag to the list
?arg ...?
of tags associated with that item. SearchSpec and arg options are:
above tagOrId
Selects the last (topmost) item in display list, just after (above) the one given by
tagOrId in the display list.
all
below tagOrId
Selects the first (lowest) item in display list, just before (below) the one given by
tagOrId in the display list.
Select the last (topmost) item in display list, closest to @x,y. If specified, it must be
below start in the display list. Any item closer than halo to the point is considered to
overlap it.
enclosed x1 y1 x2 y2
Selects all the items completely enclosed within rectangular region @x1,y1 and
@x2,y2 where x1 < x2 and y1 < y2.
overlapping x1 y1 x2 y2
Selects all the items that overlap or are enclosed within rectangular region @x1,y1 and
@x2 ,y2 where x1 < x2 and y1y2. <
withtag tagOrId
pathName bindtagOrId
?sequence? ?command?
Create a binding to evaluate command whenever event in sequence occurs within the
items named by tagOrId . See bind command for options. Only mouse, keyboard, and
virtual events can be used.
pathName canvasxscreenx
?gridspacing?
pathName canvasyscreeny
?gridspacing?
Returns the current value of the configuration option. See Standard Options and
Canvas Specific Options above for options.
pathName configure ?option?
Change the configuration option to value. Without value, a list describing option is
?value? ?option value ...?
returned. Without option, a list of all available options for pathName is returned. For
multiple options an empty string is returned. See Canvas Options above for options.
Change coordinates for first item given by tagOrId to specifed coordinates or
pathName coordstagOrId ?x0 y0
coordList (Tcl 8.3+). Without coordinates, returns a list whose elements are
...? ?coordList?
coordinates of item tagOrId.
pathName cget option
Create a new item in pathName of typetype (See Canvas Item Types below) at
specified coordinates or coordList (Tk 8.3+) with options. Returns id of new item.
For items given by tagOrId, delete the characters (text) or coordinates (line or
polygon) in the range given by first and last (defaults to first), inclusive. See Indicies
or Char Positions above.
pathName dtagtagOrId
?tagToDelete?
Delete the tag given by tagToDelete (default is tagOrId) from the list of associated
tags for each item given by tagOrId.
Returns a list of items in stacking order that satisfy the specification searchSpec. See
addtag for searchSpec options.
Set the keyboard focus to the first item (lowest) given bytagOrId that supports the
insertion cursor (text). If tagOrId is empty string, the focus item is unset. Without
tagOrId , returns current item with focus or empty string if none.
Return a list of the tags associated with the first item (lowest) given by tagOrId or
empty string if none.
Set the insertion cursor for the item(s) given by tagOrId that support the insertion
pathName icursor tagOrId index cursor (text) to just before the character at position index. See Indicies or Char
Positions above. Does not effect keyboard focus.
pathName indextagOrId index
Returns a decimal string giving the numerical index of the first item (lowest) within
tagOrId corresponding to the character (text) or coordinate (line or polygon) at
position index. See Indicies or Char Positions above.
pathName inserttagOrId
beforeThis string
For items given by tagOrId that support text or coordinate insertion, insert string just
before character (text) or coordinate (line or polygon) at position beforeThis . For lines
or polygons, string must be a valid coordinate sequence. See Indicies or Char
Positions above.
pathName itemcgettagOrId
option
Returns the current value of the configuration option for the first item (lowest) given
by tagOrId. See Canvas Options above for options.
Change the configuration option for item tagOrId to value. Without value, a list
pathName itemconfiguretagOrId
describing option is returned. Without option, a list of all available options for the first
?option? ?value? ?option value
item (lowest) given by tagOrId is returned. For multiple options an empty list is
...?
returned. See Canvas Options above for options.
pathName lowertagOrId
?belowThis?
Move items given by tagOrId to a new position on the display list just before the first
(lowest) item given by belowThis . If tagOrId refers to more than one item, then all
items are moved, but their relative order remains the same.
pathName movetagOrId xAmount Move each of the items given by tagOrId in the canvas coordinate space by adding
yAmount
xAmount and yAmount to each items x and y coordinates, respectively.
pathName postscript?option
value ...?
-channel channelID
-colormap varName
Generate a Encapsulated Postscript representation for part or all of the canvas. Options
are:
Specifies the channelID to write the Postscript code to.
Specifies a color mapping array varName where each element is a color name and the
value is Postscript code to set a particular color value. If not set or for unspecified
colors, Tk uses the RGB intensities.
-colormode mode
Specifies how to output color information where mode is: color, gray (grayscale), or
mono (black or white).
-file fileName
Specifies the file to write the Postscript code to. Not vaild for safe interpreters. If not
specified, the Postscript is returned as the result of the command.
-fontmap varName
Specifies a font mapping array varName where each element is a list of two elements
consisting of the name and point size of a postscript font and the value is Postscript
code to set a particular font. If not set or for unspecified fonts, Tk attempts to guess.
See Fonts for font options.
-height size
Specifies the height (default is canvas window height) of the area of the canvas to
print. See Coordinates in Options and Resources for screen unit options.
-pageanchor anchor
Specifies which point (default is center ) of the printed area should be appear over the
positioning point on the postscript page.
-pageheight size
Specifies that the Postscript should be scaled in both x and y directions so that the
printed area is size high (default is height on screen) on the Postscript page. See
Coordinates in Options and Resources for screen unit options.
-pagewidth size
Specifies that the Postscript should be scaled in both x and y directions so that the
printed area is size wide (default is width on screen) on the Postscript page. See
Coordinates in Options and Resources for screen unit options. Supercedes
-pageheight option.
-pagex position
Set the x-coordinate of the positioning point on the postscript page to position (default
is center). See Coordinates in Options and Resources for screen unit options.
-pagey position
Set the y-coordinate of the positioning point on the postscript page to position (default
is center). See Coordinates in Options and Resources for screen unit options.
-rotate boolean
If true, the printed area is to be rotated 90 degrees for landscape orientation (default is
false for portrait).
-width size
Specifies the width (default is canvas window width) of the area of the canvas to print.
See Coordinates in Options and Resources for screen unit options.
-x position
Specifies the x-coordinate of the left edge of canvas area (default is left edge of canvas
window) to print in canvas coordinates.
-y position
Specifies the y-coordinate of the top edge of canvas area (default is top edge of canvas
window) to print in canvas coordinates.
pathName raisetagOrId
?aboveThis?
Move all items given by tagOrId to a new position on the display list just after the last
(topmost) item given by aboveThis. If tagOrId refers to more than one item, then all
items are moved, but their relative order remains the same.
Rescale all items given by tagOrId in canvas coordinate space to change the distance
from @xOrigin,yOrigin by a scale factor of xScale,yScale (1.0 = no change)
respectively.
mark x y
dragto x y ?gain?
Records x and y and the current view in canvas. Typically associated with mouse
button press in widget at coordinates x,y.
Adjusts the view in Tk 8.3+ by gain (default is 10 in all Tk versions) times the
difference between the coordinates x,y and the last mark x,y coordinates. Used with
mouse motion events to produce high speed dragging effect.
Manipulates the selection based on the specified option. Where specified, the first item
given by tagOrId that supports indexing and selection (text) is used. See Indicies or
Char Positions above for index options.
clear
from tagOrId index
item
to tagOrId index
pathName typetagOrId
moveto fraction
scroll number pages
moveto fraction
scroll number pages
scroll number units
Adjust the end of the selection nearest to the character given by index in tagOrId to
include up to index and set the other end to be the anchor point. Works the same as
select to if selection is not in tagOrId.
Clear the selection if it is in the widget.
Set the selection anchor point to be just before the character given by index in the item
given by tagOrId.
Return id of the selected item or an empty string if there is none.
Set the selection to the characters in tagOrId from position index to the anchor point
(included only if index > anchor point) in tagOrId. If the anchor point is not in
tagOrId, index is used.
Returns the type (see Canvas Item Types below) of the first item (lowest) given by
tagOrId or empty string if none.
Query or change the horizontal canvas widget view. Without any options, a two
element list is returned specifying the start and end of the visible fraction (from 0 to 1)
of the horizontal span of the widget between the left and right edges of the window.
Vaild options and args are:
Adjust the view in the window so that fraction (from 0 to 1) of the total width of the
widget is off-screen to the left.
Shift the view left or right in units of nine-tenths the windows width. If number < 0,
information farther to the left becomes visible, otherwise information farther to the
right becomes visible.
Shift the view left or right by number units. If number > 0, units is same as
xScrollIncrement option, otherwise units is one-tenth of windows width.
Query or change the vertical canvas widget view. Without any options, a two element
list is returned specifying the start and end of the visible fraction (from 0 to 1) of the
vertical span of the widget between the top and bottom edges of the window. Vaild
options and args are:
Adjust the view in the window so that fraction (from 0 to 1) of the total height of the
widget is off-screen to the top.
Shift the view up or down in units of nine-tenths the windows height. If number < 0,
then higher information becomes visible, otherwise lower information becomes
visible.
Shift the view up or down by number units. If number > 0, units is same as
yScrollIncrement option, otherwise units is one-tenth of windows height.
Normal State
-dash pattern
list
containing
[.,-_ ]
-dashoffset
offset
Description
Display an arc-shaped region (oval delimited by two angles specified by -start and -extent options). Args
x1,y1 and x2,y2 or coordList give the coordinates of two diagonally opposite corners of a rectangular
region enclosing the oval that defines the arc. Options are:
-dash
-activedash
-disableddash
-fill
-activefill
-disabledfill
-outline
-activeoutline
-disabledoutline
-dashoffset
-disabledstipple
-offset
-disabledwidth
-extent
degrees
Size of the angular range occupied by arc in degrees (range = 360, if outside range then
degrees modulo 360) counter-clockwise from -start angle.
-start
degrees
-style
type
Arc is drawn as either type pieslice (default) where the enclosed region is a section of the
perimeter and two lines from the center to the perimeter endpoints; chord where the enclosed
region is a section of the perimeter and a line connecting the perimeter endpoints; or arc
where the enclosed region is just a section of the perimeter.
Specifies how to position the image relative to the item positioning point
whereanchorPos is n, ne, e, se, s,sw ,w,nw, or center (default).
Specifies the image to display in the normal state.
(Tk 8.4+) Specifies the image to display in the active state.
(Tk 8.4+) Specifies the image to display in the disabled state.
Display one or more connected line segments or curves. Args x1,y1 through xN,yN or coordList give the
coordinates for a series of two or more points that describe a series of connected line segments. Options
are:
-dash
-activedash
-disableddash
-fill
-activefill
-disabledfill
-dashoffset
-arrow where
Specifies whether an arrowhead should be drawn at line endpoints. Options are: none
(default option for no arrowheads), first (for an arrowhead at the first point of the line),
last (for an arrowhead at the last point of the line), or both (for arrowheads at both
ends).
-arrowshape
shape
Specifies arrowhead shape where shape is a three element list (neck length to tip,
trailing point length to tip, width from line to trailing point). Default is a reasonable
shape. See Coordinates in Options and Resources for screen unit options.
-capstyle style
Specifies caps to be drawn at endpoints of the line. Style options are: butt (default),
projecting, or round. Superceded by -arrow.
-joinstyle style Specifies joints to be drawn at line verticies. Style options are: bevel ,miter, or round.
-smooth
Set to true or bezier, smoothing is used to draw the line as a curve. The line is rendered
smoothMethod as a set of parabolic splines: one spline is drawn for the first and second line segments,
one for the second and third, and so on. Straight-line segments can be generated by
duplicating the end-points of the desired line segment. Set to false or {}, no smoothing
is performed. In Tk 8.5+, set to raw, indicates that the line should also be drawn as a
curve but where the list of coordinates is such that the first coordinate pair (and every
third coordinate pair thereafter) is a knot point on a cubic Bezier curve, and the other
coordinates are control points on the cubic Bezier curve.
-splinesteps
number
Specifies degree of smoothness desired for curves by approximating spline over number
line segments. Used with -smooth true or raw.
Display an oval region. Args x1,y1 and x2,y2 or coordList give the coordinates of two diagonally opposite
corners of a rectangular region enclosing the oval. The oval includes the top and left edges but not bottom
and right edges. Options are:
pathName
create oval
?x1 y1 x2 y2?
?coordList?
?option value
...?
-dash
-activedash
-disableddash
-fill
-activefill
-disabledfill
-outline
-activeoutline
-disabledoutline
-dashoffset
-activestipple
-disabledstipple
-width
-activewidth
-disabledwidth
-offset
-state
-tags
Display a polygonal or curved filled region. Args x1,y1 through xN ,yN or coordList give the coordinates
of three or more points that define a polygon. The first point is not repeated as the last point. Options are:
-dash
-activedash
-disableddash
-fill
-activefill
-disabledfill
-outline
-activeoutline
-disabledoutline
-dashoffset
pathName
create
polygon ?x1
y1 ... xN yN?
?coordList?
?option value
...?
-stipple
-activestipple
-disabledstipple
-width
-activewidth
-disabledwidth
-offset
-state
-tags
Polygon Specific Options:
-joinstyle
style
-smooth
boolean
(Tk 8.4+) Specifies joints to be drawn at outline verticies. Style options are: bevel, miter,
or round.
Set to true, bezier smoothing is used to draw the outline as a curve. The line is rendered as
a set of parabolic splines: one spline is drawn for the first and second line segments, one
for the second and third, and so on. Straight-line segments can be generated by duplicating
the end-points of the desired line segment. Set to false or {}, no smoothing is performed.
In Tk 8.5+, set to raw, indicates that the line should also be drawn as a curve but where the
list of coordinates is such that the first coordinate pair (and every third coordinate pair
thereafter) is a knot point on a cubic Bezier curve, and the other coordinates are control
points on the cubic Bezier curve.
-splinesteps Specifies degree of smoothness desired for outline curves by approximating spline over
number
number line segments. Used with -smooth true or raw.
Display a rectangular region. Args x1,y1 and x2,y2 or coordList give the coordinates of two diagonally
opposite corners of the rectangle. The rectangle includes the top and left edges but not bottom and right
edges. Options are:
pathName
create
rectangle ?x1
y1 x2 y2?
?coordList?
?option value
...?
-dash
-activedash
-disableddash
-fill
-activefill
-disabledfill
-outline
-activeoutline
-disabledoutline
-dashoffset
-activestipple
-disabledstipple
-width
-activewidth
-disabledwidth
-offset
-state
-tags
Display a string of characters in one or more lines at positioning point coordinates of x,y or coordList.
Options are:
-fill
-activefill
-disabledfill
Specifies how to justify multiple text lines within its bounding region. How options are:
left, right, or center.
Specifies the characters to be displayed in the text item. Newline causes line break.
Specifies the maximum line length for the text. If zero (default), break only on newline,
otherwise break on last space before maximum line length. See Coordinates in Options
and Resources for screen unit options.
Display a window at positioning point coordinates of x,y or coordList . It is not possible to draw other
graphical items on top of window items. A window item always obscures any graphics that overlap it,
regardless of their order in the display list. Options are:
-state
-tags
pathName
Window Specific Options:
create
window ?x y?
-anchor
Specifies how to position the window relative to the item positioning point where
?coordList?
anchorPos is n, ne, e, se,s ,sw,w,nw, or center (default).
?option value anchorPos
...?
Height in screen units to assign items window. See Coordinates in Options and
-height height
Resources for screen unit options.
-width width
Width in screen units to assign items window. See Coordinates in Options and
Resources for screen unit options.
-window
pathName
Specifies the window pathName to associate with this item. The window must be either a
child of the canvas widget or a child of some ancestor of the canvas widget and not a
top-level window.
3.4 Checkbutton
Command
Description
checkbutton
pathName
?options?
Creates a checkbutton widget pathName with options and returns the new widgets path name. When
invoked, pathName must not exist, but pathNames parent should. A checkbutton widget displays a
textual string, bitmap, or image and a square called an indicator. By default a checkbutton is configured
to select and deselect itself on alternate button clicks. Each checkbutton monitors its associated variable
and automatically selects and deselects itself when the variables value changes to and from the buttons
"on" value.Multiple fonts within a button text field are not supported.
Checkbutton Options
Standard
See Common Options and Resources in Options and Resources for full details.
-activebackground
-disabledforeground
-padx
-activeforeground
-font
-pady
-anchor
-foreground
-relief
-background
-highlightbackground
-takefocus
-bitmap
-highlightcolor
-text
-borderwidth
-highlightthickness
-textvariable
-compound (8.4+)
-image
-underline
-cursor
-justify
-wraplength
Checkbutton Specific
Resource
Name
command
Resource
Class
Command
Height
-indicatoron
boolean
indicatorOn IndicatorOn
-offrelief type
offRelief
OffRelief
Value
Value
-overrelief
type
-selectcolor
color
overRelief
OverRelief
selectColor
Background
-selectimage
image
-state state
selectImage SelectImage
-tristateimage
image
tristateImage TristateImage
-tristatevalue
value
-variable
variable
tristateValue Value
variable
Variable
-width width
width
Width
state
State
Description
Tcl command to associate with the button. Script is invoked when mouse
button 1 is released over the button window. The buttons global variable
(-variable option) will be updated before the command is invoked.
Height of button in screen units for bitmaps/images and in lines for text.
Default is to auto size.
Specifies whether the indicator should be drawn (default) or not. If false,
the relief option is ignored and the relief is set to sunken when widget is
selected and raised in all other cases.
(Tk 8.4+) Specifies the relief for the checkbutton when the indicator is not
drawn and the checkbutton is off. Options are: flat, raised (default), and
sunken.
Value (default is 0) stored in buttons global variable when the checkbutton
is deselected.
Value (default is 1) stored in buttons global variable when the checkbutton
is selected.
(Tk 8.4+) Alternative relief for when mouse cursor is over button. Not used
when set to empty string (default). Options are: flat, raised, and sunken.
Specifies a background color to use when the button is selected. If set to
empty string, no special color is used. If -indicatoron is true then the color
applies to the indicator, if false this color is used as the background for the
entire widget when selected.
Specifies image to be displayed when checkbutton is selected. Used with
-image.
State of button. Options are: active (mouse pointer over button, use
activeforeground and activebackground), disabled (button is insensitive,
use disabledforeground and background), or normal (use foreground
and background ).
(Tk 8.5+) Specifies an image to display (in place of the image option)
when the checkbutton is in tri-state mode. This option is ignored unless the
image option has been specified.
(Tk 8.5+) Specifies the value that causes the checkbutton to display the
multi-value selection, also known as the tri-state mode. Defaults to {}.
Specifies name of global variable to use for button selection status. Default
is name of the button within its parent.
Width of button in screen units for bitmaps/images and in characters for
text. Default is to auto size.
Effect
Options
Toolbar buttons
-relief flat -overrelief raised
Text-style toolbar buttons -offrelief flat -indicatoron false -overrelief raised
Checkbutton Commands
Command
Description
Returns the current value of the configuration option for checkbutton pathName. See
Checkbutton Widget Options above for options.
pathName
Change the configuration option for the checkbutton pathNamevalue. Without value, a list
configure?option? ?value? describing the available options is returned. Without option, a list describing all of the
?option value ...?
available options for pathName is returned. For multiple options an empty string is returned.
See Checkbutton Widget Options to above for options.
pathName deselect
Deselect the checkbutton and set the associated variable to its "off" value.
pathName flash
Flash checkbutton by toggling between active and normal colors several times. Checkbutton
is left is initial state of active or normal. Ignored if checkbutton is disabled.
pathName invoke
Toggle the selection state of the checkbutton and invoke the Tcl command specified with
-command, if any. Returns value of Tcl command or empty string if no -command. Ignored
if button is disabled.
pathName select
Select the checkbutton and set the associated variable to its "on" value.
pathName toggle
Toggle the selection state of the checkbutton, redisplaying it and modifying its associated
variable to reflect the new state.
Description
On Unix, when mouse passes over button statebecomesactive.
On Unix, when mouse leaves the button state becomes normal.
On Unix, relief changes to sunken and associated -command script is executed.
On Windows and Mac, relief changes to sunken and state becomes active.
On Windows and Mac, relief changes to raised, state becomes normal, and associated
-command script is executed.
On Windows and Mac, relief changes to sunken and state becomes active.
On Windows, selects the button.
On Windows, deselects the button.
On Windows and Mac, relief changes to sunken and associated -command script is
executed.
Command
Description
clipboard
append?-displayof window?
?-format format? ?-type
type? ?--? data
Append data to clipboard on window s display in the form type with the representation
format . Also claims ownership of clipboard on windows display. See Common Target
Atom Types below for type options. See Common Selection Property Types below for
format options. Format is required for non-Tk clipboard users.
clipboard clear?-displayof
window?
Claim ownership of clipboard on windows display (default is ".") and clears its contents.
(Tk 8.4+) Retrieve data from the clipboard on windows display (default is ".") in form
type. See Common Target Atom Types below for type options. Same as selection get
-selection CLIPBOARD.
If selection (see Selection Atom Types below for options) exists anywhere on windows
display (default is "."), clear it so that no window owns the selection anymore.
Returns the value of selection (see Selection Atom Types below for options) from
windows
display (default is ".") in format type (see Common Target Atom Types below for
selection get ?-displayof
options). If the selection is returned in a non-string format, such as INTEGER or ATOM,
window? ?-selection
the selection command converts it to string format as a collection of fields separated by
selection? ?-type type?
spaces: atoms are converted to their textual names, and anything else is converted to
hexadecimal integers.
Creates a handler for selection requests, such that command will be executed with args
offset (starting char in selection) and maxChars (max chars to retreive) whenever selection
selection handle?-selection (see Selection Atom Types below for options) is owned by window (default is ".") and
someone attempts to retrieve it in the form given by type (see Common Target Atom Types
selection? ?-type type?
below
for options). Format (see Common Selection Property Types below for options)
?-format format? window
specifies
how to format the data to the requestor. Format is required for non-Tk clipboard
command
users. If tclCommand is an empty string, the existing handler is removed. Tk 8.4+ (broken
in 8.4.0 and 8.4.1) adds a duplicate handler for UTF8_STRING when STRING is used for
type.
selection own?-displayof
Returns the path name of the window in this application that owns selection (see Selection
Atom Types below for options) on the display containing window, or an empty string if
window? ?-selection
none.
selection?
selection own?-command
command??-selection
selection? window
Causes window to become the new owner of selection (see Selection Atom Types below for
options) on windows display and sets up a handler to run command when window loses the
selection to another window later on.
Definitions
Platform independent method that allows for the exchange of data between applications via copy, cut, and
Clipboard paste.
Primary mechanism on X-Windows to exchange information via a copy and paste between clients. Selections
Selection are assigned to an particular atom such that other applications can retreive the selection by specifying the same
atom.
Atom
Unique name (strings without a specific encoding) that clients can use to communicate information to each
other.
Description
Converted into ATOM name.
FILE_NAME
POSTSCRIPT
STRING
INTEGER
UTF8_STRING Text encoded in UTF-8 character set plus tab and newline.
other
3.6 Console
Command
Description
console eval
script
console hide
console show
(Windows and Mac only) Evaluate the script argument as a Tcl script in the console interpreter.
console title
?string ?
consoleinterp
eval script
consoleinterp
record script
(Windows and Mac only) Hide the console window from view.
(Windows and Mac only) Display the console window. The console window replaces the real console
for input and output on platforms that do not have a real console. It is implemented as a separate
interpreter with the Tk toolkit loaded, and control over this interpreter is given through the console
command.
(Windows and Mac only) Change name of console window totitle. Without string, returns the console
window title.
(Windows and Mac only) Evaluates script as a Tcl script at the global level in the main interpreter.
(Windows and Mac only) Records and evaluates script as a Tcl script at the global level in the main
interpreter as if script had been typed in at the console.
Description
Insert tab (/t) chanacter.
Causes the current line to be passed to the main interpreter for evaluation.
Deletes the selected text (if any selected) or character right of the cursor.
Deletes the selected text (if any selected) or character left of the cursor.
Moves cursor to the start of the line after prompt.
Moves cursor to the end of the line.
Selects the previous entry in the command history.
Selects the next entry in the command history.
Moves the cursor one character backwards (left) if not at prompt.
Moves the cursor one character forwards (right) if not at end of the line.
Deletes the character to the right of the insertion cursor.
<Meta-d>
<Control-k>
<Control-t>
Reverses the order of the two characters to the right of the insertion cursor.
<Control-h> or
<Meta-BackSpace>
<F9>
<Insert>
<Keypress>
Rebuilds console window by destroying all its children and reloading the Tcl script that
defined the consoles behaviour.
Inserts selected text into console window
Insert character into entry widget.
<<Copy>>
<<Cut>>
<<Paste>>
3.7 Dialogs
Command
Description
tk_chooseColor ?option Creates a pop-up dialog box for the user to choose a color and returns the selected color. See
Colors in Options and Resources for color formats. Options are:
value ...?
-initialcolor color
-parent window
-title string
tk_chooseDirectory
?option value ...?
-initialdir directory
-mustexist boolean
-parent window
-title string
(Tk 8.3+) Creates a pop-up dialog box for the user to select a directory and returns the selected
directory. Options are:
Use directory as initial directory. Default is current working directory. If initial directory is a
relative path, the returned path will be the absolute path.
Specifies whether only existing directories can be selected. Default is false.
Makes window the parent of dialog.
Specifies the dialog window title.
Creates a pop-up modial dialog box, does a local grab, and waits for a response. Window is the
top-level window to use (destroys window if it already exists). Title specifies the dialog
window title. Text specifies the message to display in the dialog. Bitmap specifies the bitmap
tk_dialog window title
(See Default Bitmaps in Options and Resources) to display to the left of the message or no
text bitmap default string
bitmap if set to an empty string. Default specifies the index of the default button (0 is the
?string ...?
leftmost button) or no default if set to an empty string or negative number. Creates a button at
the bottom of the dialog for each string arg. When done the dialog is destroyed and the index of
the button selected is returned.
tk_getOpenFile ?option Creates a pop-up dialog box for the user to choose an existing filename and returns the choice.
Non-existant files are rejected with an error prompt. Options are:
value ...?
-defaultextension
extension
String to append to filename if user enters a filename without an extension. Default is empty
string or reasonable guess based on -filetypes, if specified.
-filetypes
filePatternList
List of file types the user can choose from for determining which types of files to display, if
supported by the platform. Format of elements: {{description {extensions ...} ?{MacTypes
...}?} ...}
Use directory as initial directory. Default is current working directory. If initial directory is a
relative path, the returned path will be the absolute path.
-initialdir directory
-initialfile fileName
-multiple
-message string
-parent window
(Tk 8.4+) Allows the user to choose multiple files from the Open dialog.
(Tk 8.4+) Specifies a message to include in the client area of the dialog on Macs.
Makes window the parent of dialog.
-title string
tk_getSaveFile ?option
value ...?
Creates a pop-up dialog box for the user to choose a filename and returns the choice. If an
existing file is selected, another pop-up is displayed to confirm the choice. Options are:
-defaultextension
extension
String to append to filename if user enters a filename without an extension. Default is empty
string or reasonable guess based on -filetypes, if specified.
-filetypes
filePatternList
List of file types the user can choose from for determining which types of files to display, if
supported by the platform. Format of elements: {{description {extensions ...} ?{MacTypes
...}?} ...}
Use directory as initial directory. Default is current working directory. If initial directory is a
relative path, the returned path will be the absolute path.
-initialdir directory
-initialfile fileName
-message string
-parent window
(Tk 8.4+) Specifies a message to include in the client area of the dialog on Macs.
Makes window the parent of dialog.
-title string
Creates a message dialog with an application-defined message, an icon and a set of buttons.
tk_messageBox ?option Returns the unique symbolic name of button pressed by the user. Not re-entrant, so multiple
value ...?
dialogs will interfere with each other. Options are:
-default name
Make button name the default. See -type for button names.
-detail string
-icon iconImage
-message string
Specifies an auxiliary message below -message in a less emphasized font (if available).
Specifies the icon to display. Options are: error, info (default), question, or warning .
Specifies the message to display in the message box.
-parent window
-title string
-type buttonType
Specifies which set of buttons to display. Options and symbolic names are: abortretryignore
(abort,retry, and ignore buttons), ok (ok button), okcancel (ok and cancel buttons),
retrycancel (retry and cancel buttons), yesno (yes or no buttons), or yesnocancel (yes, no,
and cancel buttons). Default is ok.
Description
entry pathName Creates an entry widget pathName with options and returns the new widgets path name. When
?options?
invoked, pathName must not exist, but pathNames parent should. An entry widget is used to display
and/or allow alterations to one line of text.
Entry Options
Standard
See Common Options and Resources in Options and Resources for full details.
-background
-highlightcolor
-relief
-borderwidth
-highlightthickness
-selectbackground
-cursor
-insertbackground
-selectborderwidth
-insertborderwidth
-selectforeground
-insertofftime
-takefocus
-font
-insertontime
-textvariable
-foreground
-insertwidth
-xscrollcommand
-highlightbackground
-justify
Entry Specific
Configure Option
Resource Name
Resource Class
Description
-disabledbackground disabledBackground DisabledBackground (Tk 8.4+) Background color of widget when the
color
entry is disabled. If set to the empty string, the
normal background color is used.
-invalidcommand
invalidCommand
InvalidCommand
(Tk 8.3+) Specifies script to eval when
script
-validcommand returns 0. If set to the empty
string (default), disables option. Typically set to
bell. See Percent Substitutions below for valid %
substitutions. (Also -invcmd).
-readonlybackground readonlyBackground ReadonlyBackground (Tk 8.4+) Background color of widget when the
color
entry is read-only. If set to the empty string, the
normal background color is used.
-show char
show
Show
Show char instead of the actual characters for
each character in entry.
-state state
state
State
State of entry. Options are: disabled (cannot
change or select contents, uses
disabledforeground and background), normal
(can change and select contents, uses
foreground and background), or readonly (Tk
8.4+, cannot change but can select contents).
-validate mode
validate
Validate
(Tk 8.3+) Specifies validation mode. See
Validation Types below for options.
-validatecommand
validateCommand
ValidateCommand
(Tk 8.3+) Specifies script to eval when entry
script
input is to be validated. If set to the empty string
(default), disables option. Script must return 1 to
accept or 0 to reject new value. See Percent
Substitutions below for valid % substitutions.
(Also -vcmd).
-width width
width
Width
Width of entry window in font average-sized
characters. If <=0, auto size based on current
text.
Validation Types
Type
none
Description
Do not perform validation (default).
focus
focusin
focusout
key
all
Percent Substitutions
Form Description
%d (Tk 8.3+) Type of action: 1 for insert, 0 for delete, or -1 for focus, forced, or textvariable validation.
%i
%P
(Tk 8.3+) The value of the entry should -validatecommand accept the new entry. When configuring to a new
textvariable, this will be the value of that textvariable.
%s
(Tk 8.3+) The current value of entry before -validatecommand accepts the new entry.
%S
(Tk 8.3+) The text string being inserted/deleted, if not an empty string {}.
%v
(Tk 8.3+) The current validation type (none, focus, focusin,focusout, key, or all).
%V (Tk 8.3.1+) The type of validation that triggered the callback (key, focusin, focusout, forced).
%W (Tk 8.3+) The name of the entry widget.
Description
A decimal number giving the position or index (starting from 0) of the desired character within the entry
string. If number < 0, the 0 is used, if number > length of text list, then end is used.
anchor
Selection anchor point as set by the select from and select adjust commands.
end
Character or coordinate just after last one in entrys string.
insert
Character just after the insertion cursor.
sel.first
First character in selection.
sel.last
Character just after last character in selection.
@number Character at the x-coordinate point in the entrys window. If x is outside the entry windows range, it is set to
the nearest legal value.
Command
Description
Returns a list of four elements x y w h , giving an approximate bounding box for the character
at position index . Coordinates x,y are top-left corner of character at index,w is width of char,
and h is height of char in pixels.
pathName cget option
Returns the current value of the configuration option. See Entry Widget Options above for
options .
pathName configure
Change the configuration option to value. Without value, a list describing option is returned.
?option? ?value? ?option Without option, a list of all available options for pathName is returned. For multiple options
value ...?
an empty string is returned. See Entry Widget Options above for options.
pathName delete first
Delete characters in entrys string from position first up to but not including position last
?last?
(default is first+1 to delete 1 character). See Indicies or Character Positions above for first and
last options.
pathName get
Returns the entrys string.
pathName icursor index Display the insertion cursor just before the character at position index. See Indicies or Char
Positions above for index options.
pathName index index
Returns the numerical index corresponding to index. See Indicies or Character Positions above
for index options.
pathName insert index
Insert string just before the character at position index. See Indicies or Character Positions
above for index options.
string
pathName scan option
Implements scanning on entry widgets. Options are:
args
mark x
Records x and the current view in the entry window. Typically associated with mouse button
press in widget.
dragto x
Adjusts the view by 10 times the difference between the coordinate x and the last mark x
coordinate. Used with mouse motion events to produce high speed dragging.
pathName selection
Manipulates the selection within an entry based on option. See Indicies or Char Positions
above for index options. Vaild options and args are:
option arg
adjust index
Adjust the end of the selection nearest to the character given by position index to include
characters up to index and set the other end to be the anchor point. Works the same as
selection to if selection is not in entry widget.
clear
Clear the selection if it is in the widget.
from index
Sets the selection anchor point to the character just before position index.
present
Returns 1 if characters are selected in the entry, 0 if not.
range start end
Sets the selection to include characters from position start up to but not including position end.
to index
If index < anchor point, set the selection to include characters from position index up to but not
including the anchor point. If index > anchor point, set the selection to include characters from
the anchor point up to but not including position index. If index = anchor point, no change is
made. If the selection isnt in the entry widget, use the most recent anchor point specified for
the widget.
pathNamevalidate
(Tk 8.3+) Forces the evaluation of -validatecommand by temporarily setting validate to all
and returns result.
pathName xview ?option Query or change the horizontal entry widget view. Without any options, returns a two element
args?
list specifying the start and end of the visible fraction (from 0 to 1) of the horizontal span of
the widget between the left and right edges of the window. Vaild options and args are:
index
Adjust window view to display the character at position index at the left edge of window. See
Indicies or Char Positions above for index options.
moveto fraction
Adjust window view so that fraction (from 0 to 1) of the total width of the widget is off-screen
to the left.
scroll number pages
Shift the view left (number < 0) or right (number > 0) by number screenfuls.
scroll number units
Shift the view left (number < 0) or right (number > 0) by number average-width characters.
pathName bboxindex
Description
Positions the insertion cursor just before the character underneath the mouse cursor,
sets the input focus to this widget, and clears any selection in the widget.
Drags out a selection (in words if double clicked) between the insertion cursor and the
character under the mouse.
Selects the word under the mouse and positions the insertion cursor at the beginning of
the word.
Selects all of the text in the entry and positions the insertion cursor before the first
character.
Adjusts the end of the selection (in words if double clicked) that was nearest to the
mouse cursor when button 1 was pressed.
Position the insertion cursor in the entry without affecting the selection.
Adjusts view in entry left or right more quickly.
Stops adjustment of view in entry left or right more quickly.
Paste selection into the entry at the position of the mouse cursor.
Adjusts view in entry by scrolling left or right.
Moves the insertion cursor one character back (left), clears any selection in the entry,
and sets the selection anchor.
Moves the insertion cursor one character forward (right), clears any selection in the
entry, and sets the selection anchor.
Move the insertion cursor one character back (left) and extend the selection to include
the new character.
Move the insertion cursor one character forward (right) and extend the selection to
include the new character.
Move the insertion cursor back (left) by one word, clears any selection in the entry, and
sets the selection anchor.
Move the insertion cursor forward (right) by one word, clears any selection in the
entry, and sets the selection anchor.
Move the insertion cursor back (left) by one word and also extend the selection.
Move the insertion cursor forward (right) by one word and also extend the selection.
Move the insertion cursor to the beginning of the entry and clear any selection in the
entry.
Move the insertion cursor to the beginning of the entry and also extends the selection to
that point.
Move the insertion cursor to the end of the entry and clear any selection in the entry.
Move the insertion cursor to the end of the entry and also extends the selection to that
point.
Set the selection anchor to the position of the insertion cursor without affecting the
selection.
Adjusts the selection to the current position of the insertion cursor, if there is one,
otherwise it selects from the anchor to the insertion cursor.
<Control-slash>
<Control-backslash>
<Delete>
<BackSpace> or <Control-h>
Deletes the selection, if there is one, otherwise it deletes the character to the left of the
insertion cursor.
<Control-d>
<Meta-d>
<Control-k>
<Control-t>
<Keypress>
<<Copy>>
<<Cut>>
<<Paste>>
3.9 Fonts
Command
Description
Returns actual value for fonts option on windows (default is main window) display.
font actual font ?-displayof
Without option, a list of all option and value pairs is returned. See Font Descriptions and
window? ?option?
Font Options below for font and option values, respectively.
font configure fontname
?option? ?value? ?option
value ...?
Sets each option to specified value for fontname. Without value, the current value of option
is returned. Without option, a list of all option and value pairs is returned. For multiple
options an empty string is returned. See Font Options below for options.
Create a new font fontname and returns the font name. Without fontname default naming
convention is font# where # is an integer. See Font Options below for options.
Delete all of the specified fonts. Does not remove font if it is in use by a widget until all
instances are released.
Returns a list of all font families defined on windows display (default is main window).
Returns width of string text (except /n and /t) in pixels using font in window (default is main
window). See Font Descriptions below for font.
Returns value of fonts metric option on windows (default is main window) display.
Without option, a list of all option and value pairs is returned. See Font Metrics and Font
Options below for valid font metrics andoption values, respectively.
font names
Font Description
The valid forms for the font options above are as follows. The form used is the first match meeting the match criteria.
Font
name
Match
1. fontname
Exact
only
2. systemfont
Exact
only
Description
Name of font created using font create. When used, wont cause error even if corresponding
attrributes are invalid. If font with exact attributes cant be displayed, another close font will be
substituted automatically.
Name of platform-specific font interpreted by graphics server. See Platform Specific Fonts below.
family
A list where the first element the font family name, the optional second element is desired size (See
Closest
-size in Font Options), and the optional style options are: normal or bold, roman or italic
3. ?size?
match
,underline, and overstrike.
?style ...?
X-font
4.
name
option
value
5.
?option
value ...?
Font Options
Option
-family name
-size size
Description
Specifies case-insensitive font family name . See Default Cross-Platform Fonts below for supported
names.
Specifies font size in points (or pixels if negative). If invalid, a close size will be used. A size of 0 uses
the platform specific default.
-weight weight
-slant slant
-underline
boolean
-overstrike
boolean
Font Metrics
The valid font metric options are as follows. The baseline of a font is the horizontal line where the bottom of most letters
(without descenders) line up.
Metric
-ascent
Description
Returns the distance in pixels that the tallest letter sticks up above the baseline of the font, plus any extra blank
space added by the designer of the font.
-descent Returns the distance in pixels that any letter sticks down below the baseline of the font, plus any extra blank
space added by the designer of the font.
-linespace The vertical distance in pixels between the baseline of two lines of text using the same font so that characters
do not overlap. Usually this is the sum of the ascent above the baseline line plus the descent below the
baseline.
-fixed
Returns a 1 is the font is fixed-width or 0 if it is proportionally-spaced.
Courier New
Times (*)
Arial
Bookman
Courier (*)
Geneva
Helvetica (*)
Monaco
New York
Palatino
Symbol
All valid X font names, including those listed by xlsfonts, are available.
MS Windows:
ansi
ansifixed
device
oemfixed
system
systemfixed
Mac:
system
application
Description
frame pathName
?options?
Creates a frame pathName with options and returns the new widgets path name. A frame widget is
used as a spacer or container for complex window layouts.
Frame Options
Standard
See Common Options and Resources in Options and Resources for full details.
-borderwidth
-highlightcolor
-cursor
-highlightthickness
-relief
-highlightbackground
-takefocus
Frame Specific
Configure
Option
-background
color
Resource
Resource
Description
Name
Class
background Background Same as standard -background expect if set to empty string, the widget
will not display or allocate a colormap entry for the background or border
color.
class
Class
Specifies class name to use in querying the option database and for
bindings. Can not be changed with configure command.
colormap
Colormap
Specifies colormap (default is same as parent) to use for the window where
colormap can be new (allocate new colormap) or the name of another
window on same display with same visual. Can not be changed with
configure command.
-container
boolean
container
Container
-height height
height
visual
Height
Visual
width
Width
-class name
-colormap
colormap
-visual visual
-width width
Frame Commands
Command
Description
Returns the current value of the configuration option. See Frame Options above for options.
Change the configuration option tovalue. Without value, a list describing option is returned.
Without option, a list of all available options for pathName is returned. For multiple options an
empty string is returned. See Frame Options above for options.
Description
(Tk 8.5+) Specifies how to place the grid within the master when no row/column has any
weight. Valid anchor values: n, ne, e, se ,s ,sw ,w ,nw, or center (default).
grid bbox master ?column Returns a 4 element list describing the bounding box in pixels of the space occupied by area
row? ?column2 row2?
spanning between given cells. With only column and row , returns bounding box for
specified cell (top left cell is 0). Without options, returns bounding box of grid as a list of
integers (column1 row1 column2 row2).
Set or query column properties of index column(s) in grid master. Index may be a list of
grid columnconfigure
column indicies. Without value, the current value is returned for option. Witout option, all
master index ?option value
current option and value pair settings are returned. In Tk 8.5+, index can be all in order to
...?
apply to all columns.
-minsize size
-pad amount
Padding in screen units to add to the largest window contained completly in column(s) index
when grid requests their sizes.
-uniform value
-weight int
(Tk 8.4+) Places the column in a uniform group with other columns that have the same value
for -uniform. Not used if set to empty value.
Relative weight for apportioning extra space among columns. Columns with a weight of 0,
will not deviate from requested size.
Set or query how slave windows should be managed by the grid geometry master. Unless the
grid configureslave ?slave
slave was previously managed, options not specified will be set to their default values. See
...? ?option value ...?
Grid Relative Placement below for alternate slave options.
-column n
-columnspan n
-in other
-ipadx amount
-ipady amount
-padx amount
-pady amount
-row n
-rowspan n
Insert the slave so that it occupies the n th column in the grid. Default is just to right of
previously specified slave or 0 if none. Column numbers start with 0. Each use of "x"
preceding slave increments the column position by 1.
Insert the slave so that it occupies n columns (default is 1) in the grid. Each use of "-"
following the slave name increments the column span by one.
Insert the slave(s) in the master window given by other (default is first slaves parent
window).
Specifies amount (default is 0), in screen units, of horizontal internal (added to border)
padding to leave on each side of slave(s).
Specifies amount (default is 0), in screen units, of vertical internal (added to border) padding
to leave at the top and bottom of slave(s).
Specifies horizontal external (outside of border) padding amount (default is 0), in screen
units to leave on each side of slave(s). In Tk 8.4+, amount may be a two element list
consisting of left and right padding values.
Specifies vertical external (outside of border) padding amount (default is 0), in screen units
to leave at the top and bottom of slave(s). In Tk 8.4+, amount may be a two element list
consisting of top and bottom padding values.
Insert the slave so that it occupies the nth row in the grid. Default is same as previously
specified slave or first unoccupied row if none. Row numbers start with 0.
Insert the slave so that it occupies n rows (default is 1) in the grid. If the next grid command
contains "^" characters for the same row as slave(s), then the rowspan of slave is extended
by one. The number of ^s in a row must match the number of columns spanned by the slave
above it.
-sticky style
Specifies where to position a slave within the cell if the cell is larger than the requested
dimensions. Style can be zero or more positions (n, s,e or w) with optional space and comma
separators. If both n and s (or e and w) are specified, the slave will be stretched to fill the
entire height (or width) of its cavity. The default or when set to an empty string, is to center
the slave within the cell.
grid forgetslave ?slave ...? Removes and unmaps each slave from grid and forgets their configuration options.
grid infoslave
Returns a list of option and value pairs describing the configuration state of slave. The first
two elements are "-in master" where master is the slaves master.
grid locationmaster x y
Returns column and row containing screen units x and y in master. Returns -1 if x or y is
above or to the left of the grid.
grid propagatemaster
?boolean?
Specifies whether master tries to resize its slave windows to fit grid (default) or not. Without
boolean, returns current setting.
Removes and unmaps each slave from grid and remembers their configuration options.
grid rowconfiguremaster
index ?option value ...?
Set or query row properties of index row(s) in grid master. Index may be a list of row
indicies. Without value, the current value is returned for option. Witout option, all current
option and value pair settings are returned. See Grid Relative Placement below for alternate
slave options. In Tk 8.5+, index can be all in order to apply to all rows.
-minsize size
-pad amount
Padding in screen units to add to the largest window contained completly in row(s)
indexwhen grid requests their sizes.
-uniform value
-weight int
(Tk 8.4+) Places the row in a uniform group with other rows that have the same value for
-uniform. Not used if set to empty value.
Relative weight for apportioning extra space among rows. Rows with a weight of 0, will not
deviate from requested size.
grid sizemaster
grid slavesmaster
?options?
Returns a list of the slaves in master for the specified column and/or row . Without options,
all slaves are returned.
-column column
-row row
Effect
Increases columnspan of slave to the left.
Pack
Geometry manager that arranges the children (slaves) of a parent (master) by packing them in order (defined by packing
list) in the packing cavity around the edges of the parent. The packer allocates a rectangular parcel for the slave along the
side of the cavity given by the slaves -side option. See Coordinates in Options and Resources for screen unit options.
Command
Description
Sets how slave windows should be managed by the packer. Valid options are:
Insert slaves after widget sibling in the packing order of siblings master.
-anchor anchor
Where to position slave in master window when smaller then the allocated space. Valid anchor
values: n, ne, e, se ,s ,sw ,w ,nw, or center (default).
-before sibling
Insert slaves before widget sibling in the packing order of siblings master.
-expand boolean
Specifies whether the slaves should expand to consume extra space in their master or not (default).
-fill style
Specifies whether slaves should be stretched if the allocated space is larger than the requested
dimensions. Options are: none (use requested dimensions plus internal padding), x (stretch slave
horizontally to fill allocated space with room left over for padding), y (stretch slave vertically to fill
allocated space with room left over for padding), or both (do both x and y stretching).
Insert slave at the end of the packing order in window master.
Specifies amount of horizontal internal padding to leave on each side of slave in screen units (default
is 0).
Specifies amount of vertical internal padding to leave on each side of slave in screen units (default is
0).
Specifies amount of horizontal external padding to leave on each side of slave in screen units
(default is 0). In Tk 8.4+, amount can be a list of two values for the left and right side padding.
-in master
-ipadx amount
-ipady amount
-padx amount
-pady amount
-side side
pack forget slave
?slave ...?
pack info slave
pack propagate
master ?boolean?
Specifies amount of vertical external padding to leave on each side of slave in screen units (default is
0). In Tk 8.4+, amount can be a list of two values for the top and bottom side padding.
Specifies which side of the master the slave(s) will be packed against. Options are left, right,top, or
bottom.
Removes and unmaps each slave from the packing order and forgets their configuration options.
Returns a list of option and value pairs describing the configuration state of slave . The first two
elements are "-in master" where master is the slaves master.
Specifies whether window master tries to resize its slave windows for geometry propagation
(default) or not. Without boolean, returns current setting.
pack slaves master Returns a list of the slaves in the packing order for window master. If none, empty string is returned.
Place
Geometry manager for fixed placement, where the size and location of slave windows is user specified within another
window called the master. The placer also provides rubber-sheet placement, where the user specifies the size and location
of the slave in terms of the dimensions of the master, so that the slave changes size and location in response to changes in
the size of the master. The placer supports mixing both styles of placement for slaves.
Command
Description
placewindow option
value ?option value ...?
place configure window
?option? ?value?
?option value ...?
-anchor anchor
-bordermode style
-height size
-in master
-relheight size
-relwidth size
-relx location
-rely location
-width size
-x location
-y location
place forgetwindow
Change the configuration option tovalue for the slave given by window. Without value, a list
describing option is returned. Without option, a list of all available options for pathName is
returned. For multiple options an empty string is returned. Valid options are:
Anchor specifies which point of window is to be positioned at coordinate x,y as defined by
-relx, -rely ,-x,and -y. Valid anchor values: n, ne , e,se,s,sw,w,nw (default), orcenter.
Specifies the degree to which borders within the master are used in determining the placement
of the slave. Options are: inside (default) where placer only uses innermost area of master
inside any border, outside where placer considers area to include border, or ignore where
placer ignores borders and like X windows includes internal border but not external border.
Specifies the height, including border, forwindow in screen units. Default or when set to empty
string is to auto size.
Specifes the path name of the window relative to which window is to be placed. Master must be
the parent or descendent windows parent and in the same top level window. Default is to use
windows parent.
Specifies the floating point (0 to 1) height relative to the master. If used with -height, both
values are summed before use.
Specifies the floating point (0 to 1) width relative to the master. If used with -width, both
values are summed before use.
Specifies the floating point x-coordinate of the anchor point for window relative to the master,
where 0 is the left edge and 1 is the right edge. Location need not lie within the bounds of the
master window. If used with -x, both values are summed before use.
Specifies the floating point y-coordinate of the anchor point for window relative to the master,
where 0 is the top edge and 1 is the bottom edge. Location need not lie within the bounds of the
master window. If used with -y, both values are summed before use.
Specifies the width, including border, for window in screen units. Default or when set to empty
string is to auto size.
Specifies the x-coordinate in screen units of the anchor point for window in master.Location
need not lie within the bounds of the master window.
Specifies the y-coordinate in screen units of the anchor point for window in master. Location
need not lie within the bounds of the master window.
Placer will stop managing and unmap window.
place infowindow
Returns a list of option and value pairs describing the configuration state of window. In Tcl
8.4.2+, the first two elements are "-in master" where master is the windows master.
place slavesmaster
Returns a list of the slaves for window master. If none, empty string is returned.
3.12 Images
Image Commands
Command
Description
Creates new image name (default is image# where # is an integer) of type with options and returns
the path name. If name already exists, it is replaced. Type can be either bitmap or photo. See Bitmap
Image Options or Photo Image Options below for options. Dont use the same name as an existing
command, or the command will be overwritten.
image delete
?name ...?
Deletes each of the image names. If an image is in use by a widget, it wont be deleted until all
instances are released. Deleteing a widget using an image does not delete the image.
image types
Returns a list of valid image types (Tk defaults are: bitmap and photo).
Bitmap Image
Options
Description
-background color
Set background color for bitmap. If set to an empty string, the background pixels will be
transparent.
-data string
Specify contents of bitmap in X11 bitmap program format as a string. Takes precedence
over -file.
-file fileName
Use fileName as the source of the bitmap image. The bitmap must be in X11 bitmap
program format.
-foreground color
-maskdata string
Specify contents of mask in X11 bitmap program format as a string. Takes precedence
over -maskfile.
-maskfile fileName
Use fileName as the source of the mask image. The bitmap must be in X11 bitmap
program format.
Description
Returns the current value of the configuration option for image imageName. See Bitmap
Image Options above for options.
imageName configure?option? Change the configuration option for the image imageName to value. Without value, a list
?value? ?option value ...?
describing the option is returned. Without option, a list describing all of the available
options for imageName is returned. For multiple options an empty list is returned. Option
may have any of the values accepted by the image create bitmap command. See Bitmap
Image Options above for options.
imageName cgetoption
Photo
Image
Options
Description
-format
formatName
Specify contents of image as a string in a supported format. The string can contain base64 encoded data
or binary data. Takes precedence over -file. Supports PGM and PPM in Tk 8.4.7+.
Specify format for data specified with the -data or -file options. The gif, pgm, and ppm formats are
supported for reads and gif87, gif89, pgm, and ppm formats are supported for writes.
-file fileName
Use fileName as the source of the photo image for a supported format.
-data string
-gamma value
-height height
(Tk 8.4+) Correct the colors allocated for displaying this image for a non-linear display with the
specified gamma exponent value. Value must be > 0, default is 1 (no correction). Value > 1 will make
image lighter, Value < 1 will make image darker.
Specifies the height of the image, in heightpixels. Use 0 (default) to allow the image to expand or
shrink vertically to fit the data.
-palette
paletteSpec
Set the resolution of the color cube (number of colors) to be allocated for image. String paletteSpec can
be a single decimal number to specify the number of shades of gray to use (monochrome), or three
decimal numbers separated by slashes (/), to specify the number of shades of red, green and blue to use,
respectively.
-width width
Specifies the width of the image, in widthpixels. Use 0 (default) to allow the image to expand or shrink
horizontally to fit the data.
The commands that write data to the image can expand the size of the image if necessary unless -width and/or -height are
specified to prevent changing the image size. The following are the valid commands for photo images:
Photo Image Command
Description
imageName blank
imageName cgetoption
Returns the current value of the configuration option for image imageName. See Photo
Image Options above for options.
imageName configure ?option? Change the configuration option for the image imageName to value. Without value, a
?value? ?option value ...?
list describing the option is returned. Without option, a list describing all of the available
options for imageName is returned. For multiple options an empty string is returned. See
Photo Image Options above for options.
imageName copy sourceImage
Copy a region from sourceImage to imageName using given options.
?option value ...?
-compositingrule rule
-from x1 y1 x2 y2
-shrink
-subsample x y
-to x1 y1 x2 y2
-zoom x y
(Tk 8.4+) Specifies how transparent pixels in sourceImage are combined with
imageName. Rule overlay (default) specifies the sourceImage should be overlayed on
imageName. Rule set specifies imageName be replaced by sourceImage.
Specifies rectangular sub-region (default is whole image) of the image in sourceImage
to copy into imageName where (x1,y1) is the top left and (x2,y2) is the bottom right (or
bottom right corner if not specified). Includes the left and top edges but not the bottom
or right edges.
Will shrink image in sourceImage so it fits within the current bottom-right corner of
imageName without affecting the image create settings for -height or -width.
Reduces source region of sourceImage by using only every xth and yth pixel in
respective direction when copying to imageName. Negative values will cause image to
be flipped about the respective axis. If not specified, y defaults to same value as x.
Specifies rectangular sub-region of imageName into which sourceImage will be copied
with tiling if necessary, where (x1,y1) is the top left and (x2,y2) is the bottom right (or
bottom right corner if not specified). Without x2 and y2, the default is (x1,y1) plus size
of sourceImage.
Magnifies source region in sourceImage by x and y in respective direction in
imageName. If not specified, y defaults to same value as x. Both x and y must be > 0.
imageName data ?option value (Tk 8.3+) Returns image data in the form of a string. Options are:
...?
-background color
If specified, all transparent pixels will be replaced with color.
-format formatName
Specify format for imageName (default is auto select). The GIF, PGM, PPM formats
are supported.
-from x1 y1 x2 y2
Specifies rectangular sub-region (default is whole image) of the image in imageName to
return where (x1 ,y1) is the top left and (x2,y2) is the bottom right (or bottom right
corner if not specified). Includes the left and top edges but not the bottom or right edges.
-grayscale
Image data will be returned in grayscale format.
imageName getx y
Returns a 3 element list representing the RGB color components of the pixel at (x,y) in
imageName.
imageName putdata ?option
value ...?
-format formatName
-from x1 y1 x2 y2
-shrink
-to x y
imageName readfileName
?option value ...?
-format formatName
-from x1 y1 x2 y2
-shrink
-to x y
Inserts data from string data into imageName using given options.
(Tk 8.3+) Specify format for data (default is auto select). The GIF, PGM, PPM formats
are supported.
(Tk 8.3+) Specifies rectangular sub-region (default is whole image) of the image in data
to put into imageName where (x1,y1) is the top left and (x2,y2) is the bottom right (or
bottom right corner if not specified). Includes the left and top edges but not the bottom
or right edges.
(Tk 8.3+) Will shrink image in data so it fits within the current bottom-right corner of
imageName without affecting the image create settings for -height or -width.
Specifies the top left corner (x,y) of the region (default is 0,0) within imageName, into
which the pixels from the image in data will be put. In Tk versions up to 8.2.3, args are
x1 y1 x2 y2.
Reads image data from fileName into imageName using given options.
Specify format for fileName (default is auto select). The GIF, PGM, PPM formats are
supported.
Specifies rectangular sub-region (default is whole image) of the image in fileName to
read into imageName where (x1,y1) is the top left and (x2,y2) is the bottom right (or
bottom right corner if not specified). Includes the left and top edges but not the bottom
or right edges.
Will shrink image from fileName so it fits within the current bottom-right corner of
imageName without affecting the image create settings for -height or -width.
Specifies the top left corner (x,y ) of the region (default is 0,0) within imageName, into
which the pixels from the image in fileName will be put.
imageName redither
Redither the image. Used when multiple pieces are used for an image and dithering isnt
exact.
imageName transparency
subcommand ?arg ...?
get x y
set x y boolean
imageName writefileName
?option value ...?
-background color
-format formatName option
-from x1 y1 x2 y2
-grayscale
Description
label pathName Creates a label widget pathName with options and returns the new widgets path name. When invoked,
?options?
pathName must not exist, but pathNames parent should. A label widget is used to display a text string,
bitmap, or image. Multiple fonts within the text string are not supported.
See Common Options and Resources in Options and Resources for full details.
-activebackground (Tk 8.3.2+)
-padx
-font
-pady
-anchor
-foreground
-relief
-background
-highlightbackground
-takefocus
-bitmap
-highlightcolor
-text
-borderwidth
-highlightthickness
-textvariable
-compound (8.4+)
-image
-underline
-cursor
-justify
-wraplength
Configure
Option
-height
height
-state state
Resource
Name
height
Resource
Class
Height
state
State
-width
width
width
Width
Description
Height of label widget (default is to auto size) in screen units (bitmap or image) or
lines of text (text).
(Tk 8.3.2+) State of label widget. Options are: active (use activeforeground and
activebackground), disabled (use disabledforeground and background),
normal (use foreground and background).
Width of label widget (default is to auto size) in screen units (bitmap or image) or
characters (text).
Command
pathName cget option
Returns the current value of the configuration option. See Label Widget Options above for
options .
pathName configure
Change the configuration option tovalue. Without value, a list describing option is returned.
?option? ?value? ?option Without option, a list of all available options for pathName is returned. For multiple options an
value ...?
empty string is returned. See Label Wiget Options above for options.
Description
labelframe
pathName
?options?
(Tk 8.4+) Creates a labelframe widget pathName with options and returns the new widgets path name.
When invoked, pathName must not exist, but pathNames parent should. A labelframe widget is used
as a container for complex window layouts and has the featues of a frame plus the capability to display
a label.
See Common Options and Resources in Options and Resources for full details.
-borderwidth
-cursor
-font
-foreground
-highlightbackground
-highlightcolor
-highlightthickness
-padx
LabelFrame Specific
-pady
-relief
-takefocus
-text
Configure
Option
-background
color
Resource
Resource
Description
Name
Class
background Background Same as standard -background expect if set to empty string, the widget
will not display or allocate a colormap entry for the background or border
color.
class
Class
Specifies class name to use in querying the option database and for
bindings. Can not be changed with configure command.
colormap
Colormap
-container
boolean
container
Container
-height height
-labelanchor
anchorPos
-labelwidget
pathName
height
Height
Height of frame in screen units.
labelAnchor LabelAnchor Specifies where to position label in widget. Valid anchorPos values: n,
ne,en ,e,es,se,s,sw,ws,w,wn , and nw (default).
labelWidget LabelWidget Widget to use as the label in the frame. Overrides -text option. Widget
must already exist.
visual
Visual
Specifies the visual to use for the widget if different from parent. See
Screen or Window Visuals in Toplevel for visual options. Can not be
changed with configure command.
-class name
-colormap
colormap
-visual visual
-width width
width
Width
Labelframe Commands
Description
Command
pathName cget option
Returns the current value of the configuration option. See Labelframe Options above for
options .
pathName configure
Change the configuration option tovalue. Without value, a list describing option is returned.
?option? ?value? ?option Without option, a list of all available options for pathName is returned. For multiple options an
value ...?
empty list is returned. See Labelframe Options above for options.
Description
listbox
pathName
?options?
Creates a listbox widget pathName with options and returns the new widgets path name. When
invoked, pathName must not exist, but pathNames parent should. A listbox widget is used to display a
list of strings, one per line. Listbox widgets are only one column.
See Common Options and Resources in Options and Resources for full details.
-background
-foreground
-selectborderwidth
-borderwidth
-highlightbackground
-selectforeground
-cursor
-highlightcolor
-setgrid
-highlightthickness
-takefocus
-relief
-xscrollcommand
-font
-selectbackground
-yscrollcommand
Configure
Option
-activestyle
style
Resource
Name
activeStyle
-heightheight height
Resource
Description
Class
ActiveStyle (Tk 8.4+) Style in which to draw active element. Style options are: dotbox to
show a focus ring around the active element, none, or underline (default) to
underline the active element.
Height
Height of window (0 or default is to auto size) in lines of text.
-listvariable
var
listVariable Variable
-selectmode
mode
selectMode SelectMode Specifies selection manipulation mode. Mode can be: single where only 1
element can be selected at a time, browse (default) where only 1 element can
be selected or dragged at a time, multiple where multiple elements can be
selected without affecting other selections, or extended where multiple
elements can be selected but other selected elements become deselected.
state
State
(Tk 8.4+) State of label widget. Options are:disabled where items cannot be
inserted or deleted (use disabledforeground and background) or normal
(use foreground and background).
width
Width
Width of window (0 or default is to auto size) in characters (for proportional
fonts, char size is for character "0").
-state state
-width width
(Tk 8.3+) Specifies name of variable var which contains a list to be displayed
in the listbox. Automatically updates listbox when var is altered. Unsetting
var while in use by the listbox, will be ignored.
Description
A decimal number giving the index (starting from 0) of the element in the listbox. If number < 0, the 0 is used,
if number > number of elements, then end is used.
Indicates the element that has the location cursor.
Selection anchor point as set by the selection anchor command.
Indicates the end of the listbox. Usually this is last element in the listbox, but for a few commands such as
index and insert it refers to the element just after the last one.
Indicates the element that covers coordinate x,y (pixel units) in the listbox window. If outside the window, it is
set to the nearest legal value.
Description
Sets active element (for by keybaord bindings) in listbox to index. If outside the listbox range,
it is set to the nearest element.
Returns a list of four elements x y w h , giving an approximate bounding box of the text in
element index . Coordinates x,y are top-left corner of text at index ,w is width of text, and h is
pathName bboxindex
height of text in pixels. Returns an empty string if element index is not visible on the screen or
is invalid.
pathName cget option
Returns the current value of the configuration option. See Listbox Widget Options above for
options .
pathName configure
Change the configuration option to value. Without value, a list describing option is returned.
?option? ?value? ?option Without option, a list of all available options for pathName is returned. For multiple options
value ...?
an empty string is returned. See Listbox Widget Options above for options.
pathName curselection
Returns a list of numerical indices for all of the elements in the listbox that are currently
selected or empty string if none.
pathName delete first
Deletes one or more elements in listbox from index first to index last. Without last only
?last?
element at index first is deleted.
pathName get first ?last? Returns a list of the contents of listbox elements from index first to index last (default is first).
Returns an empty string for invalid indicies.
pathName index index
Returns the numerical index corresponding to index.
pathName insert index
Insert zero or more elements just before the element at index. If index is end, new elements
?element ...?
are added to the end of the list.
pathName itemcget index (Tk 8.3+) Returns the current value of the configuration option for the element at index. See
Listbox Widget Options above for options.
option
pathName itemconfigure (Tk 8.3+) Change the configuration option for element at index to value. Without value, a list
index ?option? ?value?
describing option is returned. Without option, a list of all available options is returned. For
?option value ...?
multiple options an empty list is returned. Supported options are: -background, -foreground,
-selectbackground, and -selectforeground.
pathName nearest y
Returns the index of the visible element nearest coordinate y.
pathName scan option
Implements scanning on listbox widgets. Options are:
args
mark x y
Records x, y, and the current view in the listbox window. Typically associated with mouse
button press in widget.
dragto x y
Adjusts the view by 10 times the difference between the coordinate x,y and the last mark x ,y
coordinate. Used with mouse motion events to produce high speed dragging.
pathName see index
Adjust the view in the listbox so that the element at index is visible in the center of the listbox.
If the element is near the beginning or end then the element will be visible at the edge.
pathName selection
Manipulates the selection within a listbox based on option. Vaild options and args are:
option arg
anchor index
Sets the selection anchor to the element at index. If index is invalid, the element closest to
index will be used.
clear first ?last?
Clears from the selection the elements between indicies first and last (default is first),
inclusive, without affecting the selection state of elements outside the range.
includes index
Returns 1 if the element at index is currently selected, 0 if not.
set first ?last?
Selects all of the elements between indicies first and last (default is first), inclusive, without
affecting the selection state of elements outside the range.
pathNamesize
Returns the total number of elements in the listbox.
pathName xview ?option Query or change the horizontal listbox view. Without any options, returns a two element list
args?
specifying the start and end of the visible fraction (from 0 to 1) of the horizontal span of the
widget between the left and right edges of the window. Vaild options and args are:
index
Adjust window view to display the character at position index at the left edge of window.
moveto fraction
Adjust window view so that fraction (from 0 to 1) of the total width of the listbox widget is
off-screen to the left.
scroll number pages
Shift the view left (number < 0) or right (number > 0) by number screenfuls.
scroll number units
Shift the view left (number < 0) or right (number > 0) by number average-width characters
(proportional uses "0").
index
moveto fraction
scroll number pages
scroll number units
Query or change the vertical listbox view. Without any options, returns a two element list
specifying the start (element at top of window) and end (element just after element at the
bottom of window) of the visible fraction (from 0 to 1) of the vertical span of the widget
between the top and bottom edges of the window. Vaild options and args are:
Adjust window view to display the element at index at the top edge of window.
Adjust the view in the window so that element at fraction (from 0 to 1) is at the top edge of
the window.
Shift the view up (number < 0) or down (number > 0) by number screenfuls.
Shift the view up (number < 0) or down (number > 0) by number lines.
<B1-Leave>
<B1-Enter>
<ButtonRelease-1>
<Double-1>
<Button-2>
<B2-Motion>
<Up>
<Down>
<Shift-Up>
<Shift-Down>
<Left>
<Right>
<Control-Left>
<Control-Right>
<Prior>
<Next>
<Control-Prior>
<Control-Next>
<Home>
<End>
<Control-Home>
Description
Make the element under the mouse pointer the active element.
If the selection mode is extended, extend the selection.
If the selection mode is extended, modifies the selection to consist of the elements between the
anchor and the element under the mouse pointer, inclusive.
If the selection mode is extended, set anchor to element under the mouse pointer and toggle its
selection state. The selection state of other elements isnt changed.
If the selection mode is extended, the selection state of all elements between the anchor and the
element under the mouse is set to match that of the anchor element; the selection state of all
other elements remains what it was before the toggle operation began.
Adjusts view in listbox in direction of mouse pointer more quickly.
Stops quick adjustment of view in listbox in direction of mouse pointer.
Stops quick adjustment of view in listbox in direction of mouse pointer and activates current
listbox entry.
No function.
Mark entry for start of scanning.
Drag the contents of the listbox at high speed in the direction the mouse moves.
Move the location cursor (active element) up by one element. If the selection mode is browse
or extended then the new active element is also selected and all other elements are deselected.
In extended mode the new active element becomes the selection anchor.
Move the location cursor (active element) down by one element. If the selection mode is
browse or extended then the new active element is also selected and all other elements are
deselected. In extended mode the new active element becomes the selection anchor.
In extended mode, move the location cursor (active element) up one element and also extend
the selection to that element.
In extended mode, move the location cursor (active element) down one element and also
extend the selection to that element.
Scroll the listbox view left by the width of the character 0.
Scroll the listbox view right by the width of the character 0.
Scroll the listbox view left by the width of the window.
Scroll the listbox view right by the width of the window.
Move the location cursor (active element) and the listbox view up by one page (the height of the
window).
Move the location cursor (active element) and the listbox view down by one page (the height of
the window).
Scroll the listbox view up by one page (the height of the window).
Scroll the listbox view down by one page (the height of the window).
Scroll the listbox horizontally to the left edge.
Scroll the listbox horizontally to the right edge.
Sets the location cursor to the the first element in the listbox, selects that element, and deselects
everything else in the listbox.
<Control-End>
Sets the location cursor to the the last element in the listbox, selects that element, and deselects
everything else in the listbox.
<Shift-Control-Home> In extended mode, extends the selection to the first element in the listbox. In multiple mode,
moves the location cursor to the first element in the listbox.
<Shift-Control-End>
In extended mode, extends the selection to the last element. In multiple mode, moves the
location cursor to the last element.
<space>
Select the element at the location cursor and make it the active element.
<Select>
Select the element at the location cursor and make it the active element.
<Shift-Control-space> In extended mode, extend the selection from the anchor to the active element.
<Shift-Select>
In extended mode, extend the selection from the anchor to the active element.
<Escape>
In extended mode, cancels the most recent selection and restores all the elements in the
selected range to their previous selection state
<Control-slash>
In browse or extended modes, selects everything in the widget. In single and browse modes,
selects the active element and deselects everything else.
<Control-backslash>
In extended, multiple , and single modes, deselects everything in the widget.
<MouseWheel>
(MS Windows only) Scroll listbox vertically by several entries in direction of wheel scroll.
<Button-4>
(Unix only) Equivalent of <MouseWheel> to scroll listbox up (<4>) or down (<5>) by several
or<Button-5>
entries.
<<Copy>>
Copies the selection in the widget to the clipboard, if there is a selection.
<<ListboxSelect>>
(Tk 8.3+) Virtual event is generated whenever the selection in a listbox changes.
Description
menu pathName
?options?
Creates a top-level menu widget pathName with options and returns the new widgets path name.
When invoked, pathName must not exist, but pathNames parent should. A menu widget is used to
display a collection of one-line entries arranged in one or more columns. The several types of entries
can be combined in a single menu. The entire menu is one widget. There are three types of menus:
menubar, normal, and tearoff. For menubar and torn-off menus, a clone of the original menu is
made. This clone is a menu widget in its own right, but it is a child of the original. Changes in the
configuration of the original are reflected in the clone. Clones are destroyed when either the tearoff
or menubar is closed, or when the original menu is destroyed.
tk_menuSetFocus
pathName
tk_popup menu x y
?entry?
Used by several of the menu bindings to save the current focus and set the focus to the menu widget
pathName .
Posts a pop-up menu menu with the entry at index entry (default is menus upper left corner)
positioned at root coordinate x,y
See Common Options and Resources in Options and Resources for full details.
-activebackground
-borderwidth
-foreground
-activeborderwidth
-cursor
-relief
-activeforeground
-disabledforeground
-takefocus
-background
-font
Configure Option
-postcommand
tclCommand
Resource Name
Resource Class
postCommand
Command
Description
Specify Tcl command to invoke immediately before the
menu is posted. Returns result.
-selectcolor color
selectColor
Background
-tearoff boolean
tearOff
TearOff
-tearoffcommand
tclCommand
-title string
title
-type type
type
Title
Type
Indicies
Some menu commands support the use of an index to locate an entry within the menu starting at 0. The following are the
valid forms of specifying an index:
Index
form
number
active
end
last
none
@y
pattern
Description
A decimal number giving the entry (starting from 0) in the menu.
Indicates the entry that is currently active. If no entry is active, then this form is equivalent to none .
Entry at the bottom of the menu. If no entries, then this form is equivalent to none.
Same as end.
Indicate "no entry at all" and can be used with activate option to deactivate all entries in a widget.
Indicates the entry closest toy-coordinate (pixel units) in the menu.
Pattern is pattern-matched using Pattern Globbing against the label of each entry in the menu, in order from
the top down, until a matching entry is found.
Command
Description
Add new entry of type type to bottom of menu. See Entry Types below for types. See
Menu Entries below for options.
pathName cgetoption
Returns the current value of the configuration option. See Menu Widget Options above for
options .
pathName clone
newPathName ?cloneType?
pathName configure?option? Change the configuration option tovalue. Without value, a list describing option is
?value? ?option value ...?
returned. Without option, a list of all available options for pathName is returned. For
multiple options an empty string is returned. See Menu Widget Options above for options.
pathName delete index1
Delete all entries between index1 and index2 (default is index1) inclusive. Cant delete
?index2?
tear-off entries.
pathName entrycget index
option
Return current value of option for entry at index. See Menu Entries below for options.
pathName entryconfigure
index ?option value ...?
Change the configuration option tovalue for entry at index. Without value, a list describing
option is returned. Without option, a list of all available options for the entry is returned.
See Menu Entries below for options.
Returns the numerical index corresponding toindex or none for index none.
Insert new entry of type type to menu just before the entry at index. Entries can not be
inserted before the tearoff entry if used. See Entry Types below for types. See Menu
Entries below for options.
pathName post x y
Post or display menu pathName at root-window coordinates x,y (should be upper right
corner of entry). The coordinates are adjusted if necessary to guarantee that the entire
menu is visible on the screen.
Post submenu associated with cascade entry at index and unpost any previously posted
menu.
pathName unpost
Returns the y-coordinate within the menu window of the topmost pixel in the entry
specified by index.
Entry Types
Entry Type: Description:
cascade
Menu entry with an associated submenu specified by -menu option which allows the construction of
cascading menus. Submenus are posted and unposted via the postcascade command. Except on Windows,
the -command option is evaluated each time the entry is invoked.
checkbutton Behaves like a checkbutton widget where if invoked it toggles between selected and deselected states. Sets
the global variable specified by -variable to the -onvalue value when selected and to the -offvalue value
when deselected. The "on" indicator color is set by the -selectcolor option and the -command option is
evaluated each time the entrys state is toggled.
command
Behaves like a button widget and when invoked, the -command option is evaluated.
radiobutton Behaves like a radiobutton widget where only one entry within a group may be selected at a time. When an
entry is selected, the -value value is stored to the global variable specified by -variable and previously
specified entry is unselected. The "selected" indicator color is set by the -selectcolor option and the
-command option is evaluated each time the entrys state becomes selected.
separator
Displays a horizontal dividing line.
Menu Entries
General
The following options are valid for cascade, checkbutton, command, and radiobutton entries. They are not valid for
separator and tear-off entries.
-activebackground
-bitmap
-foreground
-activeforeground
-compound (8.4+)
-image
-background
-font
-underline
The following options work for all cascade, checkbutton, command, and radiobutton entries unless otherwise specified. See
Common Options and Resources in Options and Resources for full details.
Option
-accelerator
string
Description
Specifies string to display at right side of menu entry. Used for accelerator keystroke sequence to
invoke entry. Not valid for separator and tear-off entries.
-columnbreak
value
-command
tclCommand
When value is set to 1, entry appears at top of a new column in menu. Default value of zero puts entry
under previous entry.
-hidemargin
value
Specifies whether the standard margins are drawn (default value of 0) or not (value of 1) around the
entry.
-indicatoron
boolean
Specifies whether the checkbutton or radiobutton entry indictor should be displayed (default) or not.
-label string
Text string to display in the menu entry. Not valid for separator and tear-off entries.
Tcl command to evaluate when entry is invoked. Not valid for separator and tear-off entries.
-menu pathName Specifies pathname of submenu to post when cascade entry is active.
-offvalue value
-onvalue value
-selectcolor color
Specifies indicators color for checkbutton and radiobutton entries. The default value of empty string
sets the color to the -selectcolor option for the menu.
-selectimage
image
Specifies image to show instead of -image when checkbutton and radiobutton entries are selected.
-state state
-value value
Specifies state of entry. Options are: active (use activeforeground and activebackground),disabled
(use disabledforeground and background), normal (use foreground and background). Not valid
for separator entries.
Value to store in radiobutton entrys associated variable when selected.
-variable variable Specifies name of the global variable to set when the checkbutton or radiobutton is selected and
deselected for checkbutton.
Menu Entry Format:
Field
Name:
Main field
Description:
The main field is a label in the form of a text string, a bitmap, or an image, controlled by the -label,-bitmap,
and -image options for the entry.
Accelerator If the -accelerator option is specified for an entry, a second textual field is displayed to the right of the label.
It describes a keystroke sequence that may be used to invoke the same result as the menu entry.
Indicator
The indicator is displayed to the left of the entrys string for only checkbutton or radiobutton entries. It
indicates whether the entry is selected or not.
Description
Special Apple menu (Apple logo) that appears first on menubar. Adds users Apple Menu
Items folder to bottom of menu.
Mac
.menuName.help
Special right-justified Help menu. Adds Apple help items to top of menu.
Windows .menuName.system Windows System menu. Adds Microsoft items to top of menu.
Unix
.menuName.help
Special right-justified Help menu.
Menu Configurations
Config
Decsription
Pulldown Menus Menu widget with multiple cascade entries and associated pull down menus. Add to toplevel window
in Menubar
using the -menu option.
Pulldown Menus Menubutton widget with multiple top-level menus arranged in a row within a menubar window. Each
in Menu Buttons top-level menu can be cascade with associated submenus. The top-level menu must be a child of the
menubutton, and each submenu must be a child of the menu that refers to it.
Popup Menus
Posts the top-level menu via tk_popup in response to a mouse button press or keystroke.
Option Menus
Created with tk_optionMenu and consists of a menubutton with an associated menu that allows you to
select one of several values. The current value is displayed in the menubutton and is also stored in a
global variable.
Torn-off Menus
Created by invoking the tear-off entry at the top of an existing menu. The default bindings will create a
new menu that is a copy of the original menu and leave it permanently posted as a top-level window.
The torn-off menu behaves just the same as the original menu.
Event
<Enter>
<Leave>
Description
Entry underneath the mouse cursor activates.
All of the entries in the menu deactivate, except in the special case where the mouse moves from a
menu to a cascaded submenu.
<FocusIn>
none
<Motion>
Active entry changes to track the mouse.
<ButtonPress> Change the posted cascade entry (if any) to match the mouse position,
<ButtonRelease> Active entry is invoked and if a menu, unpost it unless it is a tear-off.
<space>
Invoke the active entry and unpost the menu.
<Return>
Invoke the active entry and unpost the menu.
<Escape>
Aborts a menu selection in progress without invoking any entry. It also unposts the menu unless it is a
torn-off menu.
<Left>
Moves to the next menu on the left. For cascade submenus, the submenu is also unposted and the
current menu entry becomes the cascade entry in the parent. For top-level menus posted from a
menubutton, then the current menubutton is unposted and the next menubutton to the left is posted,
otherwise the key has no effect. The left-right order of menubuttons is determined by their stacking
order with the lowest menubutton on the left.
<Right>
Moves to the next menu on the right. For cascade entries, the submenu is also posted and the current
menu entry becomes the first entry in the submenu, otherwise if the current menu was posted from a
menubutton, then the current menubutton is unposted and the next menubutton to the right is posted.
<Up>
Activate the next higher entry in the menu. When the top of the menu is reached, the active entry
wraps around to the bottom.
<Down>
Activate the next lower entry in the menu. When the bottom of the menu is reached, the active entry
wraps around to the top.
<KeyPress>
If any of the entries in a menu have letters underlined with with -underline option, then pressing one
of the underlined letters (or its upper-case or lower-case equivalent) invokes that entry and unposts the
menu.
<Alt-KeyPress> Implements keyboard traversal of menus. Given an ASCII character "char", it looks for a menubutton
with that character underlined. If one is found, it posts the menubuttons menu.
<F10>
Traverses to the first menubutton in the toplevel for a given window, and posts that menubuttons
menu.
<<MenuSelect>> Virtual event generated whenever a menus active entry is changed.
Description
menubutton pathName
?options?
Creates a menubutton widget pathName with options and returns the new widgets path name.
When invoked,pathName must not exist, but pathNames parent should. A menubutton widget
is used to display a textual string, bitmap, or image and is associated with a menu widget.
Selecting the menu button displays the associated menu. Text can only use a single font.
tk_optionMenu
Creates a menubutton with name pathName and an associated menu of options. When the
pathNamevarName value menubutton is selected, the associated option menu pops up and the user can select from the
?value ...?
value args. The selected value is stored in varName and displayed as the label in the
menubutton. Returns the pathname of the menu associated with pathName.
Standard
See Common Options and Resources in Options and Resources for full details.
-activebackground
-disabledforeground
-padx
-activeforeground
-font
-pady
-anchor
-foreground
-relief
-background
-highlightbackground
-takefocus
-bitmap
-highlightcolor
-text
-borderwidth
-highlightthickness
-textvariable
-compound (8.4+)
-image
-underline
-cursor
-justify
-wraplength
Configure
Option
-direction
direction
Resource
Name
direction
Resource
Class
Height
-height height
height
Height
-menu
pathName
menu
MenuName
-state state
state
State
-width width
width
Width
-indicatoron
boolean
Description
Specifies where the menu will popup. Direction can be above, below
(default), left, right, or flush (over) with the menubutton.
Description
pathName cgetoption
Returns the current value of the configuration option. See Menubutton Widget Options
above for options .
pathName configure?option? Change the configuration option tovalue. Without value, a list describing option is
?value? ?option value ...?
returned. Without option, a list of all available options for pathName is returned. For
multiple options an empty string is returned. See Menubutton Widget Options above for
options.
Event
<Enter>
<Leave>
<Button-1>
<Motion>
<B1-Motion>
<ButtonRelease-1>
<Alt-KeyPress>
<F10>
<space>
<Return>
<<MenuSelect>>
Description
Menubutton is activated.
Menubutton is deactivated and returns to its normal state.
Post menu for menubutton or activate entry.
Deactivates previous entry and activates new entry.
Deactivates previous entry and activates or posts submenus for new entry.
If the release happens inside the menubutton then leave its menu posted with element 0 activated,
otherwise unpost the menu without invoking any menu entry. If menu entry is active, invoke entry
and unpost menu.
Implements keyboard traversal of menus. Given an ASCII character "char", it looks for a
menubutton with that character underlined. If one is found, it posts the menubuttons menu.
Traverses to the first menubutton in the toplevel for a given window, and posts that menubuttons
menu.
Invoke the active entry and unpost the menu.
Invoke the active entry and unpost the menu.
Virtual event generated whenever a menus active entry is changed.
Description
message
pathName
?options?
Creates a message widget pathName with options and returns the new widgets path name. When invoked,
pathName must not exist, but pathNames parent should. A message widget is used to display a textual
string. Text can only use a single font and is broken up on word boundaries if possible. Tab characters are
replaced with blank space up to the next 8-character boundary, newlines cause line breaks, and control
characters and other undefined characters in the font are displayed as a 8-bit hex backslash sequence
(\xhh).
See Common Options and Resources in Options and Resources for full details.
-anchor
-highlightbackground
-background
-highlightcolor
-takefocus
-borderwidth
-highlightthickness
-text
-cursor
-justify
-textvariable
-font
-padx
-foreground
-pady
-relief
Configure
Option
-aspect
integer
Resource
Name
aspect
Resource
Class
Aspect
Width
Description
Ratio of text width to text height for text display. Formula is: ratio =
100*width/height. 100 = text is as wide as it is tall. 150 (default) = text is 1.5
times wide as it is tall.
Width of menubutton widget (default is to auto size) in screen units (bitmap or
image) or characters (text). See Coordinates in Options and Resources for screen
unit options.
Command
pathName cgetoption
Returns the current value of the configuration option. See Message Widget Options above
for options .
pathName configure?option? Change the configuration option tovalue. Without value, a list describing option is
?value? ?option value ...?
returned. Without option, a list of all available options for pathName is returned. For
multiple options an empty string is returned. See Message Widget Options above for
options.
Description
Adds new option with name or class pattern set to value at priority (0-100) to the database. Priority
level symbols are: widgetDefault (level 20 - Use default values hard-coded into widgets), startupFile
(level 40 - Use options in app-specific startup files), userDefault (level 60 - User specific options from
.Xdefaults, X server database, user specific start-up files), and interactive (level 80 - default - Options
specified interactively after the application starts running).
Clears option database and reloads from users Xdefaults on next add or get.
option get
window name
class
Returns the option value with highest priority level for window under name and class or empty string if
none.
option readfile
fileName
?priority?
Reads options from Xdefaults-style file into option database at priority (default is interactive).
tk_bisque
tk_setPalette
color
Set the default color for option in the color scheme. Modifies existing widgets using default values and
tk_setPalette
adds to option database at priority widgetDefault. Must include background option in all cases.
option color
Available options are: activeBackground,activeForeground, background, disabledForeground,
?option color ...? foreground,highlightBackground, highlightColor, insertBackground,selectColor,
selectBackground, selectForeground, and troughColor.
Syntax
pathName configure option value ?option value ...?
option add {app name or *}.{widget name}.{Resource name} value
option add Tk.{widget name}.{Resource Class} value
Resource Name
activeBackground
Resource Class
Foreground
Description
Background color of widget when it is active.
Normally ignored when tk_strictMotif is set.
-activeborderwidth
width
activeBorderWidth
BorderWidth
-activeforeground
color
activeForeground
Background
-anchor anchorPos
anchor
Anchor
-background color
background
Background
-bitmap bitmap
bitmap
Bitmap
-borderwidth width
name
@fileName
borderWidth
-compound value
compound
Compound
-cursor cursor
cursor
Cursor
@sourceName fgColor
@sourceName
-disabledforeground
color
-exportselection
boolean
exportSelection
ExportSelection
-font font
font
Font
-foreground color
foreground
Foreground
highlightColor
HighlightColor
-highlightthickness
width
highlightThickness
HighlightThickness
-image imageName
image
image
-insertbackground
color
insertBackground
Foreground
-insertborderwidth
width
insertBorderWidth
BorderWidth
-insertofftime
milliseconds
insertOffTime
OffTime
-insertontime
milliseconds
insertOnTime
OnTime
-insertwidth width
insertWidth
InsertWidth
-jump boolean
jump
Jump
-justify option
justify
Justify
-orient option
orient
Orient
-padx width
padX
Pad
-pady height
padY
Pad
-relief option
relief
Relief
-repeatdelay
milliseconds
repeatDelay
RepeatDelay
-repeatinterval
milliseconds
repeatInterval
RepeatInterval
-selectbackground
color
selectBackground
Foreground
-selectborderwidth
width
selectBorderWidth
BorderWidth
-selectforeground
color
selectForeground
Background
-setgrid boolean
setGrid
SetGrid
-takefocus focusType
takeFocus
TakeFocus
0
1
empty string
other
skip window
allow if viewable
Tk decides (skip if disabled, no key bindings, or not viewable)
evaluates as a Tcl script with window name lappended as an arg. Script
must return 0, 1, or empty string.
Text
Text string to be displayed inside the widget.
Can include \n.
-text string
text
-textvariable variable
textVariable
Variable
-troughcolor color
troughColor
Background
-underline index
underline
Underline
-wraplength length
wrapLength
WrapLength
-xscrollcommand
cmdPrefix
xScrollCommand
ScrollCommand
-yscrollcommand
cmdPrefix
yScrollCommand
ScrollCommand
Default Bitmaps
All Platforms:
Mac only:
error
hourglass
accessory
edition
pfolder
gray12
info
application
floppy
querydoc
gray25
questhead
caution
folder
ramdisk
gray50
question
cdrom
note
stationary
gray75
warning
document
preferences
stop
trash
Colors:
For color options the following are the valid options where colorname is a text string matching a color in the X server
database and # starts a numeric specification of the red, green, and blue intensities. Each R, G, and B represents a hex digit.
The four forms permit colors to be specified with 4-bit, 8-bit, 12-bit, or 16-bit values. When fewer than 16 bits are provided
for each color, they represent the most significant bits of the color.
colorname
#RGB
#RRGGBB
#RRRGGGBBB
#RRRRGGGGBBBB
DarkRed
maroon
red
gold
goldenrod
yellow
brown
chocolate
tan
DarkGreen
green
honeydew
DarkBlue
MidnightBlue
blue
SlateBlue
DodgerBlue
SteelBlue
black
DarkGray
gray
gray1 to gray100 or grey1 to grey100
LightYellow
wheat
PaleGreen
LightBlue
CadetBlue
LightGray
DeepPink
DarkOrange
chartreuse
aquamarine
DarkCyan
DarkViolet
bisque
OrangeRed
coral
orange
turquoise
cyan
purple
white
magenta
pink
SkyBlue
violet
BlueViolet
Purpose
Default background
Default foreground
SystemButtonHighlight
SystemButtonShadow
SystemHighlight
Default highlight background
SystemHighlightText
SystemWindow
SystemWindowText
SystemWindowFrame
Coordinates:
For options that take screen units, default value is in pixels unless one of the following optional suffix modifiers is present.
Units can be floating point numbers. Coordinate (0,0) is in the top left corner of the widget. X-Windows and MS Windows
9x and ME use 16 bit coordinates. MS Windows NT and later use 32 bit coordinates.
c (centimeters)
i (inches)
mm (millimeters)
Cursors:
Default cursors from /usr/include/X11/cursorfont.h on Unix:
arrow
crosshair
iron_cross
right_tee
tcross
based_arrow_down
diamond_cross
left_ptr
rightbutton
top_left_arrow
based_arrow_up
dot
left_side
rtl_logo
top_left_corner
boat
dotbox
left_tee
sailboat
top_right_corner
bogosity
double_arrow
leftbutton
sb_down_arrow
top_side
bottom_left_corner
draft_large
ll_angle
sb_h_double_arrow
top_tee
bottom_right_corner
draft_small
lr_angle
sb_left_arrow
trek
bottom_side
draped_box
man
sb_right_arrow
ul_angle
bottom_tee
exchange
middlebutton
sb_up_arrow
umbrella
box_spiral
fleur
mouse
sb_v_double_arrow
ur_angle
center_ptr
gobbler
pencil
shuttle
watch
circle
gumby
pirate
sizing
xterm
clock
hand1
plus
spider
X_cursor
coffee_mug
hand2
question_arrow
spraycan
cross
heart
right_ptr
star
cross_reverse
icon
right_side
target
starting
size
size_ne_sw
size_ns
size_nw_se
size_we
uparrow
wait
Mac only:
cross-hair
ibeam
text
3.20 Panedwindow
Command
Description
panedwindow
pathName
?options?
(Tk 8.4+) Creates a panedwindow widget pathName with options and returns the new widgets path
name. When invoked, pathName must not exist, but pathNames parent should. A panedwindow
widget can contain any number of panes arranged horizontally or vertically. Each pane contains one
widget, and each pair of panes is separated by a moveable (via mouse movements) sash and sash
handle. Moving a sash causes the widgets on either side of the sash to be resized. When a pane is
resized from outside (eg, it is packed to expand and fill, and the containing toplevel is resized), space is
added to the final (rightmost or bottommost) pane in the window.
Panedwindow Options
Standard
See Common Options and Resources in Options and Resources for full details.
-background
-cursor
-borderwidth
-orient
-relief
Panedwindow Specific
-handlesize size
-height height
-opaqueresize
boolean
Resource
Class
HandlePad
Description
Specifies the distance in screen units from the top or left end of the
sash (depending on the orientation of the widget) at which to draw the
handle.
handleSize
HandleSize
Specifies the size of the square sash handle in screen units.
height
Height
Height of panedwindow in screen units. Default is to auto size.
opaqueResize OpaqueResize Set to true, panes should be resized as a sash is moved, or if false,
resizing should be deferred until the sash is placed.
-sashcursor
cursor
sashCursor
SashCursor
Mouse cursor to use when over a sash. Default or when set to null,
uses sb_h_double_arrow for horizontal and sb_v_double_arrow for
vertical panedwindows.
-sashpad size
sashPad
SashPad
SashRelief
-sashwidth size
-showhandle
boolean
-width width
sashWidth
showHandle
SashWidth
ShowHandle
width
Width
Panedwindow Commands
See Coordinates in Options and Resources for screen unit options.
Command
Description
pathName add window ?window Add one or more windows to the panedwindow, each in a separate pane using the
...? ?option value ...?
specified options . See paneconfigurefor options. Tk 8.4.0 to 8.4.3 will set last pane to
use all avalable space.
pathName cget option
Returns the current value of the configuration option. See Panedwindow Options above
for options .
pathName configure ?option?
Change the configurationoption tovalue. Without value, a list describing option is
?value? ?option value ...?
returned. Without option, a list of all available options for pathName is returned. For
multiple options an empty string is returned. See Panedwindow Options above for
options.
pathName forget window
Removes and unmaps each pane window from the panedwindow and forgets their
?window ...?
configuration options.
pathName identify x y
Identify the panedwindow component at window coordinate xy. If over a slash or
handle, returns two element list with index of slash or handle and type (slash or handle),
else returns empty list.
and
pathName proxy ?args?
coord
forget
place x y
pathName sash ?args?
Used to query and change the position of the sash proxy for rubberband-style pane
resizing. Valid args are:
Return a list containing the x and y coordinates of the most recent proxy location.
Remove the proxy from the display.
Place the proxy at the given x and y coordinates.
Used to query and change the position of sashes in the panedwindow. Valid args are:
coord index
dragto index x y
mark index x y
place index x y
pathName panecget window
option
pathNamepaneconfigure
window option ?value? ?option
value ...?
Return the current x and y coordinate pair for the top left corner of the region containing
the sash given by index. Index must be an integer between 0 and 1 less than the number
of panes in the panedwindow.
Compute the difference between the given coordinates and the coordinates given to the
last sash coord command for sash given by index. It then moves that sash the computed
difference.
Records coordinates x andy for the sash given by index.
Place the sash given by index at the coordinates x and y.
Returns the current value of the configuration option for panewindow window. See
paneconfigure below for options.
Change the configuration option to value for panewindow window. Without value, a list
describing option is returned. Without option, a list of all available options for
pathName is returned. For multiple options an empty string is returned.
-after afterWindow
-before beforeWindow
-height height
Specify height of window in screen units (autosize is the default or when set to an
empty string).
(Tk 8.5+) Controls the visibility of a pane. Hidden panes are still maintained in the list
of panes
Specifies the minimum size of window for the paned direction (vertical or horizontal) in
screen units.
Specifies amount of horizontal padding to leave on each side of window in screen units
(default is 0).
-hide boolean
-minsize value
-padx amount
-pady amount
Specifies amount of vertical padding to leave on each side of window in screen units
(default is 0).
Specifies where to position window in panewindow if the cavity is larger than the
requested dimensions. Style can be zero or more positions (n, s, e or w) with optional
space and comma separators. If both n and s (or e and w) are specified, the slave will be
stretched to fill the entire height (or width) of its cavity. The default or when set to an
empty string, is to center the slave within the cell.
(Tk 8.5+) Controls how extra space is allocated to each of the panes. Options are
always (pane will always stretch), first (only left-most or top-most will stretch), last
(only right-most or bottom-most will stretch), middle (will stretch if not the first or
last), and never (pane will never stretch).
Specify width of window in screen units (autosize is the default or when set to an empty
string).
-sticky style
-stretch when
-width width
pathNamepanes
3.21 Radiobutton
Command
Description
radiobutton
pathName
?options?
Creates a radiobutton widget pathName with options and returns the new widgets path name. When
invoked, pathName must not exist, but pathNames parent should. A radiobutton widget displays a
textual string, bitmap, or image and a diamond or circle called an indicator. By default a radiobutton is
configured to select itself on a button click. To deselect a radiobutton, another button in the group must
be selected. This means only one radiobutton within a group (all use same -variable variable) can be
selected at a time. Radiobuttons also select and deselect themselves when the value of the -variable
variable changes. Multiple fonts within a button text field are not supported.
Radiobutton Options
Standard
See Common Options and Resources in Options and Resources for full details.
-activebackground
-disabledforeground
-padx
-activeforeground
-font
-pady
-anchor
-foreground
-relief
-background
-highlightbackground
-takefocus
-bitmap
-highlightcolor
-text
-borderwidth
-highlightthickness
-textvariable
-compound (8.4+)
-image
-underline
-cursor
-justify
-wraplength
Radiobutton Specific
Configure
Option
-command
script
Resource
Name
command
Resource
Class
Command
Height
indicatorOn IndicatorOn
OffRelief
-overrelief
type
-selectcolor
color
overRelief
OverRelief
selectColor
Background
-selectimage
image
-state state
selectImage SelectImage
-tristateimage
image
tristateImage TristateImage
-tristatevalue
value
-value value
tristateValue Value
value
Value
-variable
variable
variable
Variable
-width width
width
Width
state
Effect
Toolbar buttons
Text-align toolbar buttons
State
Description
Tcl command to associate with the button. Script is invoked when mouse
button 1 is released over the button window. The buttons global variable
(-variable option) will be updated before the command is invoked.
Height of button in screen units for bitmaps/images and in lines for text.
Default is to auto size.
Specifies whether the indicator should be drawn (default) or not. If false,
the -relief option is ignored and the relief is set to sunken when widget is
selected and raised in all other cases.
(Tk 8.4+) Specifies the relief for the radiobutton when the indicator is not
drawn and the radiobutton is off. Options are: flat, raised (default), and
sunken.
(Tk 8.4+) Alternative relief for when mouse cursor is over button. Not used
when set to empty string (default). Options are: flat, raised, and sunken.
Specifies a background color to use when the button is selected. If set to
empty string, no special color is used. If -indicatoron is true then the color
applies to the indicator, if false this color is used as the background for the
entire widget when selected.
Specifies image to be displayed when radiobutton is selected. Used with
-image.
State of button. Options are: active (mouse pointer over button, use
activeforeground and activebackground),disabled (button is insensitive,
use disabledforeground and background), or normal (use foreground
and background ).
(Tk 8.5+) Specifies an image to display (in place of the image option) when
the radiobutton is in tri-state mode. This option is ignored unless the image
option has been specified.
(Tk 8.5+) Specifies the value that causes the radiobutton to display the
multi-value selection, also known as the tri-state mode. Defaults to {}.
Value stored in variable specified with -variable option when the
radiobutton is selected.
Specifies name of global variable to use for button selection status. Default
is variable selectedButton .
Width of button in screen units for bitmaps/images and in characters for
text. Default is to auto size.
Options
-relief flat -overrelief raised
-offrelief flat -indicatoron false -overrelief raised
Radiobutton Commands
Description
Command
pathName cget option
Returns the current value of the configuration option for radiobutton pathName. See
Radiobutton Widget Options above for options.
pathName
Change the configuration option for the radiobutton pathNamevalue. Without value, a list
configure?option? ?value? describing the available options is returned. Without option, a list describing all of the
?option value ...?
available options for pathName is returned. For multiple options an empty string is returned.
See Radiobutton Widget Options to above for options.
pathName deselect
Deselect the radiobutton and set the associated variable to its "off" value of empty string.
pathName flash
Flash radiobutton by toggling between active and normal colors several times. Radiobutton
is left is initial state of active or normal. Ignored if radiobutton is disabled.
pathName invoke
Selects the radiobutton and invokes the Tcl command specified with -command, if any.
Returns value of Tcl command or empty string if no -command. Ignored if button is
disabled.
pathName select
Selects the radiobutton and set the associated variable to its "on" value.
Description
On Unix, when mouse passes over button statebecomesactive.
On Unix, when mouse leaves the button state becomes normal.
On Unix, relief changes to sunken and associated -command script is executed.
or
<Button-1>
<ButtonRelease-1>
<Enter>
<space>
On Windows and Mac, relief changes to sunken and state becomes active.
On Windows and Mac, relief changes to raised, state becomes normal, and associated
-command script is executed.
On Windows and Mac, relief changes to sunken and state becomes active.
On Windows and Mac, relief changes to sunken and associated -command script is
executed.
Description
scale
pathName
?options?
Creates a scale widget pathName with options and returns the new widgets path name. When invoked,
pathName must not exist, but pathNames parent should.A scale widget displays a rectangular trough and
a small slider either a vertical or horizontal orientation. The scale value may be linked to the slider, such
that a change in one affects the other.
See Common Options and Resources in Options and Resources for full details.
-activebackground
-foreground
-relief
-background
-highlightbackground
-repeatdelay
-borderwidth
-highlightcolor
-repeatinterval
-cursor
-highlightthickness
-takefocus
-font
-orient
-troughcolor
-from number
-label string
-length size
-resolution
number
-showvalue
boolean
-sliderlength
size
-sliderrelief
relief
-state state
Resource
Resource
Description
Name
Class
bigIncrement BigIncrement Specifies the increment size for interactions with scale that cause its
value to change by "large" increments. A value of 0 sets the large
increments default to 1/10 the range of the scale.
command
Command
Tcl command to execute when scales value changes via widget
command. Passes new scale value as an arg.
digits
Digits
An integer specifying how many significant digits should be retained
when converting the value of the scale to a string. If <= 0, scale picks
the smallest value forwhich each slider position prints a different string.
from
From
A real value specifying the left or top end of the scale.
label
Label
A string to display as the label at the top right of the scale for vertical
scales and at the top left of the scale for horizontal scales.
length
Length
Specifies the desired long dimension (height for vertical or width for
horizontal) of the scale in screen units.
resolution
Resolution
A real value (default is 1) specifying the scale resolution. When number
> 0, the scales value, tick marks, and endpoints will be rounded to an
even multiple of number . When number < 0, no rounding occurs.
showValue
ShowValue
Specifies whether to show the value of the scale to the left of the slider
for vertical scales or above the slider for horizontal scales.
sliderLength SliderLength Specifies long dimension size of the slider in screen units.
sliderRelief
SliderRelief
state
State
-tickinterval
number
tickInterval
TickInterval
-to number
-variable
variable
to
variable
To
Variable
-width width
width
Width
Specifies the relief to use for the slider. Options are: flat, groove,
raised, ridge ,solid, or sunken.
State of button. Options are: active (use activebackground),disabled
(value cant be changed), or normal (use background).
A real value specifying the spacing between tick marks placed to the
left of the trough for vertical scales and below the trough for horizontal
scales. Set to 0 for no tick marks.
A real value specifying the right or bottom end of the scale.
Specifies name of global variable to use for scale value.
Specifies the desired narrow dimension (width for vertical or height for
horizontal) of the scale in screen units.
Scale Elements
Element
trough1
Description
Region between the slider and top or left end of scale.
slider
trough2
Scale Commands
Command
Description
Returns the current value of the configuration option for scale pathName. See Scale Widget
Options above for options.
pathName
Change the configuration option for the scale pathName to value. Without value, a list
configure?option? ?value? describing the available options is returned. Without option, a list describing all of the
?option value ...?
available options for pathName is returned. For multiple options an empty string is returned.
See Scale Widget Options above for options.
Returns a list of the x and y coordinates of the point along the centerline of the scale
pathName coords ?value?
corresponding to value (default is scales current value).
pathName get ?x y?
Returns the scale value corresponding the coordinate x and y. Default is to return the scales
current value.
pathName identify x y
Returns a string indicating what part of scale is at coordinate x and y. Valid values are
empty (not a valid element) or one of the Scale Elements above.
Scale Bindings
Event
<Enter>
<Motion>
<Leave>
<Button-1>
Description
Activate scale.
Activate scale.
Deactivate scale.
If in trough, scales value will be incremented or decremented by value of -resolution
option in the direction of the button press. If the button is held down, the action
auto-repeats.
<ButtonRelease-1>
Cancel repeat, end drag, and activate scale.
<B1-Leave> or <B1-Enter> No function
<B1-Motion>
If pressed over the slider, the slider can be dragged with the mouse.
<Control-Button-1>
If in trough, slider moves all the way to the end of its range in the direction of the button
press.
<Button-2>
Scales value is set to the mouse position.
<B2-Motion>
Scales value changes with the drag.
<ButtonRelease-2>
Cancel repeat, end drag, and activate scale.
<B2-Leave> or <B2-Enter> No function
<Up> or <Left>
Move the slider up or left by the value of the -resolution option.
<Down> or <Right>
Move the slider down or right by the value of the -resolution option.
<Control-Up> or
Move the slider up or left by the value of the -bigincrement option.
<Control-Left>
<Control-Down> or
Move the slider down or right by the value of the -bigincrement option.
<Control-Right>
<Home>
Moves the slider to the top or left end of its range.
<End>
Moves the slider to the bottom or right end of its range.
3.23 Scrollbar
Command
Description
scrollbar
pathName
?options?
Creates a scrollbar widget pathName with options and returns the new widgets path name. When
invoked, pathName must not exist, but pathNames parent should. A scrollbar widget displays two
arrows, one at each end of the scrollbar, and a slider in the middle portion of the scrollbar. It provides a
visual representation of how much of an associated window is visible and also a way to change the visible
portion.
See Common Options and Resources in Options and Resources for full details.
-activebackground
-highlightcolor
-repeatdelay
-background
-highlightthickness
-repeatinterval
-borderwidth
-jump
-takefocus
-cursor
-orient
-troughcolor
-highlightbackground
-relief
Resource Name
Description
activeRelief
Resource
Class
ActiveRelief
-activerelief number
-command
tclCommand
command
Command
-elementborderwidth
width
-width width
width
Width
Scrollbar Elements
Element
arrow1
Description
Top or left arrow in the scrollbar.
trough1
slider
trough2
arrow2
Scrollbar Commands
Command
Description
pathName activate
?element?
Marks element as the active element. Except for the troughs, element can be one of the
elements listed in Scrollbar Elements above. Without element, returns the current active
element or empty string if none.
Returns the current value of the configuration option for scrollbar pathName. See Scrollbar
Widget Options above for options.
pathName
Change the configuration option for the scrollbar pathName to value. Without value, a list
configure?option? ?value? describing the available options is returned. Without option , a list describing all of the
?option value ...?
available options for pathName is returned. For multiple options an empty string is returned.
See Scrollbar Widget Options above for options.
Returns a real number (-1 to 1) indicating the change in the scrollbar setting corresponding
pathName delta deltaX
to the deltaX (horizontal scrollbar) or deltaY (vertical scrollbar) value in pixels. The args and
deltaY
the result may be zero or negative.
pathName fraction x y
Returns a real number (0 to 1) indicating where the closest point given by pixel coordinate x
and y lies in the trough area of the scrollbar. Top or left is at 0 and the bottom or right is at 1.
pathName get
Returns current scrollbar settings as the list whose elements are the args to the most recent
set widget command.
pathName identify x y
Returns the name of element under pixel coordinates x and y or empty string if none. See
Scrollbar Elements above valid elements.
Invoked by scrollbars associated widget to describe the current view in the widget. First
and last are real values (0 to 1) describing the first and last part of the visible portion of the
scrollbars associated widget.
Scrollbar Commands
The following are the valid formats of the command invoked by the -command option to notify the scrollbars associated
widget to change its view. The pathName is the scrollbars associated widget and command is either xview (for horizontal
scrollbars) or yview (for vertical scrollbars).
Command
Description
Widget should adjust its view so that the point given by real number fraction (0 to 1)
appears at the beginning of the widget.
Widget should adjust its view bynumber units (characters or lines for text widgets or
screen units for bitmaps or images).
Widget should adjust its view bynumber pages (height of the window or screenful, etc.).
Scrollbar Bindings
Event
Over
Element
<Enter>
<Motion>
<Leave>
<Button-1>
arrow1
<Button-1>
trough1
<Button-1>
trough2
<Button-1>
arrow2
<B1-Motion>
slider
<Button-2>
trough or
slider
<Button-2>
arrow
<B2-Motion>
trough or
slider
<Control-Button-1> arrow1 or
trough1
<Control-Button-1> arrow2 or
trough2
<Up>
any
<Down>
any
<Left>
any
<Right>
any
<Control-Up>
any
<Control-Down>
any
<Control-Left>
any
<Control-Right>
any
<Prior>
<Next>
<Home>
<End>
Description
Activate scrollbar.
Activate scrollbar.
Deactivate scrollbar.
Shifts view in the associated widget up or to the left by one unit so document appears
to move down or to the right. If the button is held down, the action auto-repeats.
Shifts view in the associated widget up or to the left by one screenful so document
appears to move down or to the right. If the button is held down, the action
auto-repeats.
Shifts view in the associated widget down or to the right by one screenful so
document appears to move up or to the left. If the button is held down, the action
auto-repeats.
Shifts view in the associated widget down or to the right by one unit so document
appears to move up or to the left. If the button is held down, the action auto-repeats.
View changes as the slider is dragged. If the jump option is true, the view only
changes when the mouse button is released.
Sets the view to correspond to the mouse position.
Same as <Button-1>.
Causes the view to drag with the mouse.
Adjusts view to the very top or left of the document.
Adjusts view to the very bottom or right of the document.
For vertical scrollbars, shifts view in the associated widget up by one unit so
document appears to move down. If the key is held down, the action auto-repeats.
For vertical scrollbars, shifts view in the associated widget down by one unit so
document appears to move up. If the key is held down, the action auto-repeats.
For horizontal scrollbars, shifts view in the associated widget left by one unit so
document appears to move right. If the key is held down, the action auto-repeats.
For horizontal scrollbars, shifts view in the associated widget right by one unit so
document appears to move left. If the key is held down, the action auto-repeats.
For vertical scrollbars, shifts view in the associated widget up by one screenful so
document appears to move down. If the keys are held down, the action auto-repeats.
For vertical scrollbars, shifts view in the associated widget down by one screenful so
document appears to move up. If the keys are held down, the action auto-repeats.
For horizontal scrollbars, shifts view in the associated widget left by one screenful so
document appears to move to the right. If the keys are held down, the action
auto-repeats.
For horizontal scrollbars, shifts view in the associated widget to the right by one
screenful so document appears to move to the left. If the keys are held down, the
action auto-repeats.
Shifts view in the associated widget up or to the left by one screenful so document
appears to move down or to the right. If the button is held down, the action
auto-repeats.
Shifts view in the associated widget down or to the right by one screenful so
document appears to move up or to the left. If the button is held down, the action
auto-repeats.
Adjusts view to the very top or left of the document.
Adjusts view to the very bottom or right of the document.
Description
spinbox
pathName
?options?
(Tk 8.4+) Creates a spinbox widget pathName with options and returns the new widgets path name.
When invoked, pathName must not exist, but pathNames parent should. A spinbox consists of an
editable entry field and two arrow button to move, or spin, through a fixed set of ascending or
descending values.
See Common Options and Resources in Options and Resources for full details.
-activebackground
-highlightthickness
-repeatinterval
-background
-borderwidth
-cursor
-exportselection
-font
-foreground
-highlightbackground
-highlightcolor
-insertbackground
-insertborderwidth
-insertofftime
-insertontime
-insertwidth
-justify
-relief
-repeatdelay
-selectbackground
-selectborderwidth
-selectforeground
-takefocus
-textvariable
-xscrollcommand
See Coordinates in Options and Resources for screen unit options. See Colors in Options and Resources for color formats.
Configure Option
-buttonbackground
color
-buttoncursor cursor
Resource Name
buttonBackground
Resource Class
Background
buttonCursor
Cursor
Description
Specifies background color for the spin buttons.
-invalidcommand
script
invalidCommand
InvalidCommand
Validation Types
Type
none
Description
Do not perform validation (default).
focus
focusin
focusout
key
all
Percent Substitutions
Sub Description
%d Type of action: 1 for insert, 0 for delete, or -1 for focus, forced, or textvariable validation.
%i
%P
The value of the spinbox should -validatecommand accept the new value. When configuring to a new textvariable,
this will be the value of that textvariable.
%s
The current value of the spinbox before -validatecommand accepts the new value.
Description
A decimal number giving the position or index (starting from 0) of the desired character within the spinbox
string. If number < 0, the 0 is used, if number > length of text list, then end is used.
anchor
Selection anchor point as set by the select from and select adjust commands.
end
Character or coordinate just after last one in spinboxs string.
insert
Character just after the insertion cursor.
sel.first
First character in selection. Returns an error if selection is not in the spinbox.
sel.last
Character just after last character in selection. Returns an error if selection is not in the spinbox.
@number Character at the x-coordinate point in the spinboxs window. If x is outside the spinbox windows range, it is
set to the nearest legal value.
Description
Returns a list of four elements x y w h , giving an approximate bounding box for the character
at position index . Coordinates x,y are top-left corner of character at index,w is width of char,
and h is height of char in pixels.
pathName cget option
Returns the current value of the configuration option. See Spinbox Widget Options above for
options .
pathName configure
Change the configuration option tovalue. Without value, a list describing option is returned.
?option? ?value? ?option Without option, a list of all available options for pathName is returned. For multiple options an
value ...?
empty string is returned. See Spinbox Widget Options above for options.
pathName delete first
Delete characters in spinboxs string from position first up to but not including position last
?last?
(default is first+1 to delete 1 character). See Indicies or Character Positions above for first and
last options.
pathName get
Returns the spinboxs string.
pathName icursor index Display the insertion cursor just before the character at position index. See Indicies or Char
Positions above for index options.
pathName identify x y
Returns the name of the window element at position x and y in the spinbox. Options are: none
,buttondown,buttonup, or entry.
pathName index index
Returns the numerical index corresponding to index. See Indicies or Character Positions above
for index options.
pathName bboxindex
Insert string just before the character at position index. See Indicies or Character Positions
above for index options.
Invokes the specified element, where element is buttondown or buttonup.
Implements scanning on spinbox widgets. Options are:
Records x and the current view in the spinbox window. Typically associated with mouse
button press in widget.
Adjusts the view by 10 times the difference between the coordinate xmark x coordinate. Used
with mouse motion events to produce high speed dragging.
Manipulates the selection within an spinbox based on option. See Indicies or Char Positions
above for index options. Vaild options and args are:
Adjust the end of the selection nearest to the character given by position index to include
characters up to index and set the other end to be the anchor point. Works the same as
selection to if selection is not in spinbox widget.
clear
Clear the selection if it is in the widget.
element ?element?
Sets the current selection to element. Without element, returns the currently selected element.
from index
Sets the selection anchor point to the character given by position index.
present
Returns 1 if characters are selected in the spinbox, 0 if not.
range start end
Sets the selection to include characters from position start up to but not including position end.
to index
If index < anchor point, set the selection to include characters from position index up to but not
including the anchor point. If index > anchor point, set the selection to include characters from
the anchor point up to but not including position index. If index = anchor point, no change is
made. If the selection isnt in the spinbox widget, use the most recent anchor point specified
for the widget.
pathName set ?string?
Sets spinbox to string. Without string, returns the current spinboxs string.
pathNamevalidate
Forces the evaluation of -validatecommand by temporarily setting validate to all and returns
result.
pathName xview ?option Query or change the horizontal view of the spinbox. Without any options, returns a two
args?
element list specifying the start and end of the visible fraction (from 0 to 1) of the horizontal
span of the widget between the left and right edges of the window. Vaild options and args
are:
index
moveto fraction
scroll number pages
scroll number units
Adjust window view to display the character at position index at the left edge of window. See
Indicies or Char Positions above for index options.
Adjust window view so that fraction (from 0 to 1) of the total width of the widget is off-screen
to the left.
Shift the view left (number < 0) or right (number > 0) by number screenfuls.
Shift the view left (number < 0) or right (number > 0) by number average-width characters.
Event
<Button-1>
<B1-Motion>
<Double-Button-1>
<Triple-Button-1>
<Shift-B1-Motion>
<Control-Button-1>
<B1-Leave>
<B1-Enter>
<Button-2>
<B2-Motion>
<Left> or <Control-b>
<Right> or <Control-f>
<Shift-Left>
<Shift-Right>
<Control-Left> or <Meta-b>
<Control-Right> or <Meta-f>
<Shift-Control-Left>
<Shift-Control-Right>
<Home> or <Control-a>
<Shift-Home>
<End> or <Control-e>
<Shift-End>
<Select> or <Control-Space>
<Shift-Select> or
<Shift-Control-Space>
<Control-slash>
<Control-backslash>
<Delete>
<BackSpace> or <Control-h>
<Control-d>
<Meta-d>
<Control-k>
<Control-t>
<Keypress>
Description
Positions the insertion cursor just before the character underneath the mouse cursor,
sets the input focus to this widget, and clears any selection in the widget.
Drags out a selection (in words if double clicked) between the insertion cursor and the
character under the mouse.
Selects the word under the mouse and positions the insertion cursor at the beginning of
the word.
Selects all of the text in the spinbox and positions the insertion cursor before the first
character.
Adjusts the end of the selection (in words if double clicked) that was nearest to the
mouse cursor when button 1 was pressed.
Position the insertion cursor in the spinbox without affecting the selection.
Adjusts view in spinbox left or right more quickly.
Stops adjustment of view in spinbox left or right more quickly.
Paste selection into the spinbox at the position of the mouse cursor.
Adjusts view in spinbox by scrolling left or right.
Moves the insertion cursor one character back (left), clears any selection in the
spinbox, and sets the selection anchor.
Moves the insertion cursor one character forward (right), clears any selection in the
spinbox, and sets the selection anchor.
Move the insertion cursor one character back (left) and extend the selection to include
the new character.
Move the insertion cursor one character forward (right) and extend the selection to
include the new character.
Move the insertion cursor back (left) by one word, clears any selection in the spinbox,
and sets the selection anchor.
Move the insertion cursor forward (right) by one word, clears any selection in the
spinbox, and sets the selection anchor.
Move the insertion cursor back (left) by one word and also extend the selection.
Move the insertion cursor forward (right) by one word and also extend the selection.
Move the insertion cursor to the beginning of the spinbox and clear any selection in the
spinbox.
Move the insertion cursor to the beginning of the spinbox and also extends the
selection to that point.
Move the insertion cursor to the end of the spinbox and clear any selection in the
spinbox.
Move the insertion cursor to the end of the spinbox and also extends the selection to
that point.
Set the selection anchor to the position of the insertion cursor without affecting the
selection.
Adjusts the selection to the current position of the insertion cursor, selecting from the
anchor to the insertion cursor if there is not an existing selection.
Selects all the text in the spinbox.
Clears any selection in the spinbox.
Deletes the selection, if there is one in the spinbox, if not it deletes the character to the
right of the insertion cursor.
Deletes the selection, if there is one in the spinbox, if not it deletes the character to the
left of the insertion cursor.
Deletes the character to the right of the insertion cursor.
Deletes the word to the right of the insertion cursor.
Deletes all the characters to the right of the insertion cursor.
Reverses the order of the two characters to the right of the insertion cursor.
Insert character into spinbox widget.
Description
text pathName
?options?
Creates a text widget pathName with options and returns the new widgets path name. When invoked,
pathName must not exist, but pathNames parent should. A text widget displays one or more lines of
text and can allow that text to be edited.
(Tk 8.4+) Copies the selection in text widget pathName to the clipboard.
tk_textCopy
pathName
tk_textCut
pathName
tk_textPaste
pathName
(Tk 8.4+) Copies the selection in text widget pathName to the clipboard and deletes it from the text
widget.
(Tk 8.4+) Inserts the contents of the clipboard into text widget pathName at the position of the
insertion cursor.
See Common Options and Resources in Options and Resources for full details.
-background
-highlightthickness
-relief
-borderwidth
-insertbackground
-selectbackground
-cursor
-insertborderwidth
-selectborderwidth
-exportselection
-insertofftime
-selectforeground
-font
-insertontime
-setgrid
-foreground
-insertwidth
-takefocus
-highlightbackground
-padx
-xscrollcommand
-highlightcolor
-pady
-yscrollcommand
Configure Option
-autoseparators boolean
Resource Name
autoSeparators
-blockcursor
blockCursor
BlockCursor
-endline
endLine
EndLine
-height size
height
Height
-maxundo count
maxUndo
MaxUndo
-spacing1 size
spacing1
Spacing1
-spacing2 size
spacing2
Spacing2
-spacing3 size
spacing3
Spacing3
-startline
startLine
StartLine
-state state
state
State
-tabs tabList
tabs
Tabs
-undo boolean
undo
Undo
-width size
width
Width
-wrap type
wrap
Wrap
Description
Indicates line line (starts at 1) and character char (starts at 0).
Indicates the character that covers the pixel at position x and y.
Indicates the character at the end of the text, just after the newline.
Indicates the character just after the mark whose name is mark.
Indicates the first character in the text that has been tagged with tag. If no characters are tagged, an error will
be generated.
tag.last
Indicates the character just after the last one in the text that has been tagged with tag. If no characters are
tagged, an error will be generated.
pathName Indicates the position of the embedded window whose name is pathName. If pathName doesnt exist, an
error is generated.
imageName Indicates the position of the embedded image whose name is imageName. If imageName doesnt exist, an
error is generated.
The following are the valid forms for modifier:
Modifier
+count
?submodifer?
chars
-count
?submodifer?
chars
Description
Adjust the index forward by count characters, moving to later lines in the text if necessary or to the last
character in the text if fewer than count characters remain. In Tk 8.5+, use the display submodifier to
skip and not count elided characters and any to count all characters (default).
Adjust the index backwards by count characters, moving to earlier lines in the text if necessary or to the
first character in the text if fewer than count characters remain. In Tk 8.5+, use the submodifier display
to skip and not count elided characters and any to count all characters (default).
+count
?submodifer?
indicies
(Tk 8.5+) Adjust the index forward by count index positions, moving to later lines in the text if
necessary. If there are fewer than count index positions in the text after the current index, then set the
index to the last index position in the text. In Tk 8.5+, use the submodifier display to skip and not count
elided indicies and any to count all indicies (default).
-count
?submodifer?
indicies
(Tk 8.5+) Adjust the index backward by count index positions, moving to earlier lines in the text if
necessary. If there are fewer than count index positions in the text before the current index, then set the
index to the first index position (1.0) in the text. In Tk 8.5+, use the submodifier display to skip and not
count elided indicies and any to count all indicies (default).
+count
?submodifer?
lines
Adjust the index forward by count lines or to the last line if less than count remain, without changing
the character position within the line or to the last character in the line (newline char) if fewer
characters than the character position are available. In In Tk 8.5+, use the submodifier display to count
visual lines and any to count logical lines (default).
-count
?submodifer?
lines
Adjust the index backwards by count lines or to the first line if less than count remain, without
changing the character position within the line or to the last character in the line (newline char) if fewer
characters than the character position are available. In In Tk 8.5+, use the submodifier display to count
visual lines and any to count logical lines (default).
linestart
lineend
wordstart
wordend
Annotations
Annotation
Description
Tag
Tags are a textual string identifiers that can be associated with a single character, range of characters, or
several ranges of characters in the text widget. There can be an unlimited number of tags within a text
widget and any number associated with any particular character. Deleting a character also removes the tag
for that text. The default prority order for tags is based on the order defined, with the latest having the
highest prioity. When tags conflict, the tag with the highest priority is used. See Tag Options below.
The sel tag is associated with the current selection if the -exportSelection option is true. The sel tag can not
be deleted. See Selection Support below. The sel tag may be set and configured (in its display style)
differently for each peer.
Mark
Embedded
Windows
Embedded
Images
Marks are textual strings that are used as floating markers in the text to keep track of particular places in the
text as it is edited. Marks are associated with the gap between two characters and a single position can only
be associated with one mark. Deleting the characters around a mark does not delete the mark. Marks have a
gravity of left or right (default), which defines what happens to the mark (which text it stays with) when
text is inserted at the point of the mark.
The insert mark is associated with the insertion cursor and thecurrent mark is associated with the character
closest to the mouse pointer unless the mouse button is held down. The insert and current marks can not
be deleted. Each peer has its own insert and current mark positions (but all other marks are shared)
Embedded windows allow any number of widgets to be embedded in a text widget which will dynamically
update as the text is modified or scrolled. They will be mapped and unmapped when moved into and out of
the visible area of the text widget. Each embedded window occupies one characters worth of index space
in the text widget, and it may be referred to either by its name or by its position in the widgets index space.
If the range of text containing the embedded window is deleted then the window is destroyed. See
Embedded Window Options below. Embedded windows, which are arbitrary other widgets, cannot be
shared between peers.
Embedded images allow any number of images to be embedded in a text widget. An image may be
embedded multiple times. The image positions will be updated as text is updated ot scrolled. Each
embedded image occupies one characters worth of index space in the text widget, and it may be referred to
either by its name or by its position in the widgets index space. If the range of text containing the
embedded image is deleted then the image is removed. See Embedded Image Options below.
Tag Options
See Colors, Coordinates, or Default Bitmaps in Options and Resources for color, screen unit, and bitmap options,
respectively. See Fonts for font options.
Option
-background
color
-bgstipple
bitmap
Description
Specifies the background color to use for characters associated with the tag.
Specifies a bitmap that is used as a stipple pattern for the background. A solid fill will be used as the
default option or if set to an empty string.
-borderwidth Specifies the width of a 3-D border to draw around the background in screen units.
pixels
-elide boolean (Tk 8.3+) Specifies whether the data should be elided. Elided data is not displayed and takes no space on
screen, but further on behaves just as normal data.
-fgstipple
Specifies a bitmap that is used as a stipple pattern for the foreground. A solid fill will be used as the
bitmap
default option or if set to an empty string.
-font fontName Specifies the name of the font to use for drawing characters.
-foreground
Specifies the foreground color to use for characters associated with the tag.
color
-justify justify Specifies how to justify text only if the first character in a line has a tag with this option. Options are left,
right, or center.
Specifies
the left margin or indentation in screen units for the first line in a paragraph. The first character
-lmargin1 size
in the text line must have the tag in order to take effect.
Specifies the left margin or indentation in screen units for the subsequent lines in a paragraph. The first
-lmargin2 size
character in the text line must have the tag in order to take effect.
-offset size
Specifies the amount in screen units by which the texts baseline should be offset vertically from the
baseline of the overall line. Use a positive offset for superscripts and a negative offset for subscripts.
-overstrike
boolean
-relief relief
-rmargin size
Specifies the 3-D relief to use for drawing backgrounds. Options are: flat, groove, raised, ridge, solid, or
sunken.
Specifies the right margin in screen units for lines in a paragraph. The first character in the text line must
have the tag in order to take effect.
-spacing1 size Specifies the space in screen units above first line of a paragraph with this tag.
-spacing2 size Specifies the space in screen units between lines within a paragraph with this tag.
-spacing3 size Specifies the space in screen units below the last line of a paragraph with this tag.
Specifies a list of tab stops consisting of offset values from the left edge in screen units followed by an
optional justification. The first character in the text line must have the tag in order to take effect. Options
-tabs tabList
are: left (default) with the left edge of text at tab position, right with text at tab position, center with the
text centered at the tab position, or numeric with decimal point in the text is positioned at the tab
position. If set to { } the default 8-character tab stops are used.
-underline
Specifies whether to underline text.
boolean
-wrap mode
Specifies how to wrap lines wider than the window. Options are: char (line break can be made after any
character), none (no wrap), or word (line break can only be made at word boundaries).
Option
Description
Specifies window alignment if smaller than line height. Options are: top (align the top of window with the
-align where top of the text), center (center window within line), bottom (align the bottom of window with the bottom
of the text), or baseline (align the bottom of window with the baseline of the text).
-create
script
Specifies script to create and return window pathname if no -window option is given.
-padx width Specifies extra space in screen units to leave on the left and right side of window.
-pady height Specifies extra space in screen units to leave at the top and bottom of window.
-stretch
boolean
Specifies whether window should be stretched vertically to fill line if less than the height of the line.
-window
pathName
Description
Specifies image alignment if smaller than line height. Options are: top (align the top of image with the top
of the text), center (center image within line), bottom (align the bottom of image with the bottom of the
text), or baseline (align the bottom of image with the baseline of the text).
-image image Specifies the name of the image to embed. Returns error if image is not a valid image.
-name
imageName
-padx width
Specifies the name to use for referencing the embedded image. Appends #nn if imageName is already in
use. Without -name, -image is used instead. Once an image is assigned a name, it cannot be changed with
image configure.
Specifies extra space in screen units to leave on the left and right side of the image.
-pady height
Specifies extra space in screen units to leave at the top and bottom of the image.
Selection Support
The selectBackground, selectBorderWidth, and selectForeground options for the text widget are tied to the
-background,-borderwidth, and -foreground options for the sel tag. Changes in either will automatically be reflected in
the other.
#
Selection Criteria
1 Whenever characters are tagged with sel the text widget will claim ownership of the selection.
2 Attempts to retrieve the selection will be serviced by the text widget, returning all the characters with the sel tag.
If the selection is claimed away by another application or by another window within this application, then the sel tag
3
will be removed from all characters in the text.
4 (Tk 8.4+) Whenever the sel tag range changes a virtual event <<Selection>> is generated.
Undo Mechanism
(Tk 8.4+) If the -undo option is true, the text widget supports an unlimited undo and redo mechanism which records each
insert and delete action in a stack. Boundaries (called "separators") are inserted between edit actions in order to group
compound edits. An undo, uses all actions between separators then transfers them to the redo stack. The redo stack is
cleared whenever new edit actions are recorded on the undo stack. Separators are inserted automatically when the
-autoseparators option is true. The undo mechanism is also linked to the modified flag so undoing or redoing an edit can
restore a text widget back to the unmodified or vice versa. Manual changes to the modified flag disable the automatic
coupling until the flag has been reset.
Description
Returns a four element list with the upper left corner x and y coordinates, width, and height of
the character or element at index. Only the visible portion will be returned or an empty list if not
visible.
Returns the current value of the configuration option. See Standard Options and Text Widget
Specific Options above for options.
Compares the characters at indices index1 and index2 according to relational operator op and
returns 1 if true, 0 if not. Op can be: <, <=, ==, >=, >, or !=.
Changes the configuration option tovalue. Without value, a list describing option is returned.
Without option, a list of all available options for pathName is returned. For multiple options an
empty string is returned. See Text Options above for options. Configuration options of each peer
can be set independently except as indicated in the options above.
(Tk 8.5+) Counts the number of relevant things between the two indices and returns a list of
integers based on options. If index1 is after index2, the result will be a negative number.
Count all characters, whether elided or not. Do not count embedded windows or images.
Count all non-elided characters.
Count all non-elided characters, windows and images.
Count all display lines from the line of the index1 up to, but not including the display line of
index2.
Count all characters, embedded windows, and embedded images whether they are elided or not.
Default option.
Count all logical lines (irrespective of wrapping) from the line of index1 up to, but not including
the line of index2.
Used before -ypixels to ensure that any possible out of date information is recalculated.
Count the number of horizontal pixels from the first pixel of index1 to (but not including) the
first pixel of index2.
Count the number of vertical pixels from the first pixel of index1 to (but not including) the first
pixel of index2.
Specified whether internal consistency checks will be turned on for text widgets. In Tk 8.4+,
global vars tk_textRedraw and tk_textRelayout are set to the indices that are redrawn. Without
boolean, returns debugging status.
Deletes contents of text widget from index1 to just before index2, if specified, and index2 >
index1 or just the character at index1. Newline characters can not be deleted. In Tk 8.4+,
multiple ranges can be specified.
pathName dlineinfo
index
Returns a five element list with the upper left corner x and y coordinates, width, height, and
baseline in pixels of the display line containing index. Includes the portion of the line outside the
window boundaries if no line wrap. If line the containing index is not visible, an empty list is
returned.
pathName dump
?options? index1
?index2?
Returns contents of text widget from index1 to just before index2, if specified, or just at index1 in
repeating key value index format. Key values are text,mark,tagon,tagoff, and window. Value is
the text, mark name, tag name, or window name. Index is the start index of the text, mark, tag
transition, or window. Options are:
-all
-command command Invokes command with args key,value, and index for each text widget element within the range
of indicies instead of returning it.
-image
-mark
-tag
-text
Include text up to next element, newline, or index2 in the dump results. Newlines are included in
the dump.
Include embedded windows info in the dump results. Returns window pathname or empty string
if not created yet.
(Tk 8.4+) Controls the undo mechanism and the modified flag. Options are:
-window
pathName edit option
?arg ...?
modified ?boolean?
redo
reset
separator
undo
Sets the text widget modified flag. Without boolean, returns current state.
If -undo is true, reapplies last undo edit if no edits have occurred since then. Generates error if
redo stack is empty.
Clears the undo and redo stacks.
If -undo is true, inserts a separator (boundary) on the undo stack.
If -undo is true, undoes last edit action (all insert, delete, etc. commands between two
separators). Generates error if undo stack is empty.
pathName get
?options? ?--? index1
?index2 ...?
-displaychars
Returns only characters from index1 to just before index2, if specified, and index2 > index1, or
just at index1. An invalid range returns the empty string. In Tk 8.4+, multiple ranges can be
specified and will be returned in the specified order. Options are:
(Tk 8.5+) Specifies that only those characters which are not elided will be returned.
pathName image
option ?arg ...?
Controls embedded images. See Annotations above for more details on embedded images.
Options are:
Return current value of option for embedded image at index. For options, see Embedded Image
Options above.
configure index
?option value ...?
Changes the embedded image configuration option to value. Without value, a list describing
option is returned. Without option, a list of all available options for the image at index is
returned. For multiple options an empty string is returned. For options, see Embedded Image
Options above.
Create a new embedded image at position index with the specified options. For options, see
Embedded Image Options above.
names
Returns a list of the names of all embedded images in the text widget.
pathName index index Returns the position of index in line.char notation. See Indicies or Character Positions above.
Inserts the char args just before the character at index using each tag in tagList. If index is at the
pathName insert index
end of the text (character after the last newline), then the new text is inserted just before the last
chars ?tagList? ?chars
newline instead. Without tagList, the new text will only use tags present in both the character at
tagList ...?
index and before index. Multiple char tagList args can be used.
pathName mark option
Controls marks. See Annotations above for more details on marks. Options are:
?arg ...?
gravity markName
?direction?
Specifies which adjacent character or direction (left or right) markName is attached to. Without
direction, returns current gravity.
names
next index
Returns name of next mark at or after index . Search starts at index unless its the name of a mark
in which case it starts at the next mark. Returns empty string if no marks are left.
previous index
Returns name of previous mark at or before index. Search starts at the character before index
unless its the name of a mark in which case it starts before the mark. Returns empty string if no
marks are left.
Creates mark markName or moves it if it already exists to just before the character at index.
unset markName
?markName ...?
pathName peeroption
?args?
create newPathName
?options?
names
pathName replace
index1 index2 chars
?tagList? ?chars tagList
...?
pathName scan option
args
mark x y
(Tk 8.5+) Used to create and query widget peers. A peer widget has complete access to
pathName widgets data while maintaining separate config options except as noted in the config
options above.
Creates a peer text widget with the given newPathName, and any specified config options. By
default the peer will have the same start and end line as the parent widget.
Returns a list of peers of this widget excluding this widget.
(Tk 8.5+) Replaces the range of characters from index1 to just before index2 with the given
characters and tags in tagList. Without tagList, the new text will only use tags present in both the
character at index1 and index2.
Controls scanning on text widgets. Options are:
Records x and y and the current view in the text widget. Typically associated with mouse button
press in widget at coordinates x,y.
dragto x y
Adjusts the view by 10 times the difference between the coordinates x,y and the last mark x ,y
coordinates. Used with mouse motion events to produce high speed dragging effect.
Searches
for a match to pattern in the range of text from index to stopIndex, if specified, or back
pathName search
to
index
and
returns the index of the match. Without stopIndex, the search wraps around at the
?switches? ?--? pattern
end/beginning
of the text. The matching range must be entirely within a single line of text.
index ?stopIndex?
Switches are:
(Tk 8.5+) Find all matches in the given range and return a list of the indices of the first character
-all
of each match.
-backwards
-count varName
Stores the length of the matched text and elements in varName. Used with -all, returns a list of
counts.
(Tk 8.3+) Find elidden (hidden) text as well. By default only displayed text is searched.
The characters must exactly match pattern . Newlines are not removed from the line end before
checking for a match. (Default)
Search forward in the text from index. (Default)
-elide
-exact
-forwards
-nocase
-nolinestop
-overlap
-regexp
Adjust the view in window so character at index is completely visible. For small adjustments the
text is scrolled just enough to see the text. For large adjustments, the text is centered in the
window.
Controls tags. See Annotations above for more details on tags. Options are:
Apply tag tagName to characters in given range from index1 to just before index2. Multiple
ranges are supported.
Create a binding to evaluate command whenever event in sequence occurs within the characters
or elements associated with tagName. See bind command for options. Only mouse, keyboard,
and virtual events can be used. An Enter event for a tag triggers when the tag first becomes
present on the current character, and a Leave event triggers when it ceases to be present on the
current character. Enter and Leave events can happen either because the current mark moved or
because the character at that position changed. When a character has multiple tags with bindings,
only one binding is invoked for each tag in lowest to highest priority order. If there are multiple
bindings for a tag, the most specific binding is used. If bindings exist for the parent widget, they
will be invoked after the tag bindings.
Return current value of option for tagtagName. For options, see Tag Options above.
configure tagName
?option? ?value?
?option value ...?
delete tagName
?tagName ...?
lower tagName
?belowThis?
Changes the tag tagName configuration option to value. Without value, a list describing option is
returned. Without option, a list of all available options for the image at index is returned. For
multiple options an empty string is returned. For options, see Tag Options above.
names ?index?
Returns a list of the names of all tags associated with character at index in increasing prioity
order. Without index,a list of all defined tags is returned.
nextrange tagName
index1 ?index2?
Searches between index1 to just beforeindex2 (default is end of text) for the first region tagged
with tagName. Returns a two element list with the character range (start and end+1) of region
found or empty string if none.
Searches between just before index1 toindex2 (default is index 1.0) for the first region tagged
with tagName . Returns a two element list with the character range (start and end+1) of region
found or empty string if none.
prevrange tagName
index1 ?index2?
Delete all tag information (tags from characters, bindings, etc.) for each tagName arg.
Change priority of tag tagName so it is just below tag belowThis or without belowThis below all
tags.
raise tagName
?aboveThis?
Change priority of tag tagName so it is just above tag aboveThis or without aboveThis above all
tags.
ranges tagName
Returns a list describing all character ranges tagged with tagName. Each pair of elements
contains the start and end+1 index for that range. If no matches are found an empty list is
returned.
remove tagName
index1 ?index2 index1
index2 ...?
pathName window
option ?arg ...?
Remove tag tagName from all characters in given range from index1 to just before index2, if
specified, and index2 > index1, or just at index1. Multiple ranges are supported.
Controls embedded windows. See Annotations above for more details on embedded windows.
Options are:
Return current value of option for embedded window at index. For options, see Embedded
Window Options above.
configure index
?option value ...?
Changes the embedded window configuration option tovalue. Without value, a list describing
option is returned. Without option, a list of all available options for the image at index is
returned. For multiple options an empty string is returned. For options, see Embedded Window
Options above.
Create a new embedded window at position index with the specified options. For options, see
Embedded Window Options above.
names
Returns a list of the names of all embedded windows in the text widget.
pathName xview
?option args?
Query or change the horizontal text widget view. Without any options, a two element list is
returned specifying the start and end of the visible fraction (from 0 to 1) of the horizontal span of
the widget between the left and right edges of the window. Vaild options and args are:
moveto fraction
scroll number pages
scroll number units
Adjust the view in the window so that fraction (from 0 to 1) of the total width of the widget is
off-screen to the left.
Shift the view left (number < 0) or right (number > 0) by number screenfuls.
Shift the view left (number < 0) or right (number > 0) by average-width number of characters on
the display.
Query or change the vertical text widget view. Without any options, a two element list is
returned specifying the start and end of the visible fraction (from 0 to 1) of the vertical span of
the widget between the top and bottom edges of the window. Vaild options and args are:
Adjust the view in the window so that fraction (from 0 to 1) of the total height of the widget is
off-screen to the top.
Shift the view up (number < 0) or down (number > 0) by number screenfuls.
Shift the view up (number < 0) or down (number > 0) by number lines.
pathName yview
?option args?
moveto fraction
?-pickplace?index
number
(Obsolete) Changes the view in the widgets window to make index visible using the following
criteria: if index is already visible then dont do anything, if index is a few lines off-screen above
the window position it at the top of the window, if index is a few lines off-screen below the
window position it at the bottom of the window, otherwise center index in the window.
(Obsolete) Makes the first character on the line after the one given by number visible at the top
of the window.
Description
Positions the insertion cursor just before the character underneath the mouse
cursor, sets the input focus to this widget, and clears any selection in the widget.
Drags out a selection (in words if double clicked or lines if triple clicked) between
the insertion cursor and the character under the mouse.
Selects the word under the mouse and positions the insertion cursor at the
beginning of the word.
Selects all of the text on the line and positions the insertion cursor before the first
character.
Adjusts the end of the selection (in words if double clicked or lines if triple
clicked) that was nearest to the mouse cursor when button 1 was pressed.
Adjusts the view in the widget in the direction that the mouse left the window
more quickly.
Stops cancel repeat.
Position the insertion cursor in the widget without affecting the selection.
Paste selection into the widget at the position of the mouse cursor.
Adjusts view in widget by scrolling in the direction of the mouse movement.
(Tk 8.0.4+) Adjusts view in widget up or down in increments of 4 lines.
Moves the insertion cursor one character back (left), clears any selection, and sets
the selection anchor.
Moves the insertion cursor one character forward (right), clears any selection, and
sets the selection anchor.
Move the insertion cursor one character back (left) and extend the selection to
include the new character.
Move the insertion cursor one character forward (right) and extend the selection
to include the new character.
Move the insertion cursor back (left) by one word, clears any selection, and sets
the selection anchor.
Move the insertion cursor forward (right) by one word, clears any selection, and
sets the selection anchor.
<Shift-Control-Left>
<Shift-Control-Right>
<Up> or <Control-p>
Move the insertion cursor back (left) by one word and also extend the selection.
Move the insertion cursor forward (right) by one word and also extend the
selection.
Moves the insertion cursor up one line, clears any selection, and sets the selection
anchor.
<Down> or <Control-n>
Moves the insertion cursor down one line, clears any selection, and sets the
selection anchor.
<Shift-Up>
Move the insertion cursor up one line and extend the selection to include the new
line.
<Shift-Down>
Move the insertion cursor down one line and extend the selection to include the
new line.
<Control-Up>
Move the insertion cursor up by one paragraph, clears any selection, and sets the
selection anchor.
<Control-Down>
Move the insertion cursor down by one paragraph, clears any selection, and sets
the selection anchor.
<Shift-Control-Up>
Move the insertion cursor up by one paragraph and also extend the selection.
<Shift-Control-Down>
Move the insertion cursor down by one paragraph and also extend the selection.
<Prior>
Moves the insertion cursor up one screenful, clears any selection, and sets the
selection anchor.
<Next>
Moves the insertion cursor down one screenful, clears any selection, and sets the
selection anchor.
<Shift-Prior>
Move the insertion cursor up by one screenful and also extend the selection.
<Shift-Next>
Move the insertion cursor down by one screenful and also extend the selection.
<Control-v>
(MS Windows only) Adjusts view in widget down by one screenful without
moving the insertion cursor or adjusting the selection.
<Control-Prior>
Adjusts view in widget left by one screenful without moving the insertion cursor
or adjusting the selection.
<Control-Next>
Adjusts view in widget right by one screenful without moving the insertion cursor
or adjusting the selection.
<Home> or <Control-a>
Move the insertion cursor to the beginning of the line and clears any selection.
<Shift-Home>
Move the insertion cursor to the beginning of the line and also extends the
selection to that point.
Move the insertion cursor to the end of the line and clears any selection.
<End> or <Control-e>
<Shift-End>
<Control-Home> or <Meta-less>
Move the insertion cursor to the end of the line and also extends the selection to
that point.
Move the insertion cursor to the beginning of the text and clears any selection.
<Shift-Control-Home>
Move the insertion cursor to the beginning of the text and also extends the
selection to that point.
<Control-End> or <Meta-greater>
Move the insertion cursor to the end of the text and clears any selection.
<Shift-Control-End>
Move the insertion cursor to the end of the text and also extends the selection to
that point.
<Tab>
<Shift-Tab>
<Control-Tab>
<Control-Shift-Tab>
<Control-i>
<Return>
<Select> or <Control-Space>
Set the selection anchor to the position of the insertion cursor without affecting
the selection.
<Shift-Select> or
<Shift-Control-Space>
<Control-slash>
<Control-backslash>
<Delete>
<BackSpace> or <Control-h>
<Insert>
<Control-x>
<Control-d>
<Control-k>
Adjusts the selection to the current position of the insertion cursor, if there is one,
otherwise it selects from the anchor to the insertion cursor.
Selects all the text in widget.
Clears any selection in the widget.
Deletes the selection, if there is one, otherwise it deletes the character to the right
of the insertion cursor.
Deletes the selection, if there is one, otherwise it deletes the character to the left
of the insertion cursor.
Insert current selection from clipboard at insertion cursor position.
Deletes the selection in the widget.
Deletes the character to the right of the insertion cursor.
Deletes all the characters right of the insertion cursor to the end of the line. If
insertion cursor is at the end of the line then the newline is deleted.
Reverses (transposes) the order of the two characters to the right of the insertion
cursor.
Opens a new line by inserting a newline character in front of the insertion cursor
without moving the insertion cursor.
Deletes the word to the right of the insertion cursor.
<Control-t>
<Control-o>
<Meta-d>
<Meta-BackSpace> or
<Meta-Delete>
<Keypress>
<<Undo>> or <Control-z> or
<Control-underscore>
<<Redo>> or <Control-Z> or
<Control-y>
(Tk 8.4+) Perform edit redo if the -undo option is true. (MS Windows only
<Control-y> )
<<Selection>>
<<Modified>>
(Tk 8.4+) Generated whenever the text widget modified flag changes state.
<<Paste>>
Description
toplevel pathName
?options?
Creates a toplevel window pathName with options and returns the new widgets path name.
Used as a container for other widgets.
-highlightcolor
-cursor
-highlightthickness
-relief
-highlightbackground
-takefocus
Resource
Resource
Description
Name
Class
background Background Same as standard -background expect if set to empty string, the widget
will not display or allocate a colormap entry for the background or border
color.
-class name
class
Class
Specifies class name to use in querying the option database and for
bindings. Can not be changed with configure command.
-colormap
colormap
colormap
Colormap
Specifies colormap (default is same as parent) to use for the window where
colormap can be new (allocate new colormap) or the name of another
window on same display with same visual. Can not be changed with
configure command.
-container
boolean
container
Container
Height
Menu
-visual visual
visual
Visual
-width width
width
Width
Use
Description
Returns the current value of the configuration option. See Toplevel Window Options above for
options .
pathName configure
Change the configuration option to value. Without value, a list describing option is returned.
?option? ?value? ?option Without option, a list of all available options for pathName is returned. For multiple options an
value ...?
empty string is returned. See Top Level Options above for options.
Description
Class name followed by integer depth. Classes are: directcolor, grayscale, greyscale, pseudocolor,
staticcolor, staticgray,staticgrey, or truecolor. Depth specifies the bits per pixel for the visual. Same logic as
best option (a).
default
Use the default visual for current screen.
pathName Use same visual as window pathName . Must be on the same screen.
number
Use the visual whose X identifier is number.
best
Choose the "best possible" visual, in decreasing order of priority: (a) visual decreasing order: visual with exact
?depth?
depth, visual with depth > depth (but as little extra as possible), visual with depth < depth(but with the greatest
depth possible); (b) without depth, then the deepest available visual is used; (c) class in decreasing order:
pseudocolor,truecolor, or directcolor, staticcolor, staticgray, or grayscale ; (d) the default visual for the
screen is better than any other visual.
Description
Returns integer identifier for the atom given by name on windows display (default is the
same as applications main window).
winfo atomname ?-displayof Returns textual name of the atom given by integer id on windows display (default is the
window? id
same as applications main window).
winfo cells window
Returns a list containing the path names of windows children in stacking order except for
top-level windows.
Returns the path name of window highest in the stacking order containing the point given
winfo containing ?-displayof
by rootX and rootY (in screen units) on windows display (default is the same as
window? rootX rootY
applications main window) or empty string if none.
winfo depth window
winfo id window
Returns a list of all Tcl interpreters registered on windows display (default is the same as
applications main window).
Returns the name of the geometry manager currently responsible for window or empty
string if none.
Returns windows name within its parent, as opposed to its full path name.
Returns the path name of windows parent or empty string if window is the main window
of the application.
Returns the path name of the window whose X identifier is id on windows display
(default is the same as applications main window).
Returns the number of pixels in window rounded to the nearest integer value
corresponding to number distance in screen units.
Returns the mouse pointers x root coordinate in pixels on windows screen. Returns -1 if
the mouse pointer isnt on the same screen as window.
Returns a two element list of mouse pointers x and y root coordinates in pixels on
windows screen. Returns -1 for each coordinate if the mouse pointer isnt on the same
screen as window.
Returns the mouse pointers y root coordinate in pixels on windows screen. Returns -1 if
the mouse pointer isnt on the same screen as window.
Returns a list of the three RGB values that correspond to color in window. See Colors in
Options and Resources for valid color formats.
Returns the x-coordinate of the upper-left corner of window (including its border if
present) in the root window of the screen.
Returns the y-coordinate of the upper-left corner of window (including its border if
present) in the root window of the screen.
Returns the name of the screen associated with window, in the form
displayName.screenIndex.
Returns the number of cells in the default color map for windows screen.
winfo screenmmheight
window
winfo screenmmwidth
window
Returns the visual class of windows screen. Options are: directcolor, grayscale,
pseudocolor,staticcolor, staticgray, or truecolor.
Returns a platform specific formatted string containing information about the server for
windows display.
Returns the pathname of the top-level window containing window.
Returns 1 if window and all of its ancestors up through the nearest toplevel window are
mapped, 0 if not.
Returns the visual class of window. Options are: directcolor, grayscale,
pseudocolor,staticcolor , staticgray, or truecolor.
Returns the height of the virtual root window associated with window if there is one,
otherwise the height of window s screen.
Returns the width of the virtual root window associated with window if there is one,
otherwise the width of windows screen.
Returns the x-offset of the virtual root window associated with window relative to the root
window of its screen or 0 if there isnt a virtual root window for window.
Returns the y-offset of the virtual root window associated with window relative to the root
window of its screen or 0 if there isnt a virtual root window for window.
winfo x window
Returns x-coordinate of the upper-left corner of window (including its border if present)
in its parent.
winfo y window
Returns y-coordinate of the upper-left corner of window (including its border if present)
in its parent.
Description
Rings the X bell on windows (default is ".") display. In Tk 8.4+ the screen saver is reset if
-nice is not specified.
tk scaling ?-displayof
window? number
tk useinputmethods
?-displayof window?
?boolean?
tk windowingsystem
wm aspect window
?minNumer minDenom
maxNumer maxDenom?
wm attributes window
?option value ...?
Deletes each window and all their descendents. If window "." is destroyed, the entire
application will be deleted. Windows are deleted in order, but stops if an error occurs. If a
window doesnt exist, no error is returned.
Returns the path name of the focus window on the display containing the applications
main window or an empty string if not the same application.
Changes focus to window on windows display. Does not alter which top-level has the input
focus for the the display.
Returns the path name of the focus window on the display containing window or an empty
string if not the same application.
Sets the focus of windows display to window, even if the application doesnt currently
have the input focus for the display.
Returns the name of the most recent window to have the input focus among all the
windows in the same top-level as window. If none or it was deleted, then the name of the
top-level is returned.
Same as grab set.
Returns name of current grab window on windows display or empty string if not the same
application. Without window, returns list of all windows grabbed by application for all
displays.
Releases grab on window.
Sets a local grab (grabbing application only) on window unless -global (locks out all other
apps on screen except subtree of grabbing app) is specified. If grab was already in effect, it
is released.
Returns current grab state (none,local, or global) for window.
Places window below window belowThis (default is below all siblings) in stacking order.
Places window above window aboveThis (default is above all siblings) in stacking order. In
Tk 8.3.4+, it does not block for 2 seconds.
Change focus model of application to an implicit one where the focus follows the mouse
pointer.
Returns the window just after window in focus order.
Returns the window just before window in focus order.
Sets and returns the applications interpreter name to newName (must not start with
uppercase char) appending # and an integer if necessary to create a unique name. Without
newName , returns current name. Reenables the send command if it was deleted.
(Tk 8.4+) Sets the caret location for the display of the specified Tk window window. The
caret is the per-display cursor location used for indicating global focus. x and y represent
window-relative coordinates, and height is the height of the current cursor location, or the
height of the specified window if none is given. Without any options, the last used values
are returned.
Set scaling factor for conversion between physical units and pixels on windows display
(default is current) where number (floating point value) is the pixels per point (1/72 inch).
(Tk 8.3+) Specifies whether Tk should use XIM (X Input Methods) for filtering events on
window (default is main window). Without boolean, the current setting is returned (default
is on in Tk 8.3.3+ and off for previous versions).
(Tk 8.4+) Returns the current Tk windowing system. Options are: x11 (X11-based), win32
(MS Windows), classic (Mac OS Classic), or aqua (Mac OS X Aqua).
Specifies the aspect ratio of window (width/length) to be constrained to lie between
minNumer/minDenom and maxNumer /maxDenom. If all are set to empty strings, then any
existing aspect ratio restrictions are removed. Without options a list of the current values is
returned.
(Tk 8.4+) Change the platform specific window manager attribute (used by MS Windows
only) option to value . Without value, the current value for option is returned. Without
option, a list of all platform specific flags and their values is returned. Options are:
-alpha value
(Tk 8.4.8+ MS Windows, Mac OSX) set alpha transparency. 0.0 (completely transparent)
to 1.0 (opaque). Default is 1.0.
-disabled ?boolean?
-fullscreen ?boolean?
(Tk 8.5+ MS Windows only) Requests that the window should fill the entire screen and
have no window decorations.
(Mac OSX) Window modification state (determines whether the window close widget
contains the modification indicator).
-modified ?boolean?
-titlepath ?path?
(Mac OSX) Window proxy title path (file referenced as the window proxy icon which can
be dragged and dropped in lieu of the files finder icon).
-toolwindow ?boolean?
-topmost ?boolean?
(MS Windows only) Requests that this window should be kept above all other windows
that do not also have the -topmost attribute set.
(UNIX TBD) Requests that the window should be maximized. Same as wm state zoomed
on Windows.
-zoomed?boolean?
wm colormapwindows
window ?windowList?
wm command window
?value?
wm deiconify window
wm focusmodel window
?option?
Specifies the focus model for window. Options are: active (claim focus for itself or
decendents) or passive (default option to never claim focus for itself).Without option,
returns the current focus model.
wm frame window
Returns the platform specific window identifier for the outermost decorative frame that
contains window. If window has none, returns the platform specific ID of window itself.
wm geometry window
?newGeometry?
Indicates that window is to be managed as a gridded window with the specified relation
between grid and pixel units. BaseWidth and baseHeight specify the number of grid units
wm grid window ?baseWidth
corresponding to the pixel dimensions requested internally by window.WidthInc and
baseHeight widthInc
heightInc specify the number of pixels in each horizontal and vertical grid unit. If all are set
heightInc?
to empty strings, then window will no longer be managed as a gridded window. Without
options a list of the current values is returned.
wm group window
?pathName?
wm iconbitmap window
?bitmap?
wm iconbitmap window
-default filename.ico
wm iconify window
wm iconmask window
?bitmap?
Gives path name for leader of group to whichwindow belongs. Without pathName, returns
window s current group leader. When set to empty string, window is removed from any
groups.
Specifies a bitmap to use as icon image when window is iconified. If set to an empty string,
then the current bitmap is cancelled. Without bitmap, the current bitmap name is returned
or empty string if none. If a "@" is the first char, the bitmap is a filename. Unix uses .xbm
files and windows uses .ico files.
(Tk 8.3.3+, MS Windows only) Specifies a bitmap file to use as icon image when window
is iconified. Overridden by wm iconphoto.
Arrange for window to be iconified.
Specifies a bitmap to use to mask icon image when window is iconified. If set to an empty
string, then the current bitmap is cancelled. Without bitmap, the current bitmap name is
returned or empty string if none.
wm iconname window
?newName?
Specifies name to use as a label for window s icon. If set to an empty string, then the
current name is cancelled and the windows title is used. Without newName, the current
name is returned or empty string if none.
(Tk 8.5+ MS Windows and UNIX) Specifies a image to use as icon image in titlebar and
when window is iconified. If -default is specified, this is applied to all future created
toplevels as well. Multiple images are accepted to allow different images sizes (eg, 16x16
and 32x32) to be provided. On UNIX, only use 2 images and put larger image first.
Specifies hints for position x and y on root window to place windows icon. If set to empty
wm iconposition window ?x
strings, then the current position is cancelled. Without x y, a list of the current values is
y?
returned or empty string if none.
wm iconphoto window
?-default? image1 ?image2
...?
wm iconwindow window
?pathName?
Specifies the path name of window to use as the icon when window is iconified. If set to an
empty string, then the current icon window is cancelled. Without pathName, the current
name of the icon window is returned or empty string if none.
Specifies maximum window size for window in pixels or grids for gridded windows. If set
wm maxsize window ?width
to empty strings, the sizes default to the screen size. Without width height, a list of the
height?
current max sizes is returned.
wm minsize window ?width
height?
Specifies mimum window size for window in pixels or grids for gridded windows. If set to
empty strings, the sizes default to one pixel in each dimension. Without width height, a list
of the current min sizes is returned.
wm overrideredirect
window ?boolean?
Specifies the override-redirect flag for window which is commonly used by the window
manager to determine whether window should show a decorative frame.
wm positionfrom window
?who?
Specifies whether windows current position was program or user requested. If set to an
empty string, the current position source is cancelled. Without who, the current position
source is returned.
wm protocol window
?name? ?command?
Specify a Tcl command to be invoked for messages of protocol name. Valid values for
name are: WM_DELETE_WINDOW, WM_SAVE_YOURSELF, or
WM_TAKE_FOCUS. Without command , the current command for name is returned. If
name is set to an empty string, then current handler is deleted. Without name or command ,
a list of all protocol handlers is returned.
wm resizable window
?widthBoolean
heightBoolean?
Specifies whether windows width and/or height is resizable (default is true for both).
Without the options, a list of the current values is returned.
Specifies whether windows current size was program or user requested. If set to an
wm sizefrom window ?who? empty string, the current size source is cancelled. Without who, the current size source is
returned.
wm stackorder window
?option? ?newWindow?
wm state window
?newState?
(Tk 8.4+) Returns stacking order of windows children in lowest to highest order. Returns
relative position of window compared to newWindow based on options isabove and
isbelow.
Returns current state of window. In Tk 8.3+, newState changes the current state of window.
Options are: normal, icon, iconic, withdrawn, and zoomed (MS Windows only).
Specifies the title for windows decorative frame. Without string, the current name is
returned.
wm transient window
?master?
Informs window manager that window is a transient of the window master. If set to an
empty string, then window is not marked as a transient window. Without master, the path
name of windows current master, or an empty string if none, is returned.
wm withdraw window
Description
(Tcl 8.5+) Evaluates a command and its arguments using the interpreter specified by topic. The DDE
service must be the TclEval service. The -async option requests asynchronous invocation. Returns an
error message if the script did not run unless the -async option was specified.
Sends data to the server indicated by service with the topic topic. Typically the application name is
the service, the filename is the topic, and data is a script to be run on the file. The -async flag
requests an asynchronous invocation. An error message will be returned if the script does not run
unless the -async flag was specified.
(Tcl 8.2+) Sends data as the value for item to the server indicated by service with the topic topic.
Typically the application name is the service, the command or filename is the topic, item is
application specific but is often not used (cant be null), and data is the value to use.
dde request
?-binary? service
topic item
Returns the value of item from the server indicated by service with the topic topic. Typically the
application name is the service, the filename is the topic, and item is application specific. In Tcl
8.4+, if -binary is specified, the result is returned as a byte array, otherwise a null terminated string is
assumed.
dde execute
?-async? service
topic data
dde servername
?options? ?--?
?topic?
-force
Registers the interpreter as a DDE server with the service name TclEval and the topic name topic.
Without topic, the current topic or an empty string (if no service is registered) will be returned.
Command
Description
::http::cleanup token
::http::code token
::http::config ?options?
-accept mimetypes
-proxyhost hostname
-proxyport number
-proxyfilter command
-urlencoding encoding
(Tcl 8.4.7+)
-useragent string
::http::data token
::http::error token
::http::formatQuery key value ?key value ...?
::http::geturl url ?options?
-binary boolean
-blocksize size
-channel name
-command callback
-handler callback
-headers keyvaluelist
-progress callback
-query query
-queryblocksize size
-querychannel channelID
-queryprogress callback
-timeout milliseconds
-type mime-type
(Tcl 8.2.3+)
-validate boolean
::http::ncode token
::http::register proto port command
(Tcl 8.2.3+)
(Tcl 8.2.3+)
::http::wait token
Command
::msgcat::mc src-string ?arg
arg ...?
::msgcat::mcload dirname
Description
(Tcl 8.1+) Returns a translation of src-string according to the users current locale.
Searches from the current namespace up to the global namespace. If none found, returns
result of ::msgcat::mcunknown. If additional arguments past src-string are given, the
format command is used to substitute the additional arguments in the translation of
src-string.
(Tcl 8.4+) Reads the contents of files in dirname that match the language specifications
returned by ::msgcat::mcpreferences and have a ".msg" extension.
(Tcl 8.1+) Sets the locale to newLocale (case insensitive). Without newLocale, returns the
current locale.
::msgcat::mclocale
?newLocale?
::msgcat::mcmax ?src-string
(Tcl 8.4+) Returns the length of the longest translated src-string.
src-string ...?
::msgcat::mcmset locale
src-trans-list
(Tcl 8.4+) Sets the translation for multiple source strings in src-trans-list (list of src-string
and translate-string pairs) in the specified locale and the current namespace.
(Tcl 8.1+) Returns a list of the user preferred locales in most specific to least specific order,
based on the users language specification.
::msgcat::mcset locale
(Tcl 8.1+) Sets the translation for src-string to translate-string in the specified locale and
src-string ?translate-string? the current namespace. If translate-string is not specified, src-string is used for both.
::msgcat::mcunknown locale (Tcl 8.1+) Used by ::msgcat::mc when src-string is not defined in the current locale.
src-string
Default action is to return src-string. Can be redefined to do other things.
::msgcat::mcpreferences
Tcl 8.5 adds: msgcat::mcpreferences command will be modified to add the empty string as a list element after the elements
corresponding to the current locale.
Locale Specification
Defult locale is specified at start-up by checking for the first non-empty value in the ::env(LC_ALL) variable,
::env(LC_MESSAGES) variable , ::env(LANG) variable, and the Windows registry (MS Windows only). Defaults to a
locale of "C".
Locale Format
Name
Example
language[_country][_modifier] The country, language, and system-specific codes.
language[_country]
The country and language codes.
en_US
language
{}
en
The country and language codes are specified in standards ISO-639 and ISO-3166
Command
Description
registry broadcast
keyName ?-timeout
milliseconds?
(Tcl 8.4.1+) Sends a broadcast message to the system and running programs to notify them of
an update to keyName. Used for environment updates, etc. The timeout specifies how long to
wait (default is 3000) for applications to respond to the broadcast message.
Deletes valueName from the registry under keyName. Without valueName, keyName and all
values under it are deleted. Returns an error if the keyNameor ValueName could not be
deleted.
Returns the data associated with the value valueName under the key keyName. Returns an
error if keyName or ValueName doesnt exist. See Supported Data Types below, for the
types.
Returns a list of names of the subkeys under keyName matching pattern (using Pattern
Globbing), if specified, or all subkeys without pattern. Returns an error if keyName doesnt
exist.
Sets valueName under keyName to data with type type (defult is sz). Creates the key
registry set keyName
keyName if it doesnt already exist. Without valueName,the key is only created if it doesnt
?valueName data ?type??
exist. See Supported Data Types below, for the types.
registry type keyName
valueName
Returns the type of the value valueName in the key keyName. See Supported Data Types
below, for the types.
Returns a list of names of the values under keyName matching pattern (using Pattern
Globbing), if specified, or all values without pattern. Returns an error if keyName doesnt
exist.
Type
binary
Description
The registry value contains arbitrary binary data.
none
The registry value contains arbitrary binary data with no defined type.
sz
multi_sz
resource_list
Representation
binary string
binary string
string
string
decimal string
decimal string
binary string
list of strings
binary string
Unknown types are with the 32-bit integer for that type code returned by the system interfaces and the data is represented
as a binary string.
Command
Sect#
after
2.07
append
2.17
array
2.01
auto_execok
2.03
auto_import
2.03
auto_load
2.03
auto_mkindex
2.03
auto_mkindex_old 2.03
auto_qualify
2.14
auto_reset
2.03
bell
3.28
bgerror
2.03
binary
2.17
bind
3.1
bindtags
3.1
break
2.04
button
3.2
canvas
3.3
case
2.04
catch
2.03
cd
2.10
checkbutton
3.4
clipboard
3.5
clock
2.02
close
2.10
concat
2.13
console
3.6
consoleinterp
3.6
continue
2.04
dde
4.1
destroy
3.28
dict
2.05
encoding
2.06
entry
3.8
eof
2.10
error
2.03
eval
2.03
event
3.1
2.10
exec
2.03
exit
2.03
expr
fblocked
2.10
Command
fconfigure
fcopy
file
fileevent
flush
focus
font
for
foreach
format
frame
gets
glob
global
grab
grid
history
Sect#
2.10
2.10
2.08
2.08
2.10
3.28
3.9
2.04
2.04
2.17
3.10
2.10
2.10
2.16
3.28
3.11
2.09
::http
4.2
if
2.04
image
3.12
incr
2.18
info
2.11
interp
2.12
join
2.13
label
3.13
labelframe 3.14
lappend 2.13
lassign
lindex
linsert
list
listbox
llength
load
lower
lrange
lrepeat
lreplace
lsearch
lset
lsort
memory
2.13
2.13
2.13
2.13
3.15
2.13
2.03
3.28
2.13
2.13
2.13
2.13
2.13
2.13
2.11
Command
Sect#
menu
3.16
menubutton 3.17
message
3.18
::msgcat
4.3
namespace 2.14
2.10
open
option
3.19
3.11
pack
2.15
package
panedwindow 3.20
2.01
parray
2.10
pid
3.11
place
2.15
::pkg
pkg_mkIndex 2.15
proc
2.16
2.10
puts
2.10
pwd
radiobutton 3.21
3.28
raise
2.10
read
2.17
regexp
registry
regsub
rename
resource
return
::safe
scale
scan
scrollbar
seek
selection
send
set
socket
source
spinbox
split
string
subst
switch
4.4
2.17
2.03
4.5
2.16
2.12
3.22
2.17
3.23
2.10
3.5
2.03
2.18
2.10
2.03
3.24
2.13
2.17
2.03
2.04
Command
Sect#
tcl_endOfWord
2.17
tcl_findLibrary
2.03
tcl_startOfNextWord
2.17
tcl_startOfPreviousWord 2.17
tcl_wordBreakAfter
2.17
tcl_wordBreakBefore
2.17
tcltest
tell
text
time
tk
tkwait
tk_bisque
tk_chooseColor
tk_chooseDirectory
tk_dialog
tk_focusFollowsMouse
tk_focusNext
tk_focusPrev
tk_getOpenFile
tk_getSaveFile
tk_menuSetFocus
tk_messageBox
tk_optionMenu
tk_popup
tk_setPalette
tk_textCopy
tk_textCut
tk_textPaste
toplevel
trace
unknown
unload
unset
update
uplevel
upvar
variable
vwait
while
winfo
wm
4.6
2.10
3.25
2.03
3.28
2.07
3.19
3.7
3.7
3.7
3.28
3.28
3.28
3.7
3.7
3.16
3.7
3.17
3.16
3.19
3.25
3.25
3.25
3.26
2.18
2.03
2.03
2.18
2.07
2.18
2.18
2.14
2.07
2.04
3.27
3.28