blt::treeview(3tcl)
blt::treeview π β the BLT Built-In Commands era
okay bestie, buckle up, because this is the manual page for treeview from the BLT Built-In Commands collection, and she is long. Grab a snack. π
β¨ NAME β¨
treeview β create and manipulate hierarchical table widgets π¦
πΈ SYNOPSIS πΈ
treeview pathName ?options?
π DESCRIPTION π
The treeview widget shows you a whole tree of data, and it comes with styles, tags, and data sharing (through tree data objects). It's giving main character energy, honestly.
π INTRODUCTION π
So the treeview widget keeps a whole collection of entries, and every single entry holds a tree node plus extra style and attribute info on top. Like, node but make it fashion. β¨
Entries usually get inserted into a treeview with a label-list, which spells out the unique hierarchical position relative to root (or relative to the -at node). The tail of that label-list is unique within its own hierarchical level, no cap. If you don't hand over a label, then the generated node-id becomes the label. Labels are the whole reason you can index entries with the -> notation. Obsessed. 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 π
You can stash column data inside an entry using the -data option or the 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
And guess what β labels can be created with auto-generated sequence numbers by using an empty string or a trailing #auto. slay. π
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 π§
Plot twist: node data in treeview is actually stored in a tree data object, which keeps data storage and widget appearance totally separate. Very "we are not the same" of it. The -tree option lets you explicitly set a tree (one you created externally with the tree command), which gives you access to trees' way 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 you insert data via the tree sub-commands, unique label checking is not performed. Not me warning you, but like, I'm warning you.
β SYNTAX β
treeview pathName ?option value?...
The treeview command creates a brand-new window pathName and turns it into a treeview widget. At the moment you invoke this command, there must not already be a window named pathName β but pathName's parent has to exist. You can also pass additional options on the command line or in the option database to configure widget things like its colors and font. For the exact deets on which option and value pairs are valid, check out the configure operation below.
If it works out, treeview returns the path name of the widget. It also creates a new Tcl command with that same name. You use that command to invoke various operations that query or modify the widget. All the operations available are described in the TREEVIEW OPERATIONS section.
Treeview displays nodes as row entries in the widget. Every entry has a text label and an icon. When a node has children, its entry gets drawn with a little button to the left of the label. Clicking the mouse over that button opens or closes the node. When a node is open, its children are exposed; when it's closed, the children and their descendants are hidden. That button is normally a + or - symbol (ala Windows Explorer), but you can swap it out for a pair of Tk images (open and closed images). π
If the node has data associated with it, that data can be displayed in columns running vertically on either side of the tree. You can control the color, font, etc of each entry. Any entry label or data field can be edited in-place. iconic.
π IDS AND TAGS π
Nodes can be inserted into a tree using the treeview widget
blt::treeview .t
set node [.t insert end "one"]
or the tree command.
set tree [blt::tree create]
set node [$tree insert root -label "one"]
blt::treeview .t -tree $tree
Either way, you get back a number identifying the node (that's the value of $node). This serial number, or id, uniquely identifies the node. Please note: you can't infer a location or position of a node from its id. The one and only exception is that the root node is always id 0. Since nodes may have the same labels or get moved around within the tree, ids are a convenient way to identify nodes. If a tree is shared, the ids will be the same 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 can 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 β which is typically done to associate a group of nodes. Lots of operations in the treeview widget take either node ids or tag names as arguments. Using a tag means the operation applies 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 consists 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. That means, for example, that tags created by the tree command are available in the treeview widget. sharing is caring fr fr π«Ά
π₯ SPECIAL NODE IDS π₯
There are several special non-numeric ids. Special ids differ from tags in that they're always translated to a single numeric node. They also take precedence over tags. So like, you can't use a tag name that's 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's 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's 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.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's 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 a 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. π
...and that's just part 1, bestie β more parts coming, don't go anywhere π
β¨ 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.
π 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 commmands support the array notation: entry get, entry set, entry incr, entry unset, and find -column. See tree for more complete support.
π«Ά 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 the 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 operation are available for treeview widgets:
pathName bbox ?-screen? tagOrId...β Returns a list of 4 numbers, representing a bounding box of around the specified entries. The entries is 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 y coordinate the title height is added in. 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 occurs 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.
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 it's 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 an 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 occurs 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.
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 the"", 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 of around the specified entries cell. Giving an entry of-1matches the title row. If-visibleis given, the width is constrained to not extend past the widgets 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 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 of 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"or"end-N".
pathName column insert position field ?field ...? ?options...?β bestie, this one makes columns. β¨ Eachfieldis the name of a data field that every entry node gets displayed in that column. If a node doesn't define the field you asked for, the cell just sits there blank (mood, honestly).positionsays where in the column lineup the new one goes β it can be a name, a number, orend. If you're inserting multiplefields at once, only the first one is allowed to start with a dash. Iffieldis the empty string or#auto, a name gets generated for you, prefixed with the stringColplus a unique integer. And iffieldends with#auto, the generated name uses its prefix instead. What comes back is the created column names. π Oh and heads up β the tree column#0is predefined and can not be deleted, periodt.pathName column invoke fieldβ fires off the Tcl command tied to the columnfield, if there even is one (it's the column's-commandoption). But if that column's-stateoption is set todisabled, the command is straight-up ignored. πpathName column isset ?startOrTag? ?end?β hands you a list of the data columns for elements in a range that actually have data values set in them. One possible use? Hiding columns that are empty. π§ No arguments at all = it only checks the entries on the visible screen. One argument = it checks all entries matching a tag or id. Two arguments = it checks all entries between thestartandendrange.pathName column istree fieldβ returns1if the column is the tree column. That's it, that's the whole vibe check. πpathName column move name destβ moves the columnnameto the destination position.destis 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, ordered exactly how they're drawn, left-to-right. If you pass-visible, it only shows columns where-hideis0. You can also hand it a pattern to limit the results. πpathName column nearest x ?y?β returns the name of the column closest to that X-Y screen coordinate. And if you also give it ayargument (it's optional, no pressure), a name only comes back if the point is over a column's title. πpathName column offsetsβ returns the starting offsets for each column. Little map of where everything begins. βpathName column resize op ...β the operations for resize, whereopis one ofactivate,anchor,mark, orset. That's the list, bestie, I'm not making any of it up. πΈpathName column see ?-anchor anchor? fieldβ adjusts the view so the column given byfieldis visible in the widget window. Where it lands on your screen is controlled with the-anchorflag, and 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 sitting inside closed subtrees. The root node does not get included when-hiderootis true. And the-defaultoption gives you a value to substitute in for unset data column cells. π (yes it's a lot of options, you're doing great)
pathName configure ?option? ?value option value ...?β query or modify the configuration options of the widget. Nooptionat all? You get a list describing all the available options forpathName(peepTk_ConfigureInfofor info on the format of that list). Give it anoptionwith novalueand you get a list describing that one named option β and that list will be identical to the corresponding sublist of the value you'd get if you'd specified no option. Give it one or more option-value pairs and it modifies the given widget option(s) to have the given value(s); in that case the command returns an empty string.optionandvalueare described in the section TREEVIEW OPTIONS below. πpathName curselectionβ returns a list with the ids of all the entries currently selected. Nothing selected? You get the empty string back. πpathName delete tagnode...β deletes one or more entries given bytagnode, and its children. Be so careful, bestie, this one takes the whole family. π₯pathName edit ?-test? ?-root? ?-noscroll? ?-scroll? ?X Y?β handles cell editing. Thex,ycoordinates are usually required, except when you're using the scroll options.-noscrollβ disables scrolling. Useful when displaying an edit subwindow.-scrollβ re-enables scrolling. Usually bound to a destroy event of an edit subwindow.-rootβ use root coordinates.-testβ test if the 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 bytagOrId. When an entry is active it gets drawn using its active icon (see the-activeiconand-activeleaficonoptions). The special id of the currently active node isactive. Heads up though: there can be only one active node at a time, and currently the icons must be the same size/shape as the backgrounds, because 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 byoption.optioncan be 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 oftagOrId.TagOrIdis the id or tag of the node you're examining. Only afirstargument present? Then you get the id of that child at that numeric position. Bothfirstandlastgiven? Then you get the ids of all the children in that range. Otherwise, you get the ids of all the children. π¦pathName entry configure tagnode ?option? ?value option value ...?β query or modify the configuration options of the widget. Nooption? You get a list describing all the available options fortagnode(checkTk_ConfigureInfofor info on the format of this list).optionwith novalue? You get a list describing that one named option β identical to the corresponding sublist of the value returned if no option were specified. One or more option-value pairs? It modifies the given widget option(s) to have the given value(s), and returns an empty string.optionandvalueare described below: πpathName entry delete tagOrId ?first ?last?β deletes the one or more children nodes of the parenttagOrId. If thefirstandlastarguments are there, they're positions designating a range of children nodes to be deleted. πpathName entry depth tagOrIdβ returns the tree depth of the node, where the root is0. πpathName entry down tagOrIdβ the next open node from the given node. The down of the last open node is the same. π«ΆpathName entry exists tagOrIdβ returns1if the entry exists. βpathName entry get tagOrId ?key? ?default?β returns a key-field value for an entry. With nokeygiven, it returns the values of all visible columns. If the givenkeyis undefined, you getdefaultif one was given, otherwise it throws an error. And unlikeentry set, the tree is accessed directly, so keys that don't have associated columns are supported. π₯pathName entry incr tagOrId key ?amount?β increments the value by1, or by the givenamount, and returns the value. Theincroperation normally tries to use integers, but it uses doubles when either the value or theamountis a double. An array reference may also be used. πpathName entry isbefore tagOrId1 tagOrId2β returns1iftagOrId1is beforetagOrId2, and0otherwise. πpathName entry ishidden tagOrIdβ returns1if the node is currently hidden,0otherwise. And a node also counts as 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β returns true if the entry sets a column-field (like, it has a value). Both the entry and the column must exist. β¨pathName entry isvisible tagOrIdβ returns1if the node is not hidden, 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 back to the root node. πpathName entry parent tagOrIdβ returns the parent of the given node. π«ΆpathName entry prev tagOrIdβ the last open node from the given node. But unlikeup, when the focus is at the root,lastwraps around to the last open node in the tree. βpathName entry relabel tagOrId newLabelβ changes the tree node label associated with an entry. This sets the tree node label, i.e. the value returned by thegetcommand. And no, this is not the same thing as the treeview entries-labeloption, don't get it twisted. Also, the-allowduplicatesoption must be enabled to use this command, since no duplicate checking will be performed. No duplicate checking, bestie. π
pathName entry select tagOrId
Makes that node show up on screen and hands it the focus. And if you're in single selectmode? It also gets selected. Under the hood this calls ::blt::tv::MoveFocus, so yeah, it's doing the whole song and dance. β¨
pathName entry set tagOrId col ?value col value ...?
Reads or writes column-fields on an entry. It's the easy-peasy way to peek at or update the fields that live in an entry's -data option. You can also hand it an array reference instead. π
pathName entry sibling ?-before? tagOrId
Gives you the next/previous sibling of the given node. If the node is already the last/first sibling, then... nothing comes back. Empty. Void. π
pathName entry size -recurse tagOrId
Returns how many children the parent node tagOrId has. Throw in the -recurse flag and you get the count of all its descendants instead. Oh and heads up β the node itself is never counted. It's not about them. π
pathName entry unset tagOrId col
Removes a column-field from an entry. An array reference works here too.
pathName entry up tagOrId
The last open node, in depth-first order, going from the given node. And plot twist: the up of the last node is itself. π
pathName entry value tagOrId ?col?
Returns the value for one entry column β or, if you don't pass col, all the visible columns. And unlike entry set, this one lets you get at the formatted value that came out of -formatcmd (if there even was one). That's the glow-up version of the value, bestie. π
pathName find ?flags? first last
Finds all the entries that match whatever criteria you threw in flags, and hands you back a list of ids for every matching node. first and last are ids marking the range of the search in depth-first order. And if last comes before first? Then it searches in reverse. π₯
The valid flags are:
-addtagNAME β Slap this tag onto every matching entry. And yes, the tag gets created even if literally no nodes end up tagged.-cmdargscolumns β Names the columns whose values get appended onto-command.-commandcommand β Runs command once per matching node. Right before it fires, the node's id gets appended. If command throws an error, processing stops and the whole find operation returns an error. If command returnsreturn, then the integer it gives back is used to signal 1 for a match or 0 for a mismatch.-columncol β Matches name against the value of the given column. An array reference may also be used. This one must be used together with-name, and it may not be used with-usepath.-countβ Just give me the number of matches. That's it, that's the whole job.-depthnumber β The entry has to be at depth number.-exactβ Patterns have to match exactly. This is the default, no cap.-execstring β A Tcl script that gets evaluated for each matching node. If-varwas also given, that variable gets set to the node id's value before each evaluation. Otherwise, percent substitutions happen β and note that 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 gets skipped.
Here are the percent substitutions available on string:
%#β 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 it gives you the on-screen value (from-formatcmd).%Cβ The current column.%%β Translates to a single percent sign.
-globβ Use global pattern matching. The matching works similar to the waystring matchdoes it.-invertβ Flips the meaning of the pattern match for-name.-isclosedβ Only include entries that are closed.-isemptyβ Only match nodes where the value of the specified-columnkey was unset.-ishiddenβ Only include entries that are hidden, whether that's because the entry has-hideset or because it has a style that's hidden. The root node is not included.-isleafβ The entry must not have any child nodes.-ismappedβ Only include entries that are currently all or partly drawn on screen. The root node is not included.-isopenβ Only include entries that are opened.-istreeβ The entry must have child nodes.-limitnumber β Stop searching once you hit number matches.-maxdepthβ The entry must be at that depth or lower.-mindepthβ The entry must be at that depth or higher.-namepattern β The pattern to match against node names.-nocaseβ Comparison ignores case. For-regexp, the target string gets lower-cased (but not the pattern). π-notopβ Excludes the-topnode, or the starting node.-regexpβ Use regular expression pattern matching, i.e. the same thingregexpimplements.-reldepthβ Changes what-depth,-mindepthand-maxdepthmean, so they're relative to the-topnode.-returncol β Instead of the node id, return the data value of the named column. If col starts with a%, it does percent substitution just like-commanddoes. Note that a percent substitution longer than 2 chars will append values as list elements.-topnode β Search only at node and 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 you use it with-visible, only the visible column keys get used.-visibleβ Exclude values that are hidden or sitting inside closed subtrees. e.g. the root node gets excluded if-hiderootis true.-withouttagNAME β Match entries without the tag.-withtagNAME β Match entries with the tag.-varvariable β A variable to set with the node id before each iteration of the-execscript.-optionname value β Specifies an option name and value to match against the node entry's configuration option.--β Indicates the end of flags. Periodt.
pathName focus ?tagOrId?
Gets or sets the focus to the node given by tagOrId. When a node has focus, it can receive keyboard events β that's its main character moment. π And the special id focus designates whichever node currently has focus.
pathName get ?-full? ?-labels? tagnode tagnode...
Translates one or more ids into their node entry names, and returns a list of names for every id you specified. Set the -full flag and you get full pathnames back instead. Set the -labels flag and you get full pathnames that use labels. π¦
Note: Except when it's called with a single node id (i.e. an integer), the result will be a list (or a list of lists when -separator isn't set).
pathName hide ?flags? tagOrId...
Hides every node matching the criteria in flags. If you don't pass any tagOrId, it just walks the entire tree. πΈ The valid flags are:
-columncol β Match name against the value of the given column. Must be used with-name, and can not use-usepath.-depthnumber β The entry must be at depth number.-exactβ Match patterns exactly. This is the default.-globβ Use global pattern matching. The matching works similar to the waystring matchdoes it.-invertβ Invert the meaning of the pattern match for-nameor-option.-maxdepthβ The entry must be at that depth or lower.-mindepthβ The entry must be at that depth or higher.-namepattern β The pattern to match against node names.-nocaseβ Ignore case in the match.-optionname 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 thingregexpimplements.-uselabelβ Says the-namepattern is meant to match the label.-usepathβ Says the-namepattern is meant to match the full path.-withouttagNAME β Match entries with tag.-withtagNAME β Match entries with tag.--β Indicates the end of flags.
pathName index ?-at tagOrId? ?-path? ?-quiet? string
Returns the id of the node that string points at. string can be a tag or a node id. Some of the special ids are normally relative to whichever node has focus, but the -at option lets you change that. The -path flag does the lookup treating string as a path relative to the tree root (unless -at is given, of course). And if you pass the -quiet flag, lookup failures just quietly return the empty string instead of making a whole scene. π€«
pathName insert position ?path? ?path? ... ?options...?
Inserts one or more nodes at child position β which is a number, or end β inside the parent node. The parent node is either root or whatever value you gave to -at. You get back a list of ids for all the new entries. Oh, and heads up: only the first path may start with a dash. β
Path is the pathname of the new node. By default, pathnames are a Tcl list (each element is a path component) β but bestie, the -separator option can change that whole vibe. Pathnames are normally relative to the root, except the -at switch lets you pick a different parent node. If path is omitted, it defaults to #auto. A path name of #auto will generate a name β and it tries to use the tree node name as the path name. π«
If the last component of a path name ends in #auto, the path gets generated using the string prefix (everything before #auto) followed by a sequential number that's unique within the parent, like:
.t insert end {users u#auto}
Note that all ancestors of the new node must already exist, unless the -autocreate option is set. It's also an error if a node already exists, unless the -allowduplicates option is set. π
For large flat trees, setting -allowduplicates to true can greatly speed up loading #auto because it skips the checking overhead. This is the fastest way to bulk load large numbers of nodes (next to using -tree). Periodt. π₯
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. The default is root.-nodenum β The-nodeswitch 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 β The-stylesswitch specifies a list of column/stylename pairs to set for entries having a-dataoption.-tagslist β The-tagsswitch specifies a list of tags to add to the new entries.
π move β the glow-up relocation
pathName move tagnode how destId
Moves the node(s) given by tagnode to the destination node. The node can not 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.
π nearest β where my mouse at
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, it's 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 on. 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. π―
π open β let the children out
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. πΈ
π range β the in-between
pathName range ?-open? first last
Returns the ids in depth-first order of the nodes between the first and last ids. If the -open flag is present, it means consider only open nodes. If last is before first, then the ids are returned in reverse order. π
π±οΈ scan β the drag-and-scan moment
pathName scan option args
This command implements scanning. 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 together with laterscan dragtocommands. Typically this command 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.
π see β bring them into view
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. The node's position on the screen can be set using the -anchor flag. Its value is w, but it can be any one of the Tk anchor positions. π
β¨ selection β the chosen ones
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 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. π§Ή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's 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, from the selection. If a node is currently selected, it becomes deselected, and vice versa.
π«£ show β un-hide, come back bestie
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. π
π sort β put it in order
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 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 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.
Alright bestie, still deep in TREEVIEW OPERATIONS β here come the rest of the sort flags π
-decreasing booleanβ tells it to sort ascending or descending. If boolean is true, entries come out in descending order. Default isno.-mode stringβ how it compares entries while sorting. String can be any one of these, no cap:asciiβ plain string comparison, using the ASCII collation order.dictionaryβ dictionary-style comparison. Same asasciiexcept (a) case is ignored unless it's a tie-breaker, and (b) if two strings have embedded numbers, those numbers compare as integers, not characters. So"bigBoy"sorts between"bigbang"and"bigboy", and"x10y"sorts between"x9y"and"x11y". numbers just make sense now β¨integerβ compares fields as integers.realβ compares fields as floating point numbers.commandβ uses the Tcl proc you gave to the-commandoption to compare entries while sorting. If no command is specified, the sort quietly reverts todictionarysorting. π
-setflat boolβ this one exists purely soSortColumncan remember whether the tree got forced flat by a sort. iykyk.
pathName sort once ?flags? tagOrId...
Sorts the children for each entry specified by tagOrId. By default entries sort by name, but you can hand it a Tcl proc and do your own comparisons, main character style.
-recurseβ recursively sort the whole entire branch, not just the children. go deep or go home π¦
β¨ style β because data deserves a glow-up β¨
Styles control how data gets rendered by the widget. You make them with the create subcommands (described below). There's a builtin default style named text β it's of type textbox and it's the default style for columns. Styles can also be applied to entries, to individual cells, or to widget options. For example, the -altstyle option applies a style to every second visible row entry, while -levelstyles lets you give each node level its own different style. a whole outfit change per level, obsessed
Here are all the operations available for treeview styles:
pathName style activate ?entry? ?column?β get or set a particular cell's state to active. With two arguments it sets the current cell to active. With no arguments it returns the active cell. With one argument whose entry is0, it sets no cell to active.pathName style cget stylename optionβ returns the current value of the configuration option given by option. Option can be anything accepted by theconfigureoperation 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 the available options for pathName (peepTk_ConfigureInfofor the format of that list). If option is specified with no value, it returns a list describing that one named option β and that list will be identical to the corresponding sublist of the value you'd get if no option was specified. If one or more option-value pairs are specified, then it modifies the given widget option(s) to have the given value(s), and in that case the command returns an empty string. Option and value are described below:pathName style create ...?β creates a named style. For the 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. π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 stylewindowboxsupports embedding subwindows inside data cells. πͺβ¨
pathName style find stylename ?column? ?node? ...β gets all entries with the given style, for a given column, in the given nodes. When no column is given, it looks in entry and data columns. Duplicates are not eliminated. cell.pathName style forget stylename ...β eliminates one or more style names whose reference count has 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 the styletextis always greater than zero, so that one's not going anywhere.pathName style get column tagoridβ returns the style(s) for column and nodes. cell.pathName style highlight stylename ?on|off?β turns highlighting on/off 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β gets the priority style for the given cell.pathName style set stylename column node ...β sets a style for a given column for all the ids given. If column is thetree, it sets the entry style; otherwise it sets the style in the data column, which means it sets the style for a single cell in an entry. Stylename may be an empty string to unset the style. Cells that don't have a value can't have a style set, so they're silently ignored. It returns the number of cells that actually got set with a style.pathName style slaves ?-col col? ?-id node? ?-style styleName? ?-visible bool? ?-info path?β with no arguments, lists all embedded window slaves. The-colargument shows only windows in the given column. The-idargument shows only windows for the given entry. The-styleargument shows only windows with the given style. The-visibleargument shows only windows that are visible or invisible. The-infoargument dumps all information for a single window.pathName style type ?name? ?newtype?β with no arguments, returns a list of all available styles. With one argument, returns the style type of name. With two arguments, changes the style type of name to newtype, and resets all style options back to their defaults. a full rebrand, slaypathName style use stylenameβ returns the use count for a style. Note: to remove a style withstyle forget, this count has to be0. π₯
π tag β tagging it so you can find it later
Tags are a general way to select and mark nodes in the tree. A tag is just a string of characters, and it can take basically any form except that of an integer. The same tag can be associated with many different nodes, no jealousy.
Both operation and its arguments determine the exact behavior of the command. Here are the operations available for tags:
pathName tag add string ?id...?β adds the tag string to one or more entries. If no nodes are given, it 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, returns1(or0) depending on whether that entry has (or hasn't) the tag. Otherwise, returns1if at least one entry has the tag string.pathName tag forget stringβ removes the tag string from all entries. It's not an error if no entries are tagged as string. no stress πpathName tag names ?id?β returns a list of tags used. If an id argument is present, only the tags used by the node designated by id come back.pathName tag nodes name ?name ...?β returns a list of ids that have any of the name tags. If no node is tagged as name, you get an empty list back. π
pathName toggle tagnode
Opens or closes the node given by tagOrId. And if the matching -opencommand or -closecommand option is set, that command gets invoked too. double the action, double the fun
pathName xview args
This one is for querying and changing the horizontal position of the information in the widget's window. It can take any of these forms:
pathName xviewβ returns a list with two elements. Each element is a real fraction between0and1, and together they describe the horizontal span that's visible in the window. So for example, if the first element is.2and the second is.6, then 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 exact same values passed to scrollbars via the-xscrollcommandoption. math but make it visible πpathName xview tagOrIdβ shifts the view so the character position tagged by tagOrId lands at the left edge of the window. And how do we even measure "character positions"? By the width of the character0. That's the unit. That's the vibe. πpathName xview moveto fractionβ moves the view so that fraction of the total width of the treeview widget's text is off-screen to the left. And fraction has to be a fraction between0and1, bestie, no chaos allowed.pathName xview scroll number whatβ shifts the view left or right based on number and what. number must be an integer. what must be eitherunitsorpages, or any abbreviation of one of those. If what isunits, the view slides left or right by number character units (aka the width of the0character) on the display. If it'spages, then the view adjusts by number screenfuls. Negative number? Characters farther to the left become visible. Positive number? Characters farther to the right become visible. Simple as. β¨
π¦ yview, the vertical one π¦
pathName yview ?args? β this command queries and changes the vertical position of the text in the widget's window. It can take any of these forms:
pathName yviewβ returns a list with 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's 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 literally the same values passed to scrollbars via the-yscrollcommandoption. no cap. π«ΆpathName yview tagOrIdβ adjusts the view 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. math girlies rise π§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'spages, the view adjusts by number screenfuls. Negative number β earlier nodes become visible. Positive number β 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 entries -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 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.
π 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 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 affect 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. π-hiderootboolean β when boolean is true, bestie, the root node just... doesn't get an entry. No row for the root, periodt. Default isno.-highlightbackgroundcolor β the normal color of that traversal highlight region, for when the widget is NOT holding the input focus. Yes, it still gets dressed up even when nobody's looking π«Ά-highlightcolorcolor β the color of the traversal highlight rectangle when the widget does have the input focus. Default isblack.-highlightthicknesspixels β how wide that focus highlight rectangle is. pixels can take any of the formsTk_GetPixelsaccepts. If it's zero, no focus highlight shows up at all. Default is2.-iconsimages β the images for an entry's icon. images is a list of two Tk images: image #1 shows when the node is open, image #2 when it's closed π¦-imagecmdscriptcmd β 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 the same way asfind -exec, with the image name as the value (%V). The called command can either modify the image or set a new icon.
The whole point of -imagecmd is loading images on demand, like, as they become visible for the first time. To use it you set an icon option with a placeholder image, and when that placeholder first becomes visible, the callback swaps it out for the real one. The callback can also add tags, styles, or even dynamically load data, eg.:
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]
}
-inlinedatabool β enables the behaviour where data column values that start with an@and are a list of length 2 get interpreted as an inline style or image name. If the value is the name of an image, a style gets created using the name of that image with-iconset to it. A style is applied to the cell in the manner ofstyle set. Default istrueβ¨-insertfirstnumβ on inserts, do a forward search of the tree label for num elements, then fall back to a reverse search. Default is1, which gives you very fast insertions at the beginning or near the end of really long trees. Set it to-1for forward search only β say, if you're using-allowduplicates.-leaficonsimages β the images for a leaf entry's icons. images is a list of two Tk images: the first is displayed when the node is open, the second when it's closed. (Yes, same deal as-icons, but for the leaves π)-levelpadpixels β indentation added when displaying sub-tree levels. Gotta have that visual hierarchy, iykyk.-levelstylesstylenames β a list of styles to use for entries at a given level. First style = entries at level 1, second = level 2, and so on. It's the easy way to color entries by level without explicitly setting entry options on every single one π-linecolorcolor β the color of those connecting lines drawn between entries. Default isblack.-linespacingpixels β how many pixels of spacing go between entries. Default is0.-linewidthpixels β the width of the lines drawn connecting entries. If pixels is0, no vertical or horizontal lines get drawn. Default is1.-minheightpixels β the minimum height for entries. Default is0.-nextautonumβ for inserts at the root node, this is the start number for the next#autoinsert. It gets automatically incremented on each insert, which speeds up bulk#autoinserts. Go off, bulk inserts π₯-nextsubautonumβ for inserts that are not into the root node, the number the next child#autoinsert starts its search from. Default is1.-newtagsboolean β if boolean is true, when you're sharing a tree object (peep the-treeoption), don't share its tags too. Default is0.-noautocloseleafboolean β if boolean is true, then 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. Important distinction, bestie, don't sleep on it.-nofocusselectbackgroundcolor β background select color when focus is lost.-nofocusselectforegroundcolor β foreground select color when focus is lost.-openanchorstring β when a node with children gets opened, this defines the-anchorused for theseesub-command. Must be one of:n,c,s. Default isc.-opencommandstring β a Tcl script to invoke when a node is open. You can override this for individual entries with the entry's own-opencommandconfiguration option. Default is"". Percent substitutions get performed on string before it's executed, and here's the valid set:%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.
-padxpixels β padding on the left and right of the widget.-padypixels β padding on the top and bottom of the widget.-reliefrelief β the 3-D effect for the widget. relief says how the treeview should appear relative to whatever widget it's packed into; like,raisedmeans the treeview looks like it's protruding. Default issunken.-resizecursorstring β the cursor to use on resize.-rootnodenum β the node number that should be the root. This lets a subtree show up as the root. Multiple treeviews can share one tree with different root nodes, which is how you get subviews π Default is0.-scrollmodemode β the style of scrolling to use. There are three 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.
-scrolltilebool β specifies if the tiling should scroll with the widget. Default isfalse.-selectbackgroundcolor β the background color of selected node entries. Default is#ffffea.-selectborderwidthpixels β the width of the raised 3-D border drawn around the labels of selected entries. Default is0.-selectcommandstring β a Tcl script to invoke when the set of selected nodes changes. Default is"".-selectforegroundcolor β the color of the labels of selected node entries while the widget has focus. Default isblack.-selectmodemode β the selection mode, babes. 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.-selectreliefrelief β 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.-selecttileimage β set a tile background image to use for selection. Aesthetic? Immaculate. πΈ-separatorstring β the character sequence used when splitting path components. The separator may be several characters wide (like"::"). Consecutive separators in a pathname are treated as one. If string is the empty string, the pathnames are Tcl lists. If string isnone, no splitting is done. Each element is a path component. Default is"".-showfullboolean β show the full path name when in-flatmode. Default istrue.-showtitlesboolean β if boolean is false, column titles are not displayed. Default isyes.-sortselectionboolean β 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.-stylecommandstring β a Tcl command to handle references to unknown styles. The call performs the same substitutions as the-execoption in thefindcommand, 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 happens for any style used in the configure subcommands. It also handles inline data of the form for the image passed after the @ sign (peep the -inlinedata option).
-substylestylename β a style for use with the-sublabel. Note: you can hide all sublabels by using a style with the-hideoption set. Sneaky, but iconic π-takefocusfocus β info used when moving focus from window to window via keyboard traversal (think 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 decide whether to focus on the window. Default is"1".-tileimage β set background tile image.-titlefontfont β the font to use for titles.-titlepadN β pad to add above and below the title.
-treetree β bestie, you can plug in a data tree object you made yourself, externally. Using a tree command makes data access, tracing, and loading/saving all so much easier. Obsessed. Like:
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
-trimstring β names a string of leading characters to trim off entry pathnames before parsing them. Ngl this only makes sense if-separatoris also set. Default is"".-underlineheight β draws an underline of the given height below every entry, stretching across its entire width. Team it up with column reliefs and you get a whole grid-like effect β¨ Default height is0.-widthpixels β sets the requested width of the widget. If pixels is0, the width gets computed from the contents of the treeview widget instead. Default is200.-xscrollcommandstring β the prefix for a command used to talk to horizontal scrollbars. Whenever the horizontal view in the widget's window changes, the widget builds a Tcl command by concatenating the scroll command with two numbers. If you don't set this option, no command runs at all.-xscrollincrementpixels β sets the horizontal scrolling distance. Default is20pixels.-yscrollcommandstring β the prefix for a command used to talk to vertical scrollbars. Whenever the vertical view in the widget's window changes, the widget builds a Tcl command by concatenating the scroll command with two numbers. If you don't set this option, no command runs at all.-yscrollincrementpixels β sets the vertical scrolling distance. Default is20pixels.
π ENTRY OPTIONS π
Okay so here's the tea β β a lot of widget configuration options have twins living down at the entry level. Like, there's a -closecommand option for the widget itself and for individual entries. Options set at the widget level are global, applying to all entries. But if the entry-level configuration option is set, it overrides the widget option. Why? To avoid wasting memory by replicating options everywhere. So yeah, most entries are gonna have redundant options chilling there. It's giving efficiency, honestly.
Heads up: there is no resource class or name for entries.
-activeiconsimages β the images shown as the entry's icon when it's active. Overrides the global-activeiconsconfiguration option for this specific entry. Images is a list of two Tk images: the first one shows when the node is open, the second when it's closed. π-bindtagstagList β sets the binding tags for nodes. TagList is a list of binding tag names. The tags and their order decide how events get handled for nodes. Every tag in the list that matches the current event sequence gets its Tcl command executed. Default value isall.-buttonstring β says whether a button should show up on the left side of the node entry. String can beyes,no, orauto. If it'sauto, a button automatically appears if the node has children.autois the default, bestie.-closecommandstring β a Tcl script to invoke when the node is closed. Overrides the global-closecommandoption for this entry. Default is"". Percent substitutions get performed on string before it runs. The valid substitutions are:%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.
-datalist β initializes or changes data fields for the node. List is a list of name-value pairs to set. Note that this can not be used to unset or forget values for columns, meaning an empty list does absolutely nothing. For unsetting, useentry unsetinstead. Default is"".-fontfontName β sets the font for the entry row text. Overrides the widget's-fontoption for this node.-forcetreebool β forces the node to be treated as a tree, even if it has no children. This differs from-buttonabove because all drawing and querying aspects of the node get treated as a tree. Mostly useful for deferring loading until a tree is opened. Default isfalse.-foregroundcolor β sets the text color of the entry label. Overrides the widget's-foregroundconfiguration option. Default is"".-heightnum β set height for entry.-hidebool β hide the entry.-iconsimages β the images displayed for the entry's icon. Overrides the global-iconsconfiguration option. Images is a list of two Tk images: the first shows when the node is open, the second when it's closed. π¦-isopenbool β specify whether the entry is in the open state. Default isfalse.-labelstring β sets the text for the entry's displayed label. If set to"", the label of the tree node is displayed instead. Default is""(seeentry relabel).-opencommandstring β a Tcl script to invoke when the entry is opened. Overrides the widget's-opencommandoption for this node. Default is"". Percent substitutions get performed on string before it runs. The valid substitutions are:%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.
-shadowcolor β set shadow color for text.-statevalue β sets the state of the entry, where value is one of:normal,active,disabled. The default state isnormal. When the state isdisabled, the text color displays using-disabledforegroundand the node straight-up ignores any attempted open or close. No cap π-stylestylename β sets the style to use for the entry. This overrides the column style, just like howstyle setoverrides an entry style. Mostly useful for setting bg/fg/font for a row. Other options may or may not do nothing. Note that setting icon in a style applies to all value columns, but not the tree column.-sublabelstring β sets the text for the entry's sub-label, displayed to the right of the node's-labelvalue. Rendered using the-substylestyle.-underlinenum β the character to underline in an entry's text label. Default is-1.-userdatalist β extra space available for storing user data. πΈ
π BUTTON OPTIONS π
Button configuration options can also be set with the option command. The resource subclass is Button. The resource name is always button. Periodt.
option add *TreeView.Button.Foreground white
option add *TreeView.button.Background blue
Here's every configuration option available for buttons, bestie:
-activebackgroundcolor β sets the background color of active buttons. A button becomes active when the mouse passes over it or via thebutton activateoperation.-activeforegroundcolor β sets the foreground color of active buttons. A button becomes active when the mouse passes over it or via thebutton activateoperation.-activeimagesimages β specify images to use for active buttons.-backgroundcolor β sets the background of the button. Default iswhite.-borderwidthpixels β sets the width of the 3-D border around the button. The-reliefoption determines whether a border is drawn at all. Default is1.-closereliefrelief β specifies the 3-D effect for the closed button. Relief indicates how the button should appear relative to the widget; for example,raisedmeans the button should appear to protrude. Default issolid.-cursorcursor β sets the widget's cursor. Default cursor is"".-foregroundcolor β sets the foreground color of buttons. Default isblack.-imagesimages β the images displayed for the button. Images is a list of two Tk images: the first shows when the button is open, the second when it's closed. If images is the empty string, then a plus/minus gadget gets drawn. Default is"".-openreliefrelief β specifies the 3-D effect of the open button. Relief indicates how the button should appear relative to the widget; for example,raisedmeans the button should appear to protrude. Default isflat.-sizepixels β sets the requested size of the button. Default is0. π
β¨ STYLE OPTIONS β¨
okay bestie, this is the lewk section and I'm obsessed π
There are five style types available: textbox, combobox, checkbox, barbox, windowbox. Autocreated styles are by default of type textbox. A barbox provides progressbars for numeric cell values. The special style windowbox supports embedded subwindows within data cells.
The resource subclass is 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 text comes predefined and is set for each columns -style option. Styles may also be associated with entry-rows and/or cells, as follows:
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
See also the widget options -altstyle, -emptystyle and -levelstyles.
The following are available for all but the windowbox type. Note, some of these options are utilized only in particular contexts:
-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 0.-readonlybool β Disallow editing for a cell whose column has-editset to true. The default isFalse.-shadowshadow β Set shadow.-tileimg β Set tiling.
π textbox, but make it extra
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 perfind -exec. The called command returns the value to be displayed.-iconsideN β Specifies which side of the text the icon is placed. Default isleft.-sideN β Specifies which side of cell to anchor contents. Default istop.
π combobox, but make it extra
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, but make it extra
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, but make it extra
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 isgreen.-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 perfind -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, the main character
Only the following configuration options are available with windowbox:
-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 thegridcommand. 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.
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 iswhite.-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 byinvoke. 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 thatSortColumncan 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 isTruethe 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 thefBtextbox(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'sTrue, the edit window gets managed internally through an embedded windowbox-style setup. When it'sfalse,placeis what manages the window. Default?False. An embedded window has its perks but it means a re-layout at the start and end of editing. Heads up bestie:placeis always used for the tree column. π-endcmdcmd β the command to call at the end of an edit, after the new value is set. If a percent is found in there, command substitution happens; otherwise the call appends 5 args:widget data olddata ind col.-leafsbool β limits editing to leafs only. Default isfalse. π-nlkeysopt β the keys for inserting a newline in multiline edits. Default value is:<Control-r> <Shift-Return>.-nottnullbool β don't edit empty fields that never had data assigned to them. Default isfalse.-optscmdcmd β command called to get options. It's called with 3 args:widget ind col. Returns name/value pairs, which are extra options as accepted by-editopts. Wanna flag a cell as non-editable? Return{-readonly True}.-readonlybool β cell is readonly. Do not edit. Periodt. π«-selbool β value is initially selected in the edit window. Default istrue.-startcmdcmd β command to call at the start of an edit. If a percent is found, command substitution happens; otherwise the 3 args get appended:widget ind col.-tabopts β sets up a bind forTabin the edit window (a bool, or args passed toTabMove).-titlesbool β enable editing of the title label. Default isfalse.-treelabelbool β edit the-treecmd label instead of the treeview label. Default istrue.-typebool β a basic wize type, e.g.bool,int,choice.-typecolcolumn β column/key to get-typefrom.-vcmdcmd β command to override the column's-validatecmd.-widgetwid β the widget to use. Builtin support types are:spinbox,text,entry. Default isentry.-withtagtag β edit only if it has this tag.-withouttagtag β edit only if it does not have this tag.-wrapvalue β the setting for wrap mode when the edit window is a text widget. Default isnone.
For more generalized control of editing, bind to the <<TreeViewEditStart/End>> virtual events. π
-fontfont β sets the font for the column. Right now, don't mix this with a-stylefont for the column, okay? Not the vibe. β-foregroundcolor β sets the text color of the column.-fillcmdscriptcmd β demand-load data into unset values, just before display. The call fires the first time each entry is displayed in the column. Only cells that don't have a value/label set get updated. Before calling, the id gets appended. The new value should be returned. For tree columns the result sets the entry label, otherwise it sets a data cell value. If an error is raised, the value is set to the empty string.
Here's an example that loads a big tree. It shows that only the first dozen-ish get updated initially, and more as you scroll. A practical version 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 isn't 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 gets padded by the first distance and the right side by the second. If pad has just one distance, both sides get padded evenly. 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 look like it's protruding. Default isflat.-ruledashesvalue β set the resize rule as dashed.-scrolltilebool β tile image scrolls.-sortaltcolumnslist β list of alternate columns that sort can use when cell values are equal. Including the current column or the tree column is an error. π-sortcommandscript β command to actually compare entries during a sort.-sortmodemode β used by scripts to set-modefor the sort command (e.g.blt::tv::SortColumn).-statestate β sets the state of the column. If state isdisablethen the column title can't be activated or invoked. 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. 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. Default isblack.-titlereliefrelief β relief for the title.-titleshadowcolor β sets the color of the drop shadow of the column title. Default is"".-titlestylestyle β a style to use for titles.-widthnum β the user-requested width for the column.-underlinenum β character to underline in the column title text. Default is-1.-validatecmdcommand β this option provides a command for validating or post-processing edits from the builtin column edit feature (turned on withcol conf -edit 1). If a percent is found, command substitution happens; otherwise 5 args are appended:widget data olddata ind col. The called command should return newvalue, 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. 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 provide a valid window, it's silently ignored and nothing gets displayed. 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 (i.e. it must be a child of the parent).
π«£ OLD TEXT EDITING OPTIONS π«£
SECTION OBSOLETE. This section is obsolete and has been replaced with builtin editing using a Tk entry widget. See TREEVIEW EDITING above. It's giving legacy, bestie. π
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.
-backgroundcolor β sets the background of the text edit window. Default iswhite.-borderwidthpixels β sets the width of the 3-D border around the edit window. The-reliefoption determines if a border gets drawn. Default is1.-exportselectionboolean β indicates if the text selection is exported. If the edit window is exporting its selection, it will observe the standard X11 protocols for handling the selection. Selections are available as typeSTRING. 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. Default issolid.-selectbackgroundcolor β sets the background of the selected text in the edit window. 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 gets drawn. Default is1.-selectforegroundcolor β sets the foreground of the selected text in the edit window. 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. Default isflat.
π DEFAULT BINDINGS π
okay so Tk literally auto-makes class bindings for treeviews that give them that Motif-like behavior β¨ and ngl, a LOT of how a treeview widget acts is decided by its -selectmode option, which picks one of two ways of dealing with the selection. bestie, this is the vibe check of the whole widget:
If the selection mode is single, only one node can be selected at a time. Clicking button 1 on an node selects it and deselects any other selected item. one (1) node. that's it. π
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. chaos mode, and we love her π¦
[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. (iykyk, the event fires either way, you gotta check yourself π)[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.[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. (she scrolls herself fr fr π)[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 theUporDownkey 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]β TheLeftandRightkeys 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. (a whole window of scroll, dramatic much? we stan π)[8]β ThePriorandNextkeys scroll the treeview widget view up and down by one page (the height of the window), as doesControl-uandControl-d.[9]β TheHomeandEndkeys 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. queen of starting fresh π[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]β ThespaceandSelectkeys 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, theEscapekey cancels the most recent selection and restores all the entries in the selected range to their previous selection state. undo button but make it keyboard πβ¨[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. (browse mode said "not today" π)[19]β TheF16key (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. so these are the extra lil' guys:
<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. no kids? no problem π<KeyPress-Right>β Opens the entry, displaying its children. It is not an error if the entry has no children.<KeyPress-space>β Insingleselect mode this selects the entry. Inmultiplemode, 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. typeahead girlies rise up β¨οΈβ¨<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. They are associated with the all bindtag (see the entry's -bindtag option). You can use the bind operation to change them. remix them, it's your world π₯
<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. They 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>β Formultiplemode only. Saves the current location of the pointer for auto-scrolling. Resets the selection mark.<ButtonRelease-1>β Formultiplemode only. Sets the selection anchor to the current entry.<Shift-ButtonPress-1>β Formultiplemode only. Extends the selection.<Shift-Double-ButtonPress-1>β Place holder. Does nothing. (she's just standing there. menacingly. π)<Shift-B1-Motion>β Place holder. Does nothing.<Shift-ButtonRelease-1>β Stop auto-scrolling.<Control-ButtonPress-1>β Formultiplemode 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 bestie, the docs literally just say that. iconic honestly π)<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. resize slay πβ¨
β¨ QUICKSTART β¨
ok bestie listen up, because TreeFill is literally the glow-up your data loading needed π. It's a utility function that makes loading tree data from a human-readable string SO much easier. The trick? The string uses line indentation to show tree depth. And the indentation is in multiples of 4 spaces, measured relative to the first line. iykyk π
Like, watch this:
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
Obsessed. π Any column names you didn't define? They get generated for you, no stress. And if you wanna load a flat table instead of a whole tree, just set the -flat option first, easy:
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 brand new widget, periodt.
treeview .t -bg white
A new Tcl command .t gets created too β and this command is your bestie for querying and modifying the treeview widget. For example, if you wanna change the background color of the table to "green", you use that 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 hold the data. The name of that new tree is the pathname of the widget. So above, the new tree object name is ".t". But bestie, you can use the -tree option to name a different tree if you want:
# 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, cute right?). 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 (because we used the position "end"). You can hand it another position to order the node among its siblings:
# Prepend "fred".
set id [.t insert 0 "fred"]
Entry names do not need to be unique, no cap. By default, the node's label is just its name. To give it 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 that same info:
# 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 make up the path in the tree. So you can also add "barney" to "fred" like this:
# 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 the entry "fred" is an ancestor of "barney" and has to already be there. 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 instead of being formed as a list. A file name is the perfect example of this. You can use the -separator option to specify a separator string that splits the path into its components. Each pathname you insert gets automatically split using the separator string. And multiple separators are treated as one, slay:
.t configure -separator /
.t insert end "/usr/local/tcl/bin"
If your path is prefixed by extraneous characters, you can automatically trim them off with the -trim option. It removes the string from the path before it gets 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 a bunch of configuration options. They control the appearance of the entry's icon and label. We already saw 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, and all the entries you specify get 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, and another for when it's 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 it 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, and 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 option takes a list of name-value pairs, fr fr.
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 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 says whether the column is displayed:
.t column configure "mode" -hide yes
Entries can be selected by clicking with 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 gets 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, and the treeview can scroll both horizontally and vertically. You can attach scrollbars to the treeview the same way you do with 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"
So now when an entry is opened, the procedure AddEntries gets 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 gets called and deletes the entry's children using the entry delete operation (%# is the id of the entry).
β¨ OLD TREEVIEW EDITS β¨
NOTE: This section is OBSOLETE. Native Tk widgets are now used for editing.. (yes, two dots, she's extra, we love her)
When editing the subwidget .edit is available.
pathName.edit operation ?args?
This operation is used to provide text editing for cells (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 is hidden. slay, commit that edit πpathName.edit cancelβ Cancels the editing operation, reverting the entry label or data value back to the previous value. The edit window is hidden. not me hitting undo on the whole vibe π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. (yes, the signature saysvalue, the description says option β we're just the messengers, bestie)pathName.edit configure ?option value?β Query or modify the configuration options of the edit window. If no option is specified, returns a list describing all of the available options (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 TEXT EDITING OPTIONS below.pathName.edit delete first lastβ Deletes the characters in the edit buffer between the two given character positions.pathName.edit get ?-root? x yβ (no description in the original, so just know the signature and live your truth β¨)pathName.edit icursor indexβ (no description in the original either, she's mysterious π )pathName.edit index indexβ Returns the text index of given index.pathName.edit insert index stringβ Insert the text string string into the edit buffer at the index index. For example, the index0will prepend the buffer.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.pathName.edit selection from indexβ Sets the anchor of the selection.pathName.edit selection presentβ Indicates if a selection is present.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. This is not the same thing as the node label. don't confuse the two, bestie, they're different girlies π
By default labels are checked for duplicates by insert, which can slow down large (10k+) inserts. Setting -allowduplicates to 1 disables this checking.
An entries label can be changed either by by setting -allowduplicates to 1 and using treeviews entry relabel or by using trees label command. (yes, "by by" β we kept the original typo because we keep every detail, periodt π
)
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
π NOTES π
Text cells in display height can be at most 64K pixels high per row. that's the limit, bestie, don't try to make a skyscraper row ποΈ
π KEYWORDS π
treeview, widget
Source/version: BLT 2.5. Manual page: blt::treeview(3tcl). Date: not printed on this page, but she's timeless, iconic, and lowkey always relevant. πβ¨π
π¦ where this page comes from
- debian bookworm: blt-dev 2.5.3+dfsg-4.1
- debian trixie: blt-dev 2.5.3+dfsg-8
- ubuntu jammy: blt-dev 2.5.3+dfsg-4.1build2
- ubuntu noble: blt-dev 2.5.3+dfsg-7build1
- ubuntu questing: blt-dev 2.5.3+dfsg-8
- ubuntu resolute: blt-dev 2.5.3+dfsg-8build1
- ubuntu stonking: blt-dev 2.5.3+dfsg-9
- Copyright 2001-2 by Silicon Metrics Corporation
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms