treeview(n)
πΈ NAME β treeview(n) but make it cute πΈ
treeview β create and manipulate hierarchical table widgets. This is the treeview(n) page from BLT Built-In Commands, and yes bestie, we're doing the whole thing. π
β¨ SYNOPSIS β¨
treeview pathName ?options?
π¦ DESCRIPTION π¦
Okay so the treeview widget displays a tree of data with styles, tags, and data sharing (via tree data objects). It's giving hierarchical data, but with accessories. β¨
π INTRODUCTION π
The treeview widget manages a collection of entries where each entry contains a tree node plus added style and attribute information. So every entry is a node wearing its little outfit. π
Entries are usually inserted into a treeview with a label-list to specify the unique hierarchical position relative to root (or the -at node); the tail of this label-list is unique within its hierarchical level. If no label is given, the generated node-id is used as the label. Labels provide a convenient way to index entries using the -> notation. eg.
treeview .t
.t insert end
.t insert end X
.t insert end A {A a} {A b} B C
.t insert end a b c {c i} {c ii} -at root->B
set id [.t index root->B->c->i]
puts [.t get $id]; # outputs i
puts [.t get -full $id]; # outputs {B c i}
pack .t
π COLUMN DATA π
Column data can be stored within an entry using the -data option or entry sub-commands, eg.
treeview .t
.t column insert end X Y Z
.t insert end A -data {X 1 Y 2}
.t insert end B -data {X 3 Y 4 Z 5}
.t entry conf root->B -data {X 5 Y 4 Z 3}
.t entry set root->A Z 3
.t entry incr root->B Y
pack .t
Labels can be created with auto-generated sequence numbers using an empty string or a trailing #auto.
treeview .t
.t column insert end X
.t insert end {} -data {X 0}; # Label is "1"
.t insert end #auto -data {X 1}; # Label is "2"
.t insert end Foo#auto -data {X 2}; # Label is "Foo1"
pack .t
π§ TREE DATA OBJECT π§
Node data in treeview is actually stored in a tree data object, which separates data storage from widget appearance. The -tree option can be used to explicitly set a tree (externally created with the tree command) thus giving access to tree's more extensive data manipulation facilities, eg.
set t [tree create]
$t insert root -label A
$t insert root->A -label B -data {X 1}
treeview .t -tree $t
.t column insert end X
pack .t
A tree can also be attached to a treeview, eg.
set t [tree create]
$t attach [.t cget -tree]
set dump [$t dump root]
tree destroy $t
Heads up bestie: when inserting data via the tree sub-commands, unique label checking is not performed. No cap. π
π SYNTAX π
treeview pathName ?option value?... β the treeview command creates a new window pathName and makes it into a treeview widget. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist. Additional options may be specified on the command line or in the option database to configure aspects of the widget such as its colors and font. See the configure operation below for the exact details about what option and value pairs are valid.
If successful, treeview returns the path name of the widget. It also creates a new Tcl command by the same name. You can use this command to invoke various operations that query or modify the widget. The operations available are described in the TREEVIEW OPERATIONS section.
Treeview displays nodes as row entries in the widget. Each entry has a text label and icon. When a node has children, its entry is drawn with a small button to the left of the label. Clicking the mouse over this button opens or closes the node. When a node is open, its children are exposed. When it is closed, the children and their descendants are hidden. The button is normally a + or - symbol (ala Windows Explorer), but can be replaced with a pair of Tk images (open and closed images).
If the node has data associated with it, they can be displayed in columns running vertically on either side the tree. You can control the color, font, etc of each entry. Any entry label or data field can be edited in-place. Slay. π
π IDS AND TAGS π
Nodes can be inserted into a tree using the treeview widget
blt::treeview .t
set node [.t insert end "one"]
or tree command.
set tree [blt::tree create]
set node [$tree insert root -label "one"]
blt::treeview .t -tree $tree
In both cases, a number identifying the node is returned (the value of $node). This serial number or id uniquely identifies the node. Please note that you can't infer a location or position of a node from its id. The only exception is that the root node is always id 0. Since nodes may have the same labels or be moved within the tree, ids provide a convenient way to identify nodes. If a tree is shared, the ids will be the same regardless of whether you're using the treeview widget or the tree command. Ids are recycled only when all nodes are deleted.
A node may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, x123 is valid, but 123 isn't. The same tag may be associated with many different nodes. This is typically done to associate a group of nodes. Many operations in the treeview widget take either node ids or tag names as arguments. Using a tag means apply the operation to all nodes with that tag.
Commands that take a tagnode will also accept a list of zero or more integer node numbers (node-list). A node-list consist of space separated integers, without leading spaces. Node lists can simplify the use of iterating commands and are used widely in the tree command.
There are four built-in or psuedo tags:
allβ applies to every node in the tree.nonrootβ applies to every node in the tree except the root node.rootchildrenβ applies to every node in the tree whose parent is the root node.rootβ managed automatically by the tree object,rootspecifies the node that is currently set as the root node for the tree.
Tags are shared between clients. This means for example that tags created by the tree command are available in the treeview widget.
π SPECIAL NODE IDS π
There are several special non-numeric ids. Special ids differ from tags in that they are always translated to a single numeric node. They also take precedence over tags. For example, you can't use a tag name that is a special id. These ids are specific to the treeview widget.
activeβ the node where the mouse pointer is currently located. When a node is active, it is drawn using its active icon (see the-activeiconoption). Theactiveid is changed automatically by moving the mouse pointer over another node or by using theentry activateoperation. Note that there can be only one active node at a time. π±οΈanchorβ the node representing the fixed end of the current selection. The anchor is set by theselection anchoroperation.bottomβ the last viewable node.currentβ the node where the mouse pointer is currently located. But unlikeactive, this id changes while the selection is dragged. It is used to determine the current node during button drags.downβ the next open node from the current focus. Thedownof the last open node is the same.endβ the last node at depth 1 in tree.focusβ the node that currently has focus. When a node has focus, it receives key events. To indicate focus, the node is drawn with a dotted line around its label. You can change the focus using thefocusoperation.lastβ same astail.markβ the node representing the non-fixed end of the current selection. The mark is set by theselection markoperation.nextβ the next open node from the current focus. But unlikedown, when the focus is on last open node,nextwraps around to the root node.nextsiblingβ the next sibling from the node with the current focus. If the node is already the last sibling then it is thenextsibling.parentβ the parent of the node with the current focus. The parent of the root is also the root.prevβ the last open node from the current focus. But unlikeup, when the focus is at root,lastwraps around to the last open node in the tree.prevsiblingβ the previous sibling from the node with the current focus. If the node is already the first sibling then it is theprevsibling.rootβ the root node. You can also use id0to indicate the root.tailβ the last node in the tree, viewable or not.topβ the first node.upβ the last open node (in depth-first order) from the current focus. Theupof the root node (i.e. the root has focus) is also the root.view.topβ first node that's current visible in the widget.view.bottomβ last node that's current visible in the widget.@x,yβ indicates the node that covers the point in the treeview window specified by x and y (in pixel coordinates). If no part of theentrydcovers that point, then the closest node to that point is used. (Yes, the page saysentryd; we're keeping the lore. π)ID->LABEL->LABEL...β lookup via node labels, eg.0->Main->Users. Quotes can be used around labels that use reserved words or contain spaces, eg.0->"Main"->'User Groups'. See thetreeman page for more details.
A node may be specified as an id or tag. If the specifier is an integer then it is assumed to refer to the single node with that id. If the specifier is not an integer, it's checked to see if it's a special id (such as focus). Otherwise, it's assumed to be tag. Some operations only operate on a single node at a time; if a tag refers to more than one node, then an error is generated. Periodt. π
π DATA FIELDS π
okay so bestie, nodes in treeview can manage data fields associated with columns. The data is displayed in columns running on either side of the displayed tree. Any node that doesn't have a specific field will show as blank. Columns can (interactively) be resized, hidden, and, moved. π
Nodes can contain disjoint data fields (they aren't required to set all fields). And data manipulated via the tree command does not require an associated treeview column at all. periodt.
π§ ARRAY REFERENCES π§
Like tree, treeview supports accessing data sub-fields with an array notation, eg.
treeview .t
.t col insert end A
.t insert end a -data {A "x 1 y 2 z 3"}
.t entry incr root->a A(x)
.t entry set root->a A(w) 0
.t entry unset root->a A(z)
Only the following treeview commands support the array notation: entry get, entry set, entry incr, entry unset, and find -column. See tree for more complete support. iykyk β¨
π ENTRY BINDINGS π
You can bind Tcl commands to be invoked when events occur on nodes (much like Tk canvas items). You can bind a node using its id or its bindtags. Bindtags are simply names that associate a binding with one or more nodes. There is a built-in tag all that all node entries automatically have. π«Ά
π₯ TREEVIEW OPERATIONS π₯
The treeview operations are invoked by specifying the widget's pathname, the operation, and any arguments that pertain to that operation. The general form is:
pathName operation ?arg arg ...?
Operation and the args determine the exact behavior of the command. The following operations are available for treeview widgets:
pathName bbox ?-screen? tagOrId...β Returns a list of 4 numbers, representing a bounding box around the specified entries. The entries are given by one or moretagOrIdarguments. If the-screenflag is given, then the x-y coordinates of the bounding box are returned as screen coordinates, not virtual coordinates. Virtual coordinates start from 0 from the root node and include the title. If the-worldflag is given, then the title height is added into the y coordinate. The returned list contains the following values:xβ X-coordinate of the upper-left corner of the bounding box.yβ Y-coordinate of the upper-left corner of the bounding box.widthβ Width of the bounding box.heightβ Height of the bounding box.
pathName bind tagName ?sequence command?β AssociatescommandwithtagNamesuch that whenever the event sequence given bysequenceoccurs for a node with this tag,commandwill be invoked. The syntax is similar to thebindcommand except that it operates ontreeviewentries, rather than widgets. ThetagNamecan be an entry or tag, or predefined tags such asall,EntryorButton. See thebindmanual entry for complete details onsequenceand the substitutions performed oncommandbefore invoking it.
If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName. If the first character of command is + then command augments an existing binding rather than replacing it. If no command argument is provided then the command currently associated with tagName and sequence (it's an error if there's no such binding) is returned. If both command and sequence are missing then a list of all the event sequences for which bindings have been defined for tagName is returned.
pathName button operation ?args?β This command is used to control the button selectors within atreeviewwidget. It has several forms, depending onoperation:pathName button activate tagOrIdβ Designates the node given bytagOrIdas active. When a node is active its entry is drawn using its active icon (see the-activeiconoption). Note that there can be only one active entry at a time. The special idactiveindicates the currently active node.pathName button bind tagName ?sequence command?β AssociatescommandwithtagNamesuch that whenever the event sequence given bysequenceoccurs for a button of a node entry with this tag,commandwill be invoked. The syntax is similar to thebindcommand except that it operates ontreeviewbuttons, rather than widgets. See thebindmanual entry for complete details onsequenceand the substitutions performed oncommandbefore invoking it.
If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName. If the first character of command is + then command augments an existing binding rather than replacing it. If no command argument is provided then the command currently associated with tagName and sequence (it's an error if there's no such binding) is returned. If both command and sequence are missing then a list of all the event sequences for which bindings have been defined for tagName is returned.
pathName button cget optionβ Returns the current value of the configuration option given byoption.optionmay have any of the values accepted by theconfigureoperation described below.pathName button configure ?option? ?value option value ...?β Query or modify the configuration options of the widget. If nooptionis specified, returns a list describing all of the available options forpathName(seeTk_ConfigureInfofor information on the format of this list). Ifoptionis specified with novalue, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if nooptionis specified). If one or moreoption-valuepairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string.optionandvalueare described in the section BUTTON OPTIONS below.
pathName cget optionβ Returns the current value of the configuration option given byoption.optionmay have any of the values accepted by theconfigureoperation described below.pathName close ?-recurse? ?-trees? tagOrId...β Closes the node specified bytagOrId. In addition, if a Tcl script was specified by the-closecommandoption, it is invoked. If the node is already closed, this command has no effect. If the-recurseflag is present, each child node is recursively closed. The-treesflag is like-recursebut operates only on nodes with children, excluding the root.pathName column operation ?args?β The following operations are available fortreeviewcolumns.pathName column activate columnβ Sets the active column tocolumn.columnis the name of a column in the widget. When a column is active, it's drawn using its-activetitlebackgroundand-activetitleforegroundoptions. Ifcolumnis"", then no column will be active. If nocolumnargument is provided, then the name of the currently active column is returned.pathName column bbox ?-visible? column entryβ Returns a list of 4 numbers, representing a bounding box around the specified entry's cell. Giving anentryof-1matches the title row. If-visibleis given, the width is constrained to not extend past the widget's display.pathName column bind column ?sequence command?β These deal with the title part of columns. Associatescommandwithcolumnsuch that whenever the event sequence given bysequenceoccurs for a column node entry with this tag,commandwill be invoked. The syntax is similar to thebindcommand except that it operates ontreeviewcolumns, rather than widgets. See thebindmanual entry for complete details onsequenceand the substitutions performed oncommandbefore invoking it.pathName column cget name optionβ Returns the current value of the column configuration option given byoptionforname.nameis the name of a column that corresponds to a data field.optionmay have any of the values accepted by theconfigureoperation described below.pathName column configure name ?name ...? ?option? ?value option value ...?β Query or modify the configuration options of one or more columnsname.nameis the name of the column corresponding to a data field. If nooptionis specified, returns a list describing all of the available options forpathName(seeTk_ConfigureInfofor information on the format of this list). Ifoptionis specified with novalue, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if nooptionis specified). If one or moreoption-valuepairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string.optionandvalueare described in the section COLUMN OPTIONS below.pathName column currentβ Get column currently under the mouse.pathName column delete field ?field...?β Deletes one or more columns designated byfield. Requests to delete the tree column are silently ignored. Note that this does not delete the data fields themselves.pathName column index indexβ Return the integer forindex. May use"end"orend-N.
okay so the column subcommands keep rolling, and theyβre lowkey carrying the whole widget rn:
pathName column insert position field ?field ...? ?options...?β inserts one (or more) columns designated by field. A column displays each entry nodeβs data field using this name. If the node doesnβt define the given field, the cell is left blank. position says where in the list of columns to add the new column β it can be a name, a number orend. If multiple column fields are given, only the first can start with a dash. If field is the empty string or#auto, a name is generated prefixed by the stringColand a unique integer. If field ends with#auto, the generated name uses its prefix instead. The returned values are the created column names. Note: the tree column#0is predefined and can not be deleted. π¨pathName column invoke fieldβ invokes the Tcl command associated with the column field, if there is one (using the columnβs-commandoption). The command is ignored if the columnβs-stateoption is set todisabled.pathName column isset ?startOrTag? ?end?β returns a list of data columns for elements in the range that actually have data values set in them. One possible use for this might be hiding columns which are empty. With no arguments, it checks only entries on the visible screen. With one argument, it checks all entries matching a tag or id. With two arguments, it checks all entries between start and end range.pathName column istree fieldβ return1if the column is the tree column.pathName column move name destβ moves the column name to the destination position. dest is the offset, the name of another column or a screen position in the form@x,y.pathName column names ?-visible? ?PATTERN?β returns a list of the names of all columns in the widget. The list is ordered as the columns are drawn from left-to-right. If-visible, then display only columns where-hideis0. A PATTERN may be specified to limit results.pathName column nearest x ?y?β returns the name of the column closest to the given X-Y screen coordinate. If you provide a y argument (itβs optional), a name is returned only when the point is over a columnβs title. π―pathName column offsetsβ returns the starting offsets for each column.pathName column resize op ...β operations for resize, where op is one ofactivate,anchor,markorset.pathName column see ?-anchor anchor? fieldβ adjusts the view so that the column given by field is visible in the widget window. The nodeβs position on the screen can be set using the-anchorflag. Its value is a Tk anchor position:w,c,e.pathName column values ?-visible? ?-default value? field ?start? ?end?β returns a list of data values for a column. The-visibleflag excludes the values that are hidden or inside closed subtrees. The root nodes do not get included when-hiderootis true. The-defaultoption specifies a value to substitute for unset data column cells.
pathName configure ?option? ?value option value ...?β query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (seeTk_ConfigureInfofor information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option and value are described in the section TREEVIEW OPTIONS below. β¨pathName curselectionβ returns a list containing the ids of all of the entries that are currently selected. If there are no entries selected, then the empty string is returned.pathName delete tagnode...β deletes one or more entries given by tagnode and its children. πpathName edit ?-test? ?-root? ?-noscroll? ?-scroll? ?X Y?β handle cell editing. The x,y coordinates are usually required, except when using the scroll options.-noscrollβ disable scrolling. Useful when displaying an edit subwindow.-scrollβ re-enable scrolling. Usually bound to a destroy event of an edit subwindow.-rootβ use root coordinates.-testβ test if edit is complete.
pathName entry operation ?args?β the following operations are available for treeview entries:pathName entry activate tagOrIdβ sets the active entry to the one specified by tagOrId. When an entry is active it is drawn using its active icon (see the-activeiconand-activeleaficonoptions). The special id of the currently active node isactive. Note that there can be only one active node at a time and currently icons must be the same size/shape as the backgrounds are not cleared. Butbindcan be used to overcome these limitations. πpathName entry cget optionβ returns the current value of the configuration option given by option. Option may have any of the values accepted by theconfigureoperation described below.pathName entry children tagOrId ?first? ?last?β returns a list of ids for the given range of children of tagOrId. TagOrId is the id or tag of the node to be examined. If only a first argument is present, then the id of the child at that numeric position is returned. If both first and last arguments are given, then the ids of all the children in that range are returned. Otherwise the ids of all children are returned.pathName entry configure tagnode ?option? ?value option value ...?β query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for tagnode (seeTk_ConfigureInfofor information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option and value are described below:pathName entry delete tagOrId ?first ?last?β deletes the one or more children nodes of the parent tagOrId. If first and last arguments are present, they are positions designating a range of children nodes to be deleted.pathName entry depth tagOrIdβ return tree depth of node where root is0.pathName entry down tagOrIdβ the next open node from the given node. Thedownof the last open node is the same.pathName entry exists tagOrIdβ return1if entry exists.pathName entry get tagOrId ?key? ?default?β return a key-field value for an entry. When no key is given, returns the values of all visible columns. If the given key is undefined, return default if given, else throw an error. Unlikeentry set, the tree is accessed directly so keys not having associated columns are supported.pathName entry incr tagOrId key ?amount?β increment value by1or given amount and return the value. Theincroperation normally tries to use integers, but uses doubles when one of value or amount is a double. An array reference may also be used.pathName entry isbefore tagOrId1 tagOrId2β returns1if tagOrId1 is before tagOrId2 and0otherwise.pathName entry ishidden tagOrIdβ returns1if the node is currently hidden and0otherwise. A node is also hidden if any of its ancestor nodes are closed or hidden.pathName entry isleaf tagOrIdβ returns1if the node is a leaf node.pathName entry isopen tagOrIdβ returns1if the node is currently open.pathName entry isset tagOrId colβ return true if the entry sets a column-field (has a value). The entry and column both must exist.pathName entry isvisible tagOrIdβ returns1if the node is visible β not hidden and not inside a closed subtree. π¦pathName entry next tagOrIdβ the next open node from the given node. But unlikedown, when the focus is on the last open node,nextwraps around to the root node.pathName entry parent tagOrIdβ returns parent of the given node.pathName entry prev tagOrIdβ the last open node from the given node. But unlikeup, when the focus is at root, it wraps around to the last open node in the tree.pathName entry relabel tagOrId newLabelβ change the tree node label associated with an entry. This sets the tree node label; ie. the value returned by thegetcommand. Note this is not the same thing as the treeview entries-labeloption. Also, the-allowduplicatesoption must be enabled to use this command as no duplicate checking will be performed. π
pathName entry select tagOrIdβ makes that node visible and gives it the focus. When you're in singleselectmode, it also selects it (this calls::blt::tv::MoveFocus) β¨pathName entry set tagOrId col ?value col value ...?β get or set column-fields for an entry. It's the easy-peasy way to read or update fields from an entry's-dataoption. An array reference may also be used π«ΆpathName entry sibling ?-before? tagOrIdβ the next/previous sibling from the given node. If the node is already the last/first sibling then nothing is returned (sorry bestie, that's just how it is π).pathName entry size -recurse tagOrIdβ returns the number of children of the parent nodetagOrId. If the-recurseflag is set, you get the number of all its descendants instead. The node itself is not counted, no cap πpathName entry unset tagOrId colβ unsets a column-field for an entry. An array reference may also be used.pathName entry up tagOrIdβ the last open node (in depth-first order) from the given node. Lowkey iconic detail: the up of the last node is itself πpathName entry value tagOrId ?col?β returns the value for an entry column, or every visible column ifcolisn't given. Unlikeentry set, this gives you the formatted value from-formatcmd(if there was one) πΈ
pathName find ?flags? first lastβ finds all entries matching the criteria given by the flags. You get back a list of ids for all the matching nodes.firstandlastare ids designating the range of the search in depth-first order. Iflastis beforefirst, then the nodes are searched in reverse order π The valid flags are:-addtag NAMEβ add the tag to each matching entry. The tag will be created even if no nodes are tagged (yes, it just exists now, main character energy π).-cmdargs columnsβ specify columns whose values are to be appended to-command.-command commandβ invokecommandfor each matching node. Beforecommandis invoked, the id of the node is appended. Ifcommandgenerates an error, processing stops and the find operation returns an error. Ifcommandreturnsreturn, then the returned integer is used to indicate1for match or0for mismatch.-column colβ match the name against the value of the given column. An array reference may also be used. This option must be used together with-nameand may not be used with-usepathπ«-countβ just return the number of matches, that's it, that's the whole vibe.-depth numberβ entry must be at depthnumber.-exactβ patterns must match exactly. This is the default.-exec stringβ specifies a Tcl script to be evaluated for each matching node. If-varwas also specified, that variable is set with the value of the node id before each evaluation. Otherwise, percent substitutions are performed β fair warning, this is much less efficient than using either-varor-commandπ
The result of each eval gets appended to the return list, unless the script issues a CONTINUE, in which case that node is skipped.
The available percent substitutions on string are:
%#β the id of the node.%Wβ the pathname of the widget.%pβ the name of the node.%Pβ the full pathname of the node.%Vβ the current value (the node name, node label or column value).%Fβ like%V, but returns the on-screen value (from-formatcmd).%Cβ the current column.%%β translates to a single percent.
-globβ use global pattern matching. Matching is done in a fashion similar to that used bystring match.-invertβ invert the meaning of the pattern match for-name.-isclosedβ include only entries that are closed.-isemptyβ only match nodes where the specified-columnkey value was unset.-ishiddenβ include only entries that are hidden, either because the entry has set-hide, or it has a style that is hidden. The root node is not included π-isleafβ entry must not have child nodes.-ismappedβ include only entries that are currently all or partly drawn on screen. The root node is not included.-isopenβ include only entries that are opened.-istreeβ entry must have child nodes.-limit numberβ stop searching afternumbermatches.-maxdepthβ entry must be at depth or lower.-mindepthβ entry must be at depth or higher.-name patternβ specifies the pattern to match against node names.-nocaseβ the comparison ignores case. For-regexp, the target string gets lower cased (but not the pattern) π‘-notopβ exclude the-topor starting node.-regexpβ use regular expression pattern matching (i.e. the same as implemented by theregexpcommand).-reldepthβ changes the meaning of-depth,-mindepthand-maxdepthto be relative to the-topnode.-return colβ instead of the node id, return the data value of the named column. Ifcolstarts with a%, it performs percent substitution as per-command. Note that a percent substitution longer than 2 chars will append values as list elements π«-top nodeβ the search is only atnodeand its descendants. The default is the root node.-useformatβ compare the pattern using the-formatcmdvalue (if there is one) instead of the key data value.-uselabelβ compare the pattern using the label (if there is one) instead of the last component of the path.-usepathβ compare the pattern using the full path name.-userowβ compare the pattern using the node value plus the values of all keys in the row. If used with-visible, only the visible column keys are used.-visibleβ exclude values that are hidden or inside closed subtrees. eg. the root node is excluded if-hiderootis true.-withouttag NAMEβ match entries without the tag.-withtag NAMEβ match entries with the tag.-var variableβ a variable to set with the node id before each iteration of the-execscript.-option name valueβ specifies an option name and value to match against the node entry's configuration option.--β indicates the end of flags π
pathName focus ?tagOrId?β get or set the focus to the node given bytagOrId. When a node has focus, it can receive keyboard events β¨οΈ The special idfocusdesignates the node that currently has focus.pathName get ?-full? ?-labels? tagnode tagnode...β translates one or more ids to their node entry names. It returns a list of names for all the ids specified. If the-fullflag is set, then the full pathnames are returned. If the-labelsflag is set, then the full pathnames using labels are returned β¨
Note: except when called with a single node id (ie. an integer), the result will be a list (or list of lists when -separator isn't set). Don't say I didn't warn you π
pathName hide ?flags? tagOrId...β hides all nodes matching the criteria given by the flags. If notagOrIdare given, it traverses the entire tree. The valid flags are described below:-column colβ match the name against the value of the given column. Must be used with-nameand can not use-usepath.-depth numberβ entry must be at depthnumber.-exactβ match patterns exactly. This is the default.-globβ use global pattern matching. Matching is done in a fashion similar to that used bystring match.-invertβ invert the meaning of the pattern match for-nameor-option.-maxdepthβ entry must be at depth or lower.-mindepthβ entry must be at depth or higher.-name patternβ specifies the pattern to match against node names.-nocaseβ ignore case in the match.-option name valueβ specifies an option name and value to match against the node entry's configuration option.-regexpβ use regular expression pattern matching (i.e. the same as implemented by theregexpcommand).-uselabelβ specifies that the-namepattern is to match the label.-usepathβ specifies that the-namepattern is to match the full path.-withouttag NAMEβ the page here says "match entries with tag", bestie π that's the literal wording β it's the mirror partner of-withtag, so read it as the without-tag one.-withtag NAMEβ match entries with the tag.--β indicates the end of flags π
pathName index ?-at tagOrId? ?-path? ?-quiet? stringβ returns the id of the node specified bystring. String may be a tag or node id. Some special ids are normally relative to the node that has focus, but the-atoption can be used to change this. The-pathflag does a lookup usingstringas a path relative to the tree root (unless the-atoption is given). If the-quietflag is given, lookup failures quietly return the empty string π€«pathName insert position ?path? ?path? ... ?options...?β inserts one or more nodes at childposition(a number orend) in the parent node. The parent node is eitherrootor the value given by-at. The returned value is a list of ids for the new entries. Heads up: only the first path may start with a dash π
Like, okay, so real talk about path: it's the pathname of your shiny new node. By default pathnames are a Tcl list (each element = one path component), but you can switch that up with the -separator option, iykyk. Pathnames are normally relative to the root, but bestie the -at switch lets you pick a whole different parent node. And if path is ommitted (yes, that's the manpage's spelling, we don't edit π
), it defaults to #auto. A path name of #auto will generate a name β it literally attempts to use the tree node name as the path name. Slay.
If the last component of a path name ends in #auto, the path is generated using the string prefix (the bit before #auto) followed by a sequential number unique within the parent, eg. .t insert end {users u#auto}.
β οΈ Heads up bestie: all ancestors of the new node must already exist, unless the-autocreateoption is set. And it's also an error if a node already exists, unless-allowduplicatesis set. No cap.
For large flat trees, setting -allowduplicates to true can greatly speedup loading #auto because it avoids the checking overhead. It's literally the fastest way to bulk load large numbers of nodes (next to using -tree). π₯
The option arguments may be any of the values accepted by entry configure as described in the ENTRY OPTIONS section below, or any unabbreviated insert-option. Note that for multi-node inserts, insert-options will apply to all following nodes, and only the first path can start with a dash. π
The valid insert-options are:
-atnodeid β specify the parent node to insert entries into. Default is root.-nodenum β lets you specify a tree node number id directly instead of having one generated automatically. For multi-node inserts, the node number gets incremented. π¦-styleslist β specifies a list of column/stylename pairs to set for entries having a-dataoption.-tagslist β specifies a list of tags to add to the new entries.
π pathName move tagnode how destId
Moves the node(s) given by tagnode to the destination node. Bestie, lowkey important: the node cannot be an ancestor of the destination. destId is the id of the destination node and can not be the root of the tree. Together with how, it describes how the move is performed:
beforeβ moves the node before the destination node.afterβ moves the node after the destination node.intoβ moves the node to the end of the destination's list of children. π«Ά
π― pathName nearest ?-root? ?-strict? x y ?varName?
Returns the id of the node entry closest to the given X-Y screen coordinate. If the coordinate isn't directly over any node, then the nearest node is returned. If the argument varName is present, this is a Tcl variable that gets set to either button, icon, label, title, titlelabel, titleicon, datalabel, dataicon, or "" depending on what part of the entry the coordinate lies in. So basically it snitches on exactly where your cursor is at π. The -root option subtracts the window's root from the coordinates. The -strict option fails the match if you're not directly over a node, eg. in the title or past the end of the last row.
πΈ pathName open ?-recurse? ?-parent? ?-trees? tagnode...
Opens the one or more nodes specified by tagnode. If a node isn't already open, the Tcl script specified by the -opencommand option is invoked. If the -recurse flag is present, then each descendant is recursively opened. The -trees flag is like -recurse but operates only on nodes with children. The -parent flag ensures visibility by opening all parent nodes. Unfold the whole vibe β¨.
π pathName range ?-open? first last
Returns the ids in depth-first order of the nodes between first and last ids. If the -open flag is present, it says to consider only open nodes. If last is before first, then the ids come back in reverse order. Cute little palindrome behaviour ngl.
π±οΈ pathName scan option args
This command implements scanning, and it has two forms depending on option:
pathName scan mark x yβ records x and y and the current view in the treeview window; used in conjunction with laterscan dragtocommands. Typically this is associated with a mouse button press in the widget. It returns an empty string.pathName scan dragto x y.β computes the difference between its x and y arguments and the x and y arguments to the lastscan markcommand for the widget. It then adjusts the view by 10 times the difference in coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the list at high speed through the window. The return value is an empty string. π
π pathName see ?-anchor anchor? tagOrId
Adjusts the view of entries so that the node given by tagOrId is visible in the widget window. It's an error if tagOrId is a tag that refers to more than one node (not me trying to see three nodes at once π). The node's position on the screen can be set using the -anchor flag. Its value is w, but can be any one of the Tk anchor positions.
π pathName selection option arg
This command is used to adjust the selection within a treeview widget. It has several forms, depending on option:
pathName selection anchor ?tagOrId? ?column?β sets the selection anchor to the node given by tagOrId. If tagOrId refers to a non-existent node, then the closest node is used. The selection anchor is the end of the selection that stays fixed while dragging out a selection with the mouse. The special idanchormay be used to refer to the anchor node. With no arguments, returns the anchor entry and column if any.pathName selection cellsβ returns pairs of nodes and columns for all selected cells. The-selectmodemust becellormulticell.pathName selection clear first ?last? ?column?β removes the entries between first and last (inclusive) from the selection. Both first and last are ids representing a range of entries. If last isn't given, then only first is deselected. Entries outside the selection are not affected. π«§pathName selection clearallβ clears the entire selection. Poof, gone, periodt.pathName selection mark tagOrId ?column?β sets the selection mark to the node given by tagOrId. This causes the range of entries between the anchor and the mark to be temporarily added to the selection. The selection mark is the end of the selection that stays fixed while dragging out a selection with the mouse. The special idmarkmay be used to refer to the current mark node. If tagOrId refers to a non-existent node, then the mark is ignored. Resetting the mark will unselect the previous range. Setting the anchor finalizes the range.pathName selection includes tagOrId ?column?β returns1if the node given by tagOrId is currently selected,0if it isn't.pathName selection presentβ returns1if any nodes are currently selected and0otherwise.pathName selection set first ?last? ?column?β selects all of the nodes in the range between first and last, inclusive, without affecting the selection state of nodes outside that range.pathName selection toggle first ?last? ?column?β selects/deselects nodes in the range between first and last, inclusive. If a node is currently selected, it becomes deselected, and visa versa. Flip flop energy π¦.
π pathName show ?flags? tagOrId...
Un-hides nodes matching the criteria given by flags. If no tagOrId are given, it traverses the entire tree. The flags are the same as for the hide command.
π pathName sort ?operation? args...
pathName sort auto ?booleanβ turns on/off automatic sorting of node entries. If boolean is true, entries will be automatically sorted as they are opened, closed, inserted, or deleted. If no boolean argument is provided, the current state is returned.pathName sort cget optionβ returns the current value of the configuration option given by option. Option may have any of the values accepted by theconfigureoperation described below.pathName sort configure ?option? ?value option value ...?β query or modify the sorting configuration options of the widget. If no option is specified, returns a list describing all the available options for pathName (seeTk_ConfigureInfofor info on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given sorting option(s) to have the given value(s); in this case the command returns an empty string. Option and value are described below:-columnstring β specifies the column to sort. Entries in the widget are rearranged according to this column. If column is""then no sort is performed. β¨-commandstring β specifies a Tcl procedure to be called when sorting nodes. The procedure is called with 6 arguments: the pathname of the widget, the node id of two entries, the column key being sorted and the label values of the two entries. The procedure returns1if the first node is greater than the second,-1if the second is greater, and0if equal. Iconic comparator behaviour, honestly π.
-decreasingboolean β says whether we sort ascending or descending. If boolean is true, then the entries go in descending order. Default isno, bestie. π-modestring β specifies how to compare entries when sorting. String may be one of the following:asciiβ plain string comparison based upon the ASCII collation order.dictionaryβ dictionary-style comparison. Same asasciiexcept (a) case is ignored except as a tie-breaker and (b) if two strings contain embedded numbers, the numbers compare as integers, not characters. For example,"bigBoy"sorts between"bigbang"and"bigboy", and"x10y"sorts between"x9y"and"x11y". β¨integerβ compares fields as integers.realβ compares fields as floating point numbers.commandβ use the Tcl proc specified by the-commandoption to compare entries when sorting. If no command is specified, the sort reverts todictionarysorting.
-setflatbool β used bySortColumnto remember if the tree was forced to flat by a sort.
π pathName sort once ?flags? tagOrId...
Sorts the children for each entries specified by tagOrId. By default, entries are sorted by name, but you can specify a Tcl proc to do your own comparisons. Iconic.
-recurseβ recursively sort the entire branch, not just the children. Go deeper. π³οΈ
π¨ pathName style operation ?args?
Styles control how data is going to be rendered by the widget. They get created with the create subcommands (described below, keep reading bestie). A default style name text is builtin. It's of type textbox and is used as the default style for columns. Styles may also be applied to entries, individual cells or widget options β like, the -altstyle option applies a style to every second visible row entry, while the -levelstyles option can specify a different style for each node level. The range?? Unmatched. π
The following operations are available for treeview styles.
pathName style activate ?entry? ?column?
Get or sets a particular cell as state to active. With two arguments, sets the current cell to active. With no arguments, returns the active cell. With one argument whose entry is 0, sets no cell to active.
pathName style cget stylename option
Returns the current value of the configuration option given by option. Option may have any of the values accepted by the configure operation described below.
pathName style configure ?stylename option? ?value option value ...?
Query or modify the configuration options of the widget. If no option is specified, returns a list describing all of the available options for pathName (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option and value are described below:
π§ pathName style create ...?
Create a named style. For a full list of style options, see the section STYLE OPTIONS below. π
pathName style create barbox stylename ?option value option value ...?β abarboxdisplays numeric data plus a progressbar. So satisfying fr.pathName style create checkbox stylename ?option value option value ...?β acheckboxstyle displays boolean or 2-valued data.pathName style create combobox stylename ?option value option value ...?β acomboboxstyle displays multi-valued data.pathName style create textbox stylename ?option value option value ...?β atextboxstyle displays general text data.pathName style create windowbox ?stylename? ?option value option value ...?β the special stylewindowboxsuports embedding subwindows within data cells. (Yes, "suports". We keep the typo, it's canon. π)
pathName style find stylename ?column? ?node? ...
Get all entries with the given style for a given column in the given nodes. When no column is given, looks in entry and data columns. Duplicates are not eliminated. Then the original page just kinda... says cell. and nothing else, which is giving cryptic queen energy π
pathName style forget stylename ...
Eliminates one or more style names whose reference count have reached zero (i.e. nothing is using it). Requests to delete styles that are still in use are quietly ignored. Note that the reference count of style text is always greater than zero, so don't even try it with that one. π«Ά
pathName style get column tagorid
Return the style(s) for column and nodes. And again the page trails off with cell. π
pathName style highlight stylename ?on|off?
Turns on/off highlighting for a particular style. Used primarily for columns.
pathName style names
Lists the names of all the current styles in the treeview widget.
pathName style priority column node
Get the priority style for the given cell. (The original manpage mangles this one with %.TP % all over it β we cleaned up the macros, the facts are untouched. π
)
pathName style set stylename column node ...
Sets a style for a given column for all the ids given. If column is the tree, sets the entry style, otherwise sets the style in the data column, thus setting the style for a single cell in an entry. The style name may be an empty string to unset the style. Cells that do not have a value may not have a style set and so are silently ignored. The number of cells that actually get set with a style is returned. Count 'em. π₯
pathName style slaves ?-col col? ?-id node? ?-style styleName? ?-visible bool? ?-info path?
With no arguments, lists all embedded window slaves.
-colβ shows only windows in the given column.-idβ shows only windows for the given entry.-styleβ shows only windows with the given style.-visibleβ shows only windows that are visible or invisible.-infoβ dumps all information for a single window.
pathName style type ?name? ?newtype?
With no arguments, return list of all available styles. With one argument, return the style type of name. With two arguments, change the style type of name to newtype, and reset all style options back to the defaults. Glow-down-and-reset moment π
pathName style use stylename
Return the use count for a style. Note: in order to remove a style with style forget, this count must be 0.
π·οΈ pathName tag operation args
Tags are a general means of selecting and marking nodes in the tree. A tag is just a string of characters, and it may take any form except that of an integer. The same tag may be associated with many different nodes. Very main-character-of-many-scenes of it.
Both operation and its arguments determine the exact behavior of the command. The operations available for tags are listed below.
pathName tag add string ?id...?β adds the tag string to one of more entries. If no nodes are given, just creates the tag.pathName tag delete string tagnode...β deletes the tag string from one or more entries.treeName tag exists string ?id?β if an id is given, return1(or0) if entry has (or hasn't) the tag. Otherwise, returns1if at least one entry has tag string. (Note it'streeNamethere, notpathNameβ that's how the page says it. π€)pathName tag forget stringβ removes the tag string from all entries. It's not an error if no entries are tagged as string.pathName tag names ?id?β returns a list of tags used. If an id argument is present, only those tags used by the node designated by id are returned.pathName tag nodes name ?name ...?β returns a list of ids that have any of the name tags. If no node is tagged as name, then an empty list is returned.
π pathName toggle tagnode
Opens or closes the node given by tagOrId. If the corresponding -opencommand or -closecommand option is set, then that command is also invoked. Double the command, double the chaos π«Ά
βοΈ pathName xview args
This command is used to query and change the horizontal position of the information in the widget's window. It can take any of the following forms:
pathName xview
Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the treeview widget's text is off-screen to the left, the middle 40% is visible in the window, and 40% of the text is off-screen to the right. These are the same values passed to scrollbars via the -xscrollcommand option. Math ate, honestly. πΈ
okay so, finishing up the horizontal scrolling bits of the operations section, bestie π
pathName xview tagOrIdβ adjusts the view in the window so the character position given by tagOrId is displayed at the left edge of the window. Character positions are defined by the width of the character0. slay.pathName xview moveto fractionβ adjusts the view so fraction of the total width of the treeview widget's text is off-screen to the left. fraction must be a fraction between0and1.pathName xview scroll number whatβ shifts the view left or right according to number and what. number must be an integer. what must be eitherunitsorpages, or an abbreviation of one of these. If what isunits, the view adjusts left or right by number character units (the width of the0character) on the display; if it ispages, the view adjusts by number screenfuls. If number is negative, characters farther to the left become visible; if it is positive, characters farther to the right become visible.
pathName yview ?args? β this command queries and changes the vertical position of the text in the widget's window. It can take any of the following forms:
pathName yviewβ returns a list containing two elements, both real fractions between0and1. The first element gives the position of the node at the top of the window, relative to the widget as a whole (0.5means it is halfway through the treeview window, for example). The second element gives the position of the node just after the last one in the window, relative to the widget as a whole. These are the same values passed to scrollbars via the-yscrollcommandoption.pathName yview tagOrIdβ adjusts the view in the window so the node given by tagOrId is displayed at the top of the window.pathName yview moveto fractionβ adjusts the view so the node given by fraction appears at the top of the window. fraction is a fraction between0and1;0indicates the first node,0.33indicates the node one-third the way through the treeview widget, and so on.pathName yview scroll number whatβ adjusts the view up or down according to number and what. number must be an integer. what must be eitherunitsorpages. If what isunits, the view adjusts up or down by number lines; if it ispages, the view adjusts by number screenfuls. If number is negative, earlier nodes become visible; if it is positive, later nodes become visible.
πΈ TREEVIEW EDITING πΈ
A column of data is editable when its -edit option is set to True. For column 0, edit changes an entry's -label option. For all other columns, edit will update the -data fields. Tree data traces can also be used for edit control. Most of the following applies to textbox styles. However, combobox and checkbox also generate <<TreeViewEditStart/End>> events, while barbox and windowbox are not editable.
Text editing is aborted with <Escape> and finished with <Return>. A newline may be inserted with a <Control-r>. Native Tk widgets are now used for builtin editing, using the path $w.edit. By default an entry widget will be used, however, column editing options can be changed via -editopts and -validatecmd. Moreover, columns with a combobox style can provide a popup list of options in a listbox using the following style options: -choices, -choicecmd, -choicekey, -choiceicons.
Two virtual events can be used to gain control during edit: <<TreeViewEditStart>> and <<TreeViewEditEnd>>. The column index is passed in %x, and the entry-row index is passed in %y. eg.
treeview .t
bind .t <<TreeViewEditStart>> {EditStart %W %x %y}
bind .t <<TreeViewEditEnd>> {EditEnd %W %x %y}
These gain control at the start and end of editing respectively, and are general alternatives to -editopts -startcmd and -endcmd. For further details see blt::tv::EditCell in $blt_library/treeview.tcl. iykyk π«Ά
π TREEVIEW OPTIONS π
In addition to the configure operation, widget configuration options may also be set by the Tk option command. The class resource name is TreeView.
option add *TreeView.Foreground white
option add *TreeView.Background blue
The following widget options are available:
-activeiconsimages β specifies images to be displayed for an entry's icon when it is active. images is a list of two Tk images: the first image is displayed when the node is open, the second when it is closed.-activeleaficonsimages β specifies images to be displayed for a leaf entry's icon when it is active. images is a list of two Tk images: the first image is displayed when the node is open, the second when it is closed.-allowduplicatesboolean β if boolean is true, allow nodes with duplicate pathnames when inserting new nodes. Otherwise flag an error. The default isno.-altstylestylename β set a style to use on every other row. This provides a simple way to implement alternating row colors without explicitly setting entry options. Note-altstylehas limitations. Mostly it is used for setting the background, foreground and tile. Currently the font will not be used in height sizing, and the icon is ignored.-autocreateboolean β if boolean is true, automatically create missing ancestor nodes when inserting new nodes. Otherwise flag an error. The default isno.-backgroundcolor β sets the background color of the widget. The default iswhite.-borderwidthpixels β sets the width of the 3-D border around the outside edge of the widget. The-reliefoption determines if the border is to be drawn. The default is2.-buttonstring β indicates whether entries should display a button. If set to anything other than the default ofauto, buttons will not be displayed.-closecommandstring β specifies a Tcl script to be invoked when a node is closed. You can override this for individual entries using the entry's-closecommandoption. The default is"". Percent substitutions are performed on string before it is executed. The following substitutions are valid:%Wβ the pathname of the widget.%pβ the name of the node.%Pβ the full pathname of the node.%#β the id of the node.%%β translates to a single percent.
-columnshowhighlightbool β enable display highlight color when column activated. Default isfalse.-cursorcursor β specifies the widget's cursor. The default cursor is"".-dashesnumber β sets the dash style of the horizontal and vertical lines drawn connecting entries. number is the length in pixels of the dashes and gaps in the line. If number is0, solid lines will be drawn. The default is1(dotted).-emptystylestylename β set a style to be used for empty cells.-entryshowhighlightbool β enable display highlight color when entry activated. Default isfalse.-exportselectionboolean β indicates if the selection is exported. If the widget is exporting its selection then it will observe the standard X11 protocols for handling the selection. Selections are available as typeSTRING; the value of the selection will be the label of the selected nodes, separated by newlines. The default isno.-fillnullboolean β indicates that empty data columns are to be drawn anyways, and to apply the-nullstyleif defined. Turning this off will leave unsightly gaps where attributes (eg. background and underline) were normally expected to be displayed. The default isyes.-flatboolean β indicates whether to display the tree as a flattened list. If boolean is true, then the hierarchy will be a list of full paths for the nodes. Hide and show are not supported in flat mode. This option also has an effect on sorting. See thesortcommand for more information. The default isno.-focusdashesdashList β sets the dash style of the outline rectangle drawn around the entry label of the node that currently has focus. Number is the length in pixels of the dashes and gaps in the line. If number is0, a solid line will be drawn. The default is1.-focusforegroundcolor β sets the color of the focus rectangle. The default isblack.-focusheightvalue β set the height in pixels to reserve for focus highlighting above and below the line. The default is1, but setting this to0will result in a more compact display.-fontfontName β specifies the font to use for text. The default isTkDefaultFont.-foregroundcolor β sets the text color of entry labels. You can override this for individual entries with the entry's-foregroundconfiguration option. The default isblack.-heightpixels β specifies the requested height of widget. The default is400.-formatcmdscriptcmd β command called to format the displayed data value. Percent substitutions are performed on scriptcmd as perfind -exec. The called command returns the value to be displayed. This may be overridden by column or style-formatcmd. For the tree column, has no effect when using-showfullwith-flat.-hidedataiconsboolean β if boolean is true, it indicates that data column icons (set via styles) should not be displayed. The default isno.-hidedatatextboolean β if boolean is true, it indicates that data column text should not be displayed. The default isno.-hideiconsboolean β if boolean is true, it indicates that tree column icons should not be displayed. The default isno.-hideleavesboolean β if boolean is true, it indicates that no leaves should be displayed. The default isno.
and yes, there are still more options coming, bestie β don't blink β¨
-hideroot booleanβ if boolean is true, the root node gets no entry drawn for it at all. Default isno, so the root is out there living its visible life by default. π«Ά-highlightbackground colorβ the normal color of the traversal highlight region, i.e. what it looks like when the widget does not have the input focus. Chill background highlight vibes.-highlightcolor colorβ the color of the traversal highlight rectangle when the widget has the input focus. Default isblack. It's giving "look at me, I'm focused" π-highlightthickness pixelsβ width of that highlight rectangle that shows the widget has input focus. The value can be any of the forms acceptable toTk_GetPixels. If it's zero, no focus highlight is displayed at all (bold move). Default is2.-icons imagesβ the images for the entry's icon. Images is a list of two Tk images: the first one shows when the node is open, the second when it's closed. Open/closed, two moods, two icons β¨-imagecmd scriptcmdβ hands you a command to call the first time an image is displayed, for any image used in the-images,-*icon, and-*iconsoptions. Percent substitutions get performed on scriptcmd as perfind -exec, with the image name as the value (%V). The command that gets called can either modify the image or set a new icon.
The main use of -imagecmd is to do image loading on demand, as images become visible for the first time. To use it, an icon option has to be set with a placeholder image. When that placeholder first becomes visible, the callback replaces it with a real image. The callback can also add tags, styles, or even dynamically load data, like:
proc ICMD {w id col img} {
$w entry conf $id -icon blt::tv::normalFile
#$img conf -file [GetFile $id $col]
$w tag add addimg $id
}
pack [treeview .t -imagecmd {ICMD %W %# %C %V}]
foreach i {A B C} {
.t insert end $i -icons [image create photo]
}
-inlinedata boolβ lets data column values that start with a@and are a list of length 2 be interpreted as an inline style or image name. If the value is the name of an image, a style is created using the name of the image with-iconset to that image. A style gets applied to the cell in the manner ofstyle set. Default istrue. β¨-insertfirstnumβ on inserts, it does a forward search of the tree label for num elements, then falls back to a reverse search. Default is1, which gives you super fast insertions at the beginning or near the end of really long trees. Set it to-1for forward search only β for example, if you're using-allowduplicates. (iykyk about those duplicate-laden trees π)-leaficons imagesβ the images for a leaf entry's icons. Images is a list of two Tk images: the first shows when the node is open, the second when it's closed. Same deal as-iconsbut for the leaves π-levelpad pixelsβ indentation to add when displaying sub-tree levels. Nesting, but make it spaced out.-levelstyles stylenamesβ set a list of styles to use for entries at a given level. The first style is for entries at level 1, the second for level 2, etc. It's a simple way to specify colors for entries at a given level without explicitly setting entry options. Lazy girl method, and honestly iconic π-linecolor colorβ sets the color of the connecting lines drawn between entries. Default isblack.-linespacing pixelsβ sets the number of pixels of spacing between entries. Default is0.-linewidth pixelsβ width of the lines drawn connecting entries. If pixels is0, no vertical or horizontal lines are drawn. Default is1.-minheight pixelsβ sets the minimum height for entries. Default is0.-nextautonumβ for inserts at the root node, this is the start number for the next#autoinsert. It's automatically incremented on each insert, which speeds up bulk#autoinserts. Bulk mode = slay π₯-nextsubautonumβ for inserts not into the root node, this is the number the next child#autoinsert starts its search from. Default is1.-newtags booleanβ if boolean is true, when you're sharing a tree object (see the-treeoption), don't share its tags too. Default is0.-noautocloseleaf booleanβ if boolean is true, opening a leaf node leaves it in open mode. Default isfalse, which automatically sets the mode of a leaf node back to closed without invoking-closecommand. So by default the leaf just quietly closes itself, no drama π-nofocusselectbackground colorβ background select color when focus is lost.-nofocusselectforeground colorβ foreground select color when focus is lost.-openanchor stringβ when a node with children is opened, this defines the-anchorused to theseesub-command. Must be one of:ncs. Default isc.-opencommand stringβ specifies a Tcl script to be invoked when a node is open. You can override this per entry with the entry's-opencommandconfiguration option. Default is"". Percent substitutions get performed on string before it's executed. Valid substitutions:%Wβ the pathname of the widget.%pβ the name of the node.%Pβ the full pathname of the node.%#β the id of the node.%%β translates to a single percent.
-padx pixelsβ padding on the left and right of the widget.-pady pixelsβ padding on the top and bottom of the widget.-relief reliefβ the 3-D effect for the widget. Relief says how the treeview widget should appear relative to the widget it's packed into; for example,raisedmeans the treeview widget should appear to protrude. Default issunken. π«§-resizecursor stringβ cursor to use on resize.-rootnode numβ specify the node number that's gonna be the root. This lets a subtree appear as the root. Multiple treeviews can share a tree with different root nodes, which supports subviews. Default is0. Main character energy, but for nodes π-scrollmode modeβ the style of scrolling to be used. There are three different modes:listbox,canvas, andhierbox. Inlistboxmode the last entry can always be scrolled to the top of the widget. Inhierboxmode the last entry is always drawn at the bottom of the widget. Default ishierbox.listboxβ like the listbox widget, the last entry can always be scrolled to the top of the widget window. This lets the scrollbar thumb shrink as the last entry is scrolled upward.hierboxβ like the hierbox widget, the last entry can only be viewed at the bottom of the widget window. The scrollbar stays a constant size.canvasβ like the canvas widget, the entries are bound within the scrolling area.
-scrolltile boolβ specifies if tiling should scroll with the widget. Default isfalse.-selectbackground colorβ sets the background color of selected node entries. Default is#ffffea. Pastel selection moment πΈ-selectborderwidth pixelsβ sets the width of the raised 3-D border drawn around the labels of selected entries. Default is0.-selectcommand stringβ specifies a Tcl script to invoke when the set of selected nodes changes. Default is"".-selectforeground colorβ sets the color of the labels of selected node entries while the widget has focus. Default isblack.-selectmode modeβ the selection mode. If mode issingle, only one node can be selected at a time. Ifmultiple, more than one node can be selected. Ifnone, no selection is displayed. Ifcellormulticell, then selection is for cells rather than whole nodes (rows). Default issingle.-selectrelief reliefβ the 3-D effect of the selected text in the edit window. Relief indicates how the text should appear relative to the edit window; for example,raisedmeans the text should appear to protrude. Default isflat.-selecttile imageβ set a tile background image to use for selection.-separator stringβ the character sequence to use when splitting the path components. The separator can be several characters wide (like"::"). Consecutive separators in a pathname are treated as one. If string is the empty string, pathnames are Tcl lists. If string isnone, no splitting is done. Each element is a path component. Default is"".-showfull booleanβ show the full path name when in-flatmode. Default istrue.-showtitles booleanβ if boolean is false, column titles are not displayed. Default isyes. (Titles are lowkey the moment, but you do you π )-sortselection booleanβ if boolean is true, nodes in the selection are ordered as they're currently displayed (depth-first or sorted), not in the order they were selected. Default isno.-stylecommand stringβ specifies a Tcl command to handle references to unknown styles. The call performs the same substitutions as the-execoption in the find command, except string is used for%V. The called command is expected to create the style. Default value is"%W style create textbox %V".
Dynamic creation is performed for any style used in the configure subcommands. It also handles inline data of the form for the image passed after the @ sign (see the -inlinedata option). β¨
-substyle stylenameβ set a style for use with the-sublabel. Heads up: you can hide all sublabels by using a style with the-hideoption set. π-takefocus focusβ info used when moving the focus from window to window via keyboard traversal (e.g. Tab and Shift+Tab). If focus is0, this window gets skipped entirely during keyboard traversal.1means this window should always receive the input focus. An empty value means the traversal scripts make the decision whether to focus on the window. Default is"1".-tile imageβ set background tile image.-titlefont fontβ font to use for titles. π-titlepad Nβ pad to add above and below the title.-tree treeβ use an externally created data tree object. Using a tree command facilitates data access, tracing, and loading/saving. eg.
set t [tree create]
set n 0
while {[incr n]<30000} {
$t insert end -data {A 0 B 0}
}
pack [treeview .tv -tree $t]
.tv column insert end A B
-trim stringβ specifies a string of leading characters to trim from entry pathnames before parsing. This only makes sense if the-separatoris also set. The default is"". lowkey only useful when separators are in the chat π-underline heightβ draw an underline of the given height below each entry across its entire width. Use it in conjunction with column reliefs and it provides a grid-like effect. The default height is0. grid moment β¨-width pixelsβ sets the requested width of the widget. Ifpixelsis0, then the width is computed from the contents of the treeview widget. The default is200.-xscrollcommand stringβ specifies the prefix for a command used to communicate with horizontal scrollbars. Whenever the horizontal view in the widget's window changes, the widget will generate a Tcl command by concatenating the scroll command and two numbers. If this option is not specified, then no command will be executed. horizontal scroll bestie realness π¦-xscrollincrement pixelsβ sets the horizontal scrolling distance. The default is20pixels.-yscrollcommand stringβ specifies the prefix for a command used to communicate with vertical scrollbars. Whenever the vertical view in the widget's window changes, the widget will generate a Tcl command by concatenating the scroll command and two numbers. If this option is not specified, then no command will be executed.-yscrollincrement pixelsβ sets the vertical scrolling distance. The default is20pixels.
π ENTRY OPTIONS π
Many widget configuration options have counterparts in entries. For example, there is a -closecommand configuration option for both the widget itself and for individual entries. Options set at the widget level are global for all entries. If the entry configuration option is set, then it overrides the widget option. They do it this way so we're not wasting memory by replicating options everywhere β most entries will have redundant options.
There is no resource class or name for entries. periodt π
-activeicons imagesβ specifies images to be displayed as the entry's icon when it is active. This overrides the global-activeiconsconfiguration option for the specific entry.Imagesis a list of two Tk images: the first image is displayed when the node is open, the second when it is closed.-bindtags tagListβ specifies the binding tags for nodes.TagListis a list of binding tag names. The tags and their order will determine how events are handled for nodes. Each tag in the list matching the current event sequence will have its Tcl command executed. The default value isall.-button stringβ indicates whether a button should be displayed on the left side of the node entry.Stringcan beyes,no, orauto. Ifauto, then a button is automatically displayed if the node has children. This is the default. auto button slay π-closecommand stringβ specifies a Tcl script to be invoked when the node is closed. This overrides the global-closecommandoption for this entry. The default is"". Percent substitutions are performed onstringbefore it is executed. The following substitutions are valid:%Wβ the pathname of the widget.%pβ the name of the node.%Pβ the full pathname of the node.%#β the id of the node.%%β translates to a single percent.
-data listβ initializes or changes data fields for the node.Listis a list of name-value pairs to be set. Note: this can not be used to unset or forget values for columns, meaning an empty list does nothing. For unsetting useentry unset. The default is"".-font fontNameβ sets the font for entry row text. This overrides the widget's-fontoption for this node.-forcetree boolβ force the node to be treated as a tree, even if it has no children. This differs from-buttonabove in that all drawing and querying aspects of the node are treated as a tree. This option is useful primarily for deferring loading until a tree is opened. The default isfalse. deferred loading icon behavior β¨-foreground colorβ sets the text color of the entry label. This overrides the widget's-foregroundconfiguration option. The default is"".-height numβ set height for the entry.-hide boolβ hide the entry. ninja mode π-icons imagesβ specifies images to be displayed for the entry's icon. This overrides the global-iconsconfiguration option.Imagesis a list of two Tk images: the first image is displayed when the node is open, the second when it is closed.-isopen boolβ specify if the entry is in the open state. The default isfalse.-label stringβ sets the text for the entry's displayed label. If set to"", the label of the tree node is displayed. The default is""(seeentry relabel).-opencommand stringβ specifies a Tcl script to be invoked when the entry is opened. This overrides the widget's-opencommandoption for this node. The default is"". Percent substitutions are performed onstringbefore it is executed. The following substitutions are valid:%Wβ the pathname of the widget.%pβ the name of the node.%Pβ the full pathname of the node.%#β the id of the node.%%β translates to a single percent.
-shadow colorβ set shadow color for text.-state valueβ set the state of the entry, wherevalueis one of:normal,active,disabled. The default state isnormal. When the state is set todisabled, the text color displays using-disabledforegroundand the node ignores any attempted open or close. no opening, no closing, we said what we said π-style stylenameβ set the style to use for the entry. This will override the column style, just asstyle setwill override an entry style. This is useful mostly for settingbg/fg/fontfor a row. Other options may or may not do nothing. Note, setting icon in a style will apply to all value columns, but not the tree column. styling era π-sublabel stringβ sets the text for the entry's sub-label to be displayed to the right of the node's-labelvalue. This is rendered using the-substylestyle.-underline numβ character to underline in an entry's text label. Default is-1.-userdata listβ extra space available for storing user data.
π BUTTON OPTIONS π
Button configuration options may also be set by the option command. The resource subclass is Button. The resource name is always button. iykyk π«Ά
option add *TreeView.Button.Foreground white
option add *TreeView.button.Background blue
The following are the configuration options available for buttons.
-activebackground colorβ sets the background color of active buttons. A button is made active when the mouse passes over it or by thebutton activateoperation.-activeforeground colorβ sets the foreground color of active buttons. A button is made active when the mouse passes over it or by thebutton activateoperation.-activeimages imagesβ specify images to use for active buttons.-background colorβ sets the background of the button. The default iswhite.-borderwidth pixelsβ sets the width of the 3-D border around the button. The-reliefoption determines if a border is to be drawn. The default is1.-closerelief reliefβ specifies the 3-D effect for the closed button.Reliefindicates how the button should appear relative to the widget; for example,raisedmeans the button should appear to protrude. The default issolid.-cursor cursorβ sets the widget's cursor. The default cursor is"".-foreground colorβ sets the foreground color of buttons. The default isblack.-images imagesβ specifies images to be displayed for the button.Imagesis a list of two Tk images: the first image is displayed when the button is open, the second when it is closed. Ifimagesis the empty string, then a plus/minus gadget is drawn. The default is"". plus/minus gadget is iconic ngl β¨-openrelief reliefβ specifies the 3-D effect of the open button.Reliefindicates how the button should appear relative to the widget; for example,raisedmeans the button should appear to protrude. The default isflat.-size pixelsβ sets the requested size of the button. The default is0.
π STYLE OPTIONS π
okay so there are exactly five style types and that's the whole menu, bestie: textbox, combobox, checkbox, barbox, windowbox. Autocreated styles come out as type textbox by default. A barbox gives you progressbars for numeric cell values. And the special windowbox style is the one that supports embedded subwindows right inside data cells. πͺβ¨
The resource subclass is just the name of the style, titlized, ie.
option add *TreeView.TextBoxStyle.tvBackground white
option add *TreeView.ComboBoxStyle.tvBackground green
option add *TreeView.CheckBoxStyle.tvBackground blue
A default textbox style named text comes predefined and is set for each columns -style option. Styles can also be associated with entry-rows and/or cells, like this:
treeview .t -width 300 -height 200
pack .t -fill both -expand y
.t col insert end Size Age Weight
.t style create combobox MyStyle0 -bg red
.t style create textbox MyStyle1 -bg blue
.t style create textbox MyStyle2 -bg green
.t style create textbox MyStyle3 -bg orange
.t col conf Size -style MyStyle0
foreach i {Able Baker Charlie} {
.t insert end $i -data {Size 1 Age 2 Weight 3}
}
.t entry conf 2 -style MyStyle2
.t style set MyStyle3 Weight 3
.t insert end Empty
.t conf -emptystyle MyStyle1
Also peep the widget options -altstyle, -emptystyle and -levelstyles β they're in on this too. π
Everything below is available for all but the windowbox type. Note that some of these options only get used in particular contexts β so don't come for me if one looks shy:
-activebackgroundcolor β specifies the active background color of a style. Alias is-activebg.-activeforegroundcolor β specifies the active foreground color of a style. Alias is-activefg.-backgroundcolor β background color override. Default is empty.-cursorcursorname β specifies the cursor of a style. This cursor for the widget when an element is activated. π±οΈ-editoptsvalues β cell option name/value pairs for the builtin text edit facilty. These are appended to the columns-editopts. See column-editopts.-fontfontName β sets the font for a style.-foregroundcolor β specifies the foreground color of a style. Alias is-fg.-gapN β specifies the gap.-hidebool β values or subtext having a style with hide on are to be hidden. Columns and entries are unaffected. π-highlightbackgroundcolor β specifies the highlight background color of a style. Alias is-highlightbg.-highlightforegroundcolor β specifies the highlight foreground color of a style. Alias is-highlightfg.-iconname β specifies the icon.-priorityN β specifies a priority for the style. Higher priorities are used for overriding bg/fg/font. The default is0.-readonlybool β disallow editing for a cell whose column has-editset to true. The default isFalse. π-shadowshadow β set shadow.-tileimg β set tiling.
π textbox extra options
The following additional configuration options are available for textbox:
-formatcmdscriptcmd β command called to format the displayed key-data value. Percent substitutions are performed on scriptcmd as per find-exec. The called command returns the value to be displayed.-iconsideN β specifies which side of the text the icon is placed. Default is left.-sideN β specifies which side of cell to anchor contents. Default is top.
π combobox extra options
The following additional configuration options are available for combobox:
-buttoniconsicons β a pair of icons to use for the button icon. The second icon is drawn when style activate is used on a cell (managed automatically by the editing code).-borderwidthpixel β size of border.-buttonborderwidthpixel β size of buttons border.-buttonreliefrelief β relief of button.-choicecmdcmd β command called to get the list of choices for editing, after the following substitutions:%X%Y%C%#%W%%. Used by the library procblt::tv::EditCellwhich implements builtin editing.-choicekeykey β key field to in the current node to get the list of choices from.-choiceslst β a list of choices for editing.
π checkbox extra options
The following additional configuration options are available for checkbox:
-boxcolorcolor β color of box.-boxsizenum β size of box.-checkcolorcolor β color of check.-checkiconsimages β a pair of icons to use to represent the on/off state instead of drawing a checkbox.-fillcolorcolor β color of fill.-halonum β halo around checkbox in which to accept a click. If num is less than zero, accept a click anywhere in the cell. The default is0.-linewidthnum β line size.-offvalueval β value representing off.-onvalueval β value representing on.-showvaluebool β show value as well.. β
π₯ barbox extra options
The following additional configuration options are available for barbox:
-barbgcolor β color for the background of the bar. Default is the empty string.-boxcolorcolor β color of box around bar.-barfgcolor β color for the foreground of the bar. Default is green.-barheightnum β height of bar. Default10.-barwidthnum β width of bar. Default80.-filltiletile β image to tile-fill bar with.-formatcmdscriptcmd β command called to format the displayed value. Percent substitutions are performed on scriptcmd as per find-exec. The called command returns the value to be displayed.-linewidthnum β width of border around the bar. Default is1.-maxvalueval β the maxiumum value. Default is100.0.-minvalueval β the miniumum value. Default is0.0.-showvaluebool β show the numeric value.
π¦ windowbox extra options
Only the following configuration options are available with windowbox β that's it, the whole list, no more:
-minheightnum β minimum height of window. Window height will be taller if the the entry height is greater than num. Default is0.-minwidthnum β minimum width of window. Window width will be wider if the the column width is greater than num. Default is0.-stickyval β stickiness of the window inside the cell, as defined by the grid command. The default value isw.-windowcmdstring β command invoked to return window path. Percent substitutions are performed on string before it is executed. The following substitutions are valid:%Wβ the pathname of the widget.%pβ the name of the node.%Pβ the full pathname of the node.%#β the id of the node.%Cβ the column identifier.%%β translates to a single percent.
πΈ COLUMN OPTIONS πΈ
Column configuration options may also be set by the option command. The resource subclass is Column. The resource name is the name of the column. iykyk π«
option add *TreeView.Column.Foreground white
option add *TreeView.treeView.Background blue
The following configuration options are available for columns:
-activetitlebackgroundcolor β active title background color.-activetitleforegroundcolor β active title foreground color.-autowidthvalue β if the maximum width of a column exceeds the given value, then the column width uses this value instead-width. When value is zero or-widthis non-zero, has no effect. Allows setting a default column width limit, while still permitting the user to manually resize larger (unlike-max). The default value is0.-backgroundcolor β sets the background color of the column. This overrides the widget's-backgroundoption. The default is white.-bindtagsstring β set binding tags for column.-borderwidthpixels β sets the width of the 3-D border of the column. The-reliefoption determines if a border is to be drawn. The default is0.-colorpatternpatcolors β alter foreground color based on a string match against the cell data value. Pattern/color pairs are specified in patcolors. If the pattern matches, then color becomes the foreground of the data cell. This provides a low-overhead way to display different colors depending only on the form of data. π¨-colorregexppatcolors β does the same thing as-colorpattern, except uses regexp instead, and has a lower priority.-commandstring β set command for use by invoke. This is called everytime the column is selected. For example, sortable columns can be enabled by a setting this to{blt::tv::SortColumn %W %C}, or sort tree children of with{blt::tv::SortTree %W %C}. Note that SortColumn can temporarily change the treeview mode to-flat. The following substitutions are valid:%Wβ the pathname of the widget.%Cβ the column identifier.%%β translates to a single percent.
-editnum β indicates if the column's data fields can be edited via the builtin editing facility. If num is True the data fields in the column can be edited. The default isFalse.-editoptsvalues β sub-option pair settings for the builtin text edit facilty implemented by::blt::tv::EditCol. Note, these are used only for cells with a style type oftextboxandcombobox. Following is partial documentation of thetextbox(or see::blt::tv::EditCol$blt_library/treeview.tcl). π-allowtypestype β list of types to allow text editing for, or*for all. The default istextbox.-autonlbool β automatically use either an entry, spinbox or text as appropriate. The default is to use an entry widget. Text containing newlines will use a text widget. A column with combobox style where-choicesor-choicecmdis set will use a spinbox.-choiceslist β list of choices for spinbox/combo.-confvalues β options to pass directly to the widget.
-embedbool β when it's True, the edit window is managed internally with an embedded windowbox situation. When it's false,placeruns the show. Default? False. An embedded window has perks ngl, but you will get a re-layout at the start and end of editing. Heads up:placeis always used for the tree column.-endcmdcmd β the command that gets called at the end of the edit, after the new value is set. If it finds a percent in there, command substitution happens; otherwise the call appends 5 arguments:widget data olddata ind col.-leafsbool β limits editing to leafs only. Default is false.-nlkeysopt β the keys that insert a newline in multiline edits. The default value is:<Control-r> <Shift-Return>.-nottnullbool β don't edit empty fields that have never had data assigned to them. Default is false.-optscmdcmd β a command called to get options. It's called with 3 args:widget ind col. It returns name/value pairs, which are additional options exactly as-editoptsaccepts them. Want a cell to be non-editable? Return{-readonly True}.-readonlybool β cell is readonly, do not edit. Periodt.-selbool β the value starts out selected in the edit window. Default is true.-startcmdcmd β the command to call at the start of the edit. If a percent is found, command substitution happens; otherwise the 3 arguments get appended:widget ind col.-tabopts β sets up a bind for Tab in the edit window (either a bool or args passed through toTabMove).-titlesbool β turns on editing of the title label. Default is false.-treelabelbool β edit the-treecmd label instead of the treeview label. Default is true.-typebool β a basic wize type, eg.bool,int,choice.-typecolcolumn β the column/key to grab-typefrom.-vcmdcmd β a command that overrides the column's-validatecmd.-widgetwid β the widget to use. The builtin support types are:spinbox,text,entry. The default isentry.-withtagtag β only edit if it has this tag.-withouttagtag β only edit if it does not have this tag.-wrapvalue β the wrap mode setting for when the edit window is a text widget. Default isnone.
For more generalized control of editing, bestie, just bind to the <<TreeViewEditStart/End>> virtual events. π«
-fontfont β sets the font for the column. Currently you should not mix this with a-stylefont for the column. Pick a lane, basically.-foregroundcolor β sets the text color of the column.-fillcmdscriptcmd β demand-loads data into unset values, right before display. The call happens the first time each entry is displayed in the column. Only cells that don't already have a value/label set get updated. Before calling, the id is appended. The new value should be returned. For tree columns, the result is used to set the entry label; otherwise it sets a data cell value. If an error is raised, the value gets set to the empty string.
Here's an example that loads a large tree β it shows off that only the first dozen or so get updated initially, and more as you scroll. A practical example might load data from a database π:
set t [tree create]
$t create -num 10000
pack [treeview .t -tree $t]
proc FillLabel {id} { puts "L$id"; return L$id }
proc FillData {id} { return D$id }
.t col conf #0 -fillcmd FillLabel
.t col insert end A -fillcmd FillData
-hideboolean β if boolean is true, the column is not displayed. Default isno.-justifyjustify β specifies how the column data fields' text should be justified within the column. This only matters when the column is wider than the data field being displayed. Justify must beleft,right, orcenter. Default iscenter.-maxsize β maximum size for the column.-minsize β minimum size for the column.-padpad β specifies how much padding goes on the left and right sides of the column. Pad is a list of one or two screen distances. If pad has two elements, the left side of the column is padded by the first distance and the right side by the second. If pad has just one distance, both sides get padded evenly. The default is2.-reliefrelief β specifies the 3-D effect of the column. Relief says how the column should appear relative to the widget; for example,raisedmeans the column should appear to protrude. The default isflat.-ruledashesvalue β set resize rule is dashed.-scrolltilebool β tile image scrolls.-sortaltcolumnslist β a list of alternate columns sort can use when cell values are equal. Including the current column or the tree column is an error, so don't.-sortcommandscript β the command that actually compares entries during sort.-sortmodemode β used by scripts to set-modefor the sort command (eg.blt::tv::SortColumn).-statestate β sets the state of the column. If state isdisable, then the column title can't be activated nor invoked. The default isnormal.-stylestylename β set the style to use for the column.-tileimage β image to tile the column with.-titlestring β sets the title for the column. The default is"".-titlearrowvalue β forces an arrow to be drawn in the title. The value is one of:leftrightupdownnone, and it defaults tonone. This is what you use when implementing custom sorts, as the indicator.-titlebackgroundcolor β background for the title.-titleborderwidthsize β border size.-titlefontfont β font for the column title.-titlejustifyjust β side to place the title.-titleforegroundcolor β sets the foreground color of the column title. The default isblack.-titlereliefrelief β relief for the title.-titleshadowcolor β sets the color of the drop shadow of the column title. The default is"".-titlestylestyle β a style to use for titles.-widthnum β the user requested width for the column.-underlinenum β which character to underline in the column title text. Default is-1.-validatecmdcommand β this option gives you a command for validating or post-processing edits from the builtin column edit feature (enabled withcol conf -edit 1). If a percent is found, command substitution occurs; otherwise 5 arguments are appended:widget data olddata ind col. The called command should returnnewvalue, possibly with modifications. Wanna revert to the original value? Just return$oldvalue. Wanna keep editing? Usereturn -code return. π«Ά-weightfloat β weighting to apply extra space.-widthpixels β sets the requested width of the column. This overrides the computed width of the column. If pixels is0, the width is computed from the contents of the column. The default is0.
πͺ EMBEDDED WINDOWS πͺ
Embedded windows are supported for columns or cells via the special style type windowbox. If -windowcmd isn't being used, the cell data is assumed to contain the widget name, or the tail part of a widget name. If the data doesn't give you a valid window, it's silently ignored and nothing gets displayed β no drama, no error. And if multiple cells try to display the same widget at the same time, only the first one shows up. The normal Tk slave window rules apply (ie. must be child of the parent).
π OLD TEXT EDITING OPTIONS π
SECTION OBSOLETE. π (iconic of it to still be here, honestly)
This section is obsolete and has been replaced with builtin editing using a Tk entry widget. See TREEVIEW EDITING above. So like... don't come for me, this is legacy.
Text edit window configuration options may also be set by the Tk option command. The resource class is TreeViewEditor. The resource name is always edit.
option add *TreeViewEditor.Foreground white
option add *edit.Background blue
The following are the configuration options available for the text editing window. Yes, all of them, yes even the obsolete ones, I'm being thorough:
-backgroundcolor β sets the background of the text edit window. The default iswhite.-borderwidthpixels β sets the width of the 3-D border around the edit window. The-reliefoption determines if a border is to be drawn. The default is1.-exportselectionboolean β indicates if the text selection is exported. If the edit window is exporting its selection, then it will observe the standard X11 protocols for handling the selection. Selections are available as typeSTRING. The default isno.-reliefrelief β specifies the 3-D effect of the edit window. Relief indicates how the background should appear relative to the edit window; for example,raisedmeans the background should appear to protrude. The default issolid.-selectbackgroundcolor β sets the background of the selected text in the edit window. The default iswhite.-selectborderwidthpixels β sets the width of the 3-D border around the selected text in the edit window. The-selectreliefoption determines if a border is to be drawn. The default is1.-selectforegroundcolor β sets the foreground of the selected text in the edit window. The default iswhite.-selectreliefrelief β specifies the 3-D effect of the selected text in the edit window. Relief indicates how the text should appear relative to the edit window; for example,raisedmeans the text should appear to protrude. The default isflat.
π DEFAULT BINDINGS π
okay so this is the part where Tk just does stuff for you β no cap, the widget comes pre-wired. Tk automatically creates class bindings for treeviews that give them Motif-like behavior. And a huge chunk of how a treeview widget actually acts? It's decided by its -selectmode option, which picks one of two ways of dealing with the selection. π¦
If the selection mode is single, only one node can be selected at a time. Clicking button 1 on a node selects it and deselects any other selected item. literally one at a time bestie, that's the whole vibe.
If the selection mode is multiple, any number of entries may be selected at once, including discontiguous ranges. Clicking Control-Button-1 on a node entry toggles its selection state without affecting any other entries. Pressing Shift-Button-1 on a node entry selects it, extends the selection. iconic multi-select behavior, we love to see it β¨
[0]β The virtual event<<TreeViewFocusEvent>>is generated for each keyboard and mouse initiated change in focus. It is up to the user to determine if the focus actually changed. (yes bestie, you gotta check yourself, the widget isn't gonna tell you π)[1]β In extended mode, the selected range can be adjusted by pressing button 1 with the Shift key down: this modifies the selection to consist of the entries between the anchor and the entry under the mouse, inclusive. The un-anchored end of this new selection can also be dragged with the button down. π«Ά[2]β In extended mode, pressing button 1 with the Control key down starts a toggle operation: the anchor is set to the entry under the mouse, and its selection state is reversed. The selection state of other entries isn't changed. If the mouse is dragged with button 1 down, then the selection state of all entries between the anchor and the entry under the mouse is set to match that of the anchor entry; the selection state of all other entries remains what it was before the toggle operation began. ngl this one's a whole little algorithm, respect it π[3]β If the mouse leaves the treeview window with button 1 down, the window scrolls away from the mouse, making information visible that used to be off-screen on the side of the mouse. The scrolling continues until the mouse re-enters the window, the button is released, or the end of the hierarchy is reached. autoscroll go brrr π[4]β Mouse button 2 may be used for scanning. If it is pressed and dragged over the treeview widget, the contents of the hierarchy drag at high speed in the direction the mouse moves. zoom zoom π[5]β If the Up or Down key is pressed, the location cursor (active entry) moves up or down one entry, as doesControl-pandControl-n. If the selection mode is browse or extended then the new active entry is also selected and all other entries are deselected. In extended mode the new active entry becomes the selection anchor.[6]β In extended mode,Shift-UpandShift-Downmove the location cursor (active entry) up or down one entry and also extend the selection to that entry in a fashion similar to dragging with mouse button 1.[7]β The Left and Right keys scroll the treeview widget view left and right by the width of the character0.Control-LeftandControl-Rightscroll the treeview widget view left and right by the width of the window. (yes, the literal character zero, that's the unit, don't ask π)[8]β The Prior and Next keys scroll the treeview widget view up and down by one page (the height of the window), as doesControl-uandControl-d.[9]β The Home and End keys scroll the treeview widget horizontally to the left and right edges, respectively.[10]βControl-Homesets the location cursor to the first entry, selects that entry, and deselects everything else in the widget. main character entry energy π[11]βControl-Endsets the location cursor to the last entry, selects that entry, and deselects everything else in the widget.[12]β In extended mode,Control-Shift-Homeextends the selection to the first entry andControl-Shift-Endextends the selection to the last entry.[13]β In multiple mode,Control-Shift-Homemoves the location cursor to the first entry andControl-Shift-Endmoves the location cursor to the last entry.[14]β The space and Select keys make a selection at the location cursor (active entry) just as if mouse button 1 had been pressed over this entry.[15]β In extended mode,Control-Shift-spaceandShift-Selectextend the selection to the active entry just as if button 1 had been pressed with the Shift key down.[16]β In extended mode, the Escape key cancels the most recent selection and restores all the entries in the selected range to their previous selection state. undo but make it selection-only π[17]βControl-slashselects everything in the widget, except in single and browse modes, in which case it selects the active entry and deselects everything else.[18]βControl-backslashdeselects everything in the widget, except in browse mode where it has no effect.[19]β The F16 key (labelledCopyon many Sun workstations) orMeta-wcopies the selection in the widget to the clipboard, if there is a selection. π
The behavior of treeview widgets can be changed by defining new bindings for individual widgets or by redefining the class bindings. your widget, your rules bestie π
π¦ WIDGET BINDINGS π¦
In addition to the above behavior, the following additional behavior is defined by the default widget class (TreeView) bindings.
<ButtonPress-2>β Starts scanning.<B2-Motion>β Adjusts the scan.<ButtonRelease-2>β Stops scanning.<B1-Leave>β Starts auto-scrolling.<B1-Enter>β Starts auto-scrolling<KeyPress-Up>β Moves the focus to the previous entry.<KeyPress-Down>β Moves the focus to the next entry.<Shift-KeyPress-Up>β Moves the focus to the previous sibling.<Shift-KeyPress-Down>β Moves the focus to the next sibling.<KeyPress-Prior>β Moves the focus to first entry. Closed or hidden entries are ignored.<KeyPress-Next>β Move the focus to the last entry. Closed or hidden entries are ignored.<KeyPress-Left>β Closes the entry. It is not an error if the entry has no children.<KeyPress-Right>β Opens the entry, displaying its children. It is not an error if the entry has no children.<KeyPress-space>β In"single"select mode this selects the entry. In"multiple"mode, it toggles the entry (if it was previous selected, it is not deselected).<KeyRelease-space>β Turns off select mode.<KeyPress-Return>β Sets the focus to the current entry.<KeyRelease-Return>β Turns off select mode.<KeyPress>β Moves to the next entry whose label starts with the letter typed. type-ahead, we stan β¨οΈ<KeyPress-Home>β Moves the focus to first entry. Closed or hidden entries are ignored.<KeyPress-End>β Move the focus to the last entry. Closed or hidden entries are ignored.<Control-a>β Move to parent of current entry.<Control-o>β Open current entry.<Control-Shift-O>β Open current entry recursively.<Double-ButtonRelease-1>β Edit cell.<Alt-Double-ButtonRelease-1>β Edit cell.<Control-KeyPress-minus>β Close parent of current entry.<Control-F1>β Opens all tree nodes.<Control-F2>β Closes all tree nodes (except root).<Control-F3>β Toggle flat mode.<Control-F4>β Reset all column widths back to0allowing autosizing.<Control-Shift-O>β Open focus tree node recursively.<Control-Shift-C>β Close focus tree node recursively.
π BUTTON BINDINGS π
Buttons have bindings. There are associated with the "all" bindtag (see the entry's -bindtag option). You can use the bind operation to change them.
<Enter>β Highlights the button of the current entry.<Leave>β Returns the button back to its normal state.<ButtonRelease-1>β Adjust the view so that the current entry is visible.
πΈ ENTRY BINDINGS πΈ
Entries have default bindings. There are associated with the "all" bindtag (see the entry's -bindtag option). You can use the bind operation to modify them.
<Enter>β Highlights the current entry.<Leave>β Returns the entry back to its normal state.<ButtonPress-1>β Sets the selection anchor the current entry.<Double-ButtonPress-1>β Toggles the selection of the current entry.<B1-Motion>β For"multiple"mode only. Saves the current location of the pointer for auto-scrolling. Resets the selection mark.<ButtonRelease-1>β For"multiple"mode only. Sets the selection anchor to the current entry.<Shift-ButtonPress-1>β For"multiple"mode only. Extends the selection.<Shift-Double-ButtonPress-1>β Place holder. Does nothing. π΄<Shift-B1-Motion>β Place holder. Does nothing. π΄<Shift-ButtonRelease-1>β Stop auto-scrolling.<Control-ButtonPress-1>β For"multiple"mode only. Toggles and extends the selection.<Control-Double-ButtonPress-1>β Place holder. Does nothing. π΄<Control-B1-Motion>β Place holder. Does nothing. π΄<Control-ButtonRelease-1>β Stops auto-scrolling.<Control-Shift-ButtonPress-1>β???(yes that's literally what the page says, we're all just vibing here π)<Control-Shift-Double-ButtonPress-1>β Place holder. Does nothing. π΄<Control-Shift-B1-Motion>β Place holder. Does nothing. π΄
β¨ COLUMN BINDINGS β¨
Columns have bindings too. They are associated with the column's "all" bindtag (see the column -bindtag option). You can use the column bind operation to change them.
<Enter>β Highlights the current column title.<Leave>β Returns the column back to its normal state.<ButtonRelease-1>β Invokes the command (see the column's-commandoption) if one if specified.
π§ COLUMN RULE BINDINGS π§
These are bindings associated with the tag Rule.
<Enter>β Highlights the current and activates the ruler.<Leave>β Returns the column back to its normal state. Deactivates the ruler.<ButtonPress-1>β Sets the resize anchor for the column.<B1-Motion>β Sets the resize mark for the column.<ButtonRelease-1>β Adjust the size of the column, based upon the resize anchor and mark positions. drag-to-resize, genuinely so satisfying π₯
πΈ QUICKSTART πΈ
TreeFill is a utility function that makes loading tree data from a human-readable string way easier, bestie. The string uses line indentation to show tree depth. Indentation is in multiples of 4 spaces, relative to the first line. eg.
pack [treeview .t]
.t column insert end X Y Z
blt::tv::TreeFill .t {
A 1 2 3
B 4 5 6
x 7 8 9
y 10 11 12
a 1 2 "Level a"
b 1 2 "Level b"
C 1 2 3
}
.t open -trees all
.t entry conf 0->B->y->a -state disabled
Any column names that aren't defined are generated. To load a table instead of a tree, just set the -flat option first. eg.
pack [treeview .t -flat 1]
.t column conf #0 -hide 1
.t column insert end Name Age Sex
blt::tv::TreeFill .t {
"Tom Brown" 9 M
"Mike Small" 8 M
"Tina Baker" 7 F
}
π EXAMPLE π
The treeview command creates a new widget. Iconic.
treeview .t -bg white
A new Tcl command .t is also created, and you can use it to query and modify the treeview widget. For example, to change the background color of the table to "green", you use the new command and the widget's configure operation.
# Change the background color.
.t configure -background "green"
By default, the treeview widget will automatically create a new tree object to contain the data. The name of the new tree is the pathname of the widget. Above, the new tree object name is ".t". But you can use the -tree option to specify the name of another tree.
# View the tree "myTree".
.t configure -tree "myTree"
When a new tree is created, it contains only a root node. That node is automatically opened. The id of the root node is always 0 (you can also use the special id root). The insert operation lets you insert one or more new entries into the tree. The last argument is the node's pathname.
# Create a new entry named "myEntry"
set id [.t insert end "myEntry"]
This appends a new node named "myEntry". It gets positioned as the last child of the root of the tree (using the position "end"). You can supply another position to order the node within its siblings.
# Prepend "fred".
set id [.t insert 0 "fred"]
Entry names do not need to be unique. By default, the node's label is its name. To supply a different text label, add the -label option.
# Create a new node named "fred"
set id [.t insert end "fred" -label "Fred Flintstone"]
The insert operation returns the id of the new node. You can also use the index operation to get this information.
# Get the id of "fred"
.t index "fred"
To insert a node somewhere other than root, use the -at switch. It takes the id of the node where the new child will be added.
# Create a new node "barney" in "fred".
.t insert end "barney" -at $id
A pathname describes the path to an entry in the hierarchy. It's a list of entry names that compose the path in the tree. Therefore, you can also add "barney" to "fred" as follows.
# Create a new sub-entry of "fred"
.t insert end "fred barney"
Every name in the list is an ancestor of the next one. All ancestors must already exist. That means that an entry "fred" is an ancestor of "barney" and must already exist. But you can use the -autocreate configuration option to force the creation of ancestor nodes.
# Force the creation of ancestors.
.t configure -autocreate yes
.t insert end "fred barney wilma betty"
Sometimes the pathname is already separated by a character sequence rather than formed as a list. A file name is a good example of this. You can use the -separator option to specify a separator string to split the path into its components. Each pathname inserted is automatically split using the separator string as a separator. Multiple separators are treated as one.
.t configure -separator /
.t insert end "/usr/local/tcl/bin"
If the path is prefixed by extraneous characters, you can automatically trim it off using the -trim option. It removes the string from the path before it is parsed.
.t configure -trim C:/windows -separator /
.t insert end "C:/window/system"
You can delete entries with the delete operation. It takes one or more tags of ids as its argument. It deletes the entry and all its children.
.t delete $id
Entries have several configuration options, and they control the appearance of the entry's icon and label. We have already seen the -label option that sets the entry's text label. The entry configure operation lets you set or modify an entry's configuration options.
.t entry configure $id -color red -font fixed
You can hide an entry and its children using the -hide option.
.t entry configure $id -hide yes
More than one entry can be configured at once. All entries specified are configured with the same options.
.t entry configure $i1 $i2 $i3 $i4 -color brown
# or ...
.t entry configure [list $i1 $i2 $i3 $i4] -color brown
An icon is displayed for each entry. It's a Tk image drawn to the left of the label. You can set the icon with the entry's -icons option. It takes a list of two image names: one to represent the open entry, another when it is closed.
set im1 [image create photo -file openfolder.gif]
set im2 [image create photo -file closefolder.gif]
.t entry configure $id -icons "$im1 $im2"
If -icons is set to the empty string, no icons are displayed.
If an entry has children, a button is displayed to the left of the icon. Clicking the mouse on this button opens or closes the sub-hierarchy. The button is normally a + or - symbol, but can be configured in a variety of ways using the button configure operation. For example, the + and - symbols can be replaced with Tk images.
set im1 [image create photo -file closefolder.gif]
set im2 [image create photo -file downarrow.gif]
.t button configure $id -images "$im1 $im2" \
-openrelief raised -closerelief raised
Entries can contain an arbitrary number of data fields. Data fields are name-value pairs. Both the value and the name are strings. The entry's -data option lets you set data fields.
.t entry configure $id -data {mode 0666 group users}
The -data takes a list of name-value pairs.
You can display these data fields as columns in the treeview widget. You can create and configure columns with the column operation. For example, to add a new column to the widget, use the column insert operation. The last argument is the name of the data field that you want to display.
.t column insert end "mode"
The column title is displayed at the top of the column. By default, it's the field name. You can override this using the column's -title option.
.t column insert end "mode" -title "File Permissions"
Columns have several configuration options. The column configure operation lets you query or modify column options.
.t column configure "mode" -justify left
The -justify option says how the data is justified within the column. The -hide option indicates whether the column is displayed.
.t column configure "mode" -hide yes
Entries can be selected by clicking on the mouse. Selected entries are drawn using the colors specified by the -selectforeground and -selectbackground configuration options. The selection itself is managed by the selection operation.
# Clear all selections
.t selection clear 0 end
# Select the root node
.t selection set 0
The curselection operation returns a list of ids of all the selected entries.
set ids [.t curselection]
You can use the get operation to convert the ids to their pathnames.
set names [eval .t get -full $ids]
If a treeview is exporting its selection (using the -exportselection option), then it will observe the standard X11 protocols for handling the selection. Treeview selections are available as type STRING; the value of the selection will be the pathnames of the selected entries, separated by newlines.
The treeview supports two modes of selection: single and multiple. In single select mode, only one entry can be selected at a time, while multiple select mode allows several entries to be selected. The mode is set by the widget's -selectmode option.
.t configure -selectmode "multiple"
You can be notified when the list of selected entries changes. The widget's -selectcommand specifies a Tcl procedure that is called whenever the selection changes.
proc SelectNotify { widget } {
set ids [$widget curselection]
}
.t configure -selectcommand "SelectNotify .t"
The widget supports the standard Tk scrolling and scanning operations. The treeview can be both horizontally and vertically scanned. You can attach scrollbars to the treeview the same way as the listbox or canvas widgets.
scrollbar .xbar -orient horizontal -command ".t xview"
scrollbar .ybar -orient vertical -command ".t yview"
.t configure -xscrollcommand ".xbar set" \
-yscrollcommand ".ybar set"
Entries can be programmatically opened or closed using the open and close operations respectively.
.t open $id
.t close $id
When an entry is opened, a Tcl procedure can be automatically invoked. The -opencommand option specifies this procedure. This procedure can lazily insert entries as needed.
proc AddEntries { dir } {
eval .t insert end [glob -nocomplain $dir/*]
}
.t configure -opencommand "AddEntries %P"
Now when an entry is opened, the procedure AddEntries is called and adds children to the entry. Before the command is invoked, special "%" substitutions (like bind) are performed. Above, %P is translated to the pathname of the entry.
The same feature exists when an entry is closed. The -closecommand option specifies the procedure.
proc DeleteEntries { id } {
.t entry delete $id 0 end
}
.t configure -closecommand "DeleteEntries %#"
When an entry is closed, the procedure DeleteEntries is called and deletes the entry's children using the entry delete operation (%# is the id of entry).
π OLD TREEVIEW EDITS π
β οΈ Heads up bestie: this whole section is OBSOLETE. Native Tk widgets are used for editing now. It's giving museum exhibit, but we're still documenting it because iykyk and the details matter. π«Ά
When editing, the subwidget .edit is available. Slay.
pathName.edit operation ?args?
Okay so this operation is the whole text-editing setup for cells (aka data fields in a column) or entry labels. It has several forms, depending on operation:
pathName.edit applyβ Applies the edited buffer, replacing the entry label or data field. The edit window then gets hidden. π¨pathName.edit cancelβ Cancels the editing operation, reverting the entry label or data value back to the previous value. The edit window is hidden. It's giving "nvm, never happened" energy.pathName.edit cget valueβ Returns the current value of the configuration option given by option. Option may have any of the values accepted by theconfigureoperation described below. Literally just a lil peek at the config.pathName.edit configure ?option value?β Query or modify the configuration options of the edit window. If no option is specified, it returns a list describing all of the available options (seeTk_ConfigureInfofor info on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. Option and value are described in the section TEXT EDITING OPTIONS below. Iconic configure behavior, no notes. β¨pathName.edit delete first lastβ Deletes the characters in the edit buffer between the two given character positions. Bye bye text π¦pathName.edit get ?-root? x yβ go grab something, bestie πpathName.edit icursor indexβ sets the cursor position, main character placement πpathName.edit index indexβ Returns the text index of given index. Lowkey useful.pathName.edit insert index stringβ Insert the text string into the edit buffer at the index index. For example, the index0will prepend the buffer. Oh we're fancy.pathName.edit selection argsβ This operation controls the selection of the editing window. Note that this differs from the selection of entries. It has the following forms:pathName.edit selection adjust indexβ Adjusts either the first or last index of the selection.pathName.edit selection clearβ Clears the selection. Gone. πpathName.edit selection from indexβ Sets the anchor of the selection.pathName.edit selection presentβ Indicates if a selection is present. A little vibe check on ur selection, honestly.pathName.edit selection range start endβ Sets both the anchor and mark of the selection.pathName.edit selection to indexβ Sets the unanchored end (mark) of the selection.
π·οΈ LABEL ISSUES π·οΈ
Entries take a -label option that can be used to specify the text to display. Important though: this is not the same thing as the node label. Don't confuse them, bestie, they're different girlies entirely. π
By default, labels are checked for duplicates by insert, which can slow down large (10k+) inserts. Setting -allowduplicates to 1 disables this checking. Fr fr, that's your speed setting for big inserts. π
An entry's label can be changed either by setting -allowduplicates to 1 and using treeview's entry relabel, or by using tree's label command. Two paths, both valid. β¨
Instead of lists, a separator can be specified with -separator. Thus for managing files we might use:
treeview .t -separator / -autocreate 1
.t insert end mann/text.n mann/canvas.n
.t insert end Help Search Close -at root->mann->text.n
pack .t
Periodt. That's the whole file-tree fantasy right there. πΈ
π NOTES π
Text cells in display height can be at most 64K pixels high per row. That's the ceiling, bestie β literally the limit. Don't come at it with a taller row. π
π KEYWORDS π
treeview, widget
And that's a wrap on the whole page, babes! π This one came to you courtesy of BLT version 2.5, and it's the treeview(n) manual page β you're fully caught up, no cap. Go forth and treeview responsibly. π¦πβ¨
π¦ where this page comes from
- nixpkgs unstable: blt 2.5.3
- Copyright 2001-2 by Silicon Metrics Corporation
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms