python-tktreectrl-2.0.1/0000755000175000017500000000000012052764536015106 5ustar moellermoellerpython-tktreectrl-2.0.1/doc/0000755000175000017500000000000012052764426015651 5ustar moellermoellerpython-tktreectrl-2.0.1/doc/TkTreectrl.html0000644000175000017500000001046512052764370020626 0ustar moellermoeller Python: package TkTreectrl
 
 
TkTreectrl (version 2.0)
index
./TkTreectrl/__init__.py

Main module of the TkTreectrl package.
Once the TkTreectrl package is installed, it is safe to do :
 
    from TkTreectrl import *
 
This will add a number of constants and the following widget classes to the
current namespace:
 
Treectrl, MultiListbox, ScrolledTreectrl, ScrolledMultiListbox, ScrolledWidget

 
Package Contents
       
MultiListbox
ScrolledTreectrl
Treectrl

 
Data
        ABOVE = 'above'
ACTIVE = 'active'
ALL = 'all'
AREA = 'area'
ASCII = 'ascii'
BELOW = 'below'
BITMAP = 'bitmap'
BORDER = 'border'
CANVAS = 'canvas'
COLUMN = 'column'
CONTENT = 'content'
DECREASING = 'decreasing'
DICTIONARY = 'dictionary'
DOT = 'dot'
DOUBLE = 'double'
DYNAMIC = 'dynamic'
ENABLED = 'enabled'
FIRST = 'first'
FIRSTCHILD = 'firstchild'
FOCUS = 'focus'
HEADER = 'header'
IMAGE = 'image'
INCREASING = 'increasing'
INTEGER = 'integer'
ITEM = 'item'
LAST = 'last'
LASTCHILD = 'lastchild'
LEFT = 'left'
LEFTMOST = 'leftmost'
LONG = 'long'
NEXT = 'next'
NEXTSIBLING = 'nextsibling'
NORMAL = 'normal'
OPEN = 'open'
PARENT = 'parent'
PRESSED = 'pressed'
PREV = 'prev'
PREVSIBLING = 'prevsibling'
REAL = 'real'
RECT = 'rect'
RIGHT = 'right'
RIGHTMOST = 'rightmost'
ROOT = 'root'
SELECT = 'select'
SELECTED = 'selected'
STATIC = 'static'
STRING = 'string'
TAIL = 'tail'
TEXT = 'text'
TIME = 'time'
TREE = 'tree'
WINDOW = 'window'
__package__ = 'TkTreectrl'
__version__ = '2.0'
python-tktreectrl-2.0.1/doc/Treectrl.html0000644000175000017500000055577212052764174020350 0ustar moellermoeller Python: module Treectrl
 
 
Treectrl
index
./TkTreectrl/Treectrl.py

Wrapper module for the Tk treectrl widget.

 
Modules
       
Tkinter

 
Classes
       
Tkinter.Widget(Tkinter.BaseWidget, Tkinter.Pack, Tkinter.Place, Tkinter.Grid)
Treectrl
TreectrlEvent

 
class Treectrl(Tkinter.Widget)
    A treectrl is a widget which displays items in a one- or two-dimensional
arrangement. Items have a parent-child relationship with other items. Items
have a set of states, which are boolean properties. Items may be spread
about one or more columns. For each column of an item there is a style
associated, which determines how to display the item's column taking into
account the item's current state set. One column can be defined to display
the data in a hierarchical structure.
Normally the origin of the coordinate system is at the upper-left corner of
the window containing the treectrl. It is possible to adjust the origin of
the coordinate system relative to the origin of the window using the
xview() and yview() widget commands; this is typically used for scrolling.
A treectrl widget can be horizontal or vertical oriented like many other Tk
widgets. For displaying hierarchical data only vertical orientation is
useful, since only then the children of an item are displayed directly
below their parent. If the treectrl widget is used only to display data in
a multicolumn listbox, the specification of an orientation will give useful
results.
 
STANDARD OPTIONS
-background
-borderwidth
-cursor
-font
-highlightbackground
-highlightcolor
-highlightthickness
-orient
-relief
-takefocus
-xscrollcommand
-yscrollcommand
-foreground
 
WIDGET SPECIFIC OPTIONS
-backgroundimage
    Specifies the name of an image to draw as the list background. The
    image is tiled horizontally and vertically to fill the content area of
    the list. If the image is transparent it is drawn on top of the
    background color(s).
-backgroundmode
    Specifies how the background color of items is chosen in each column.
    The value should be one of row, column, order, or ordervisible. The
    default is row. This option has only an effect for columns which have
    -itembackground defined as list of two or more colors (see section
    COLUMNS below for more on this). If row or column is specified, the
    background color is chosen based on the location of the item in the
    1- or 2-dimensional grid of items as layed out on the screen; this
    layout of items is affected by the -orient and -wrap options as well as
    item visibility. When order or ordervisible is specified, the
    background color is chosen based on the result of the item order
    command, regardless of the layout of items.
-bgimage
    Synonym for -backgroundimage (since 2.3)
-bgimageanchor
    Controls the alignment of the -backgroundimage.  The value is a
    standard Tk anchor position such as "nw", "se" or "center", etc.
    The image is aligned to the content area when the image doesn't scroll,
    otherwise the image is aligned to the canvas.  The default is "nw".
-bgimageopaque
    A boolean that indicates whether or not the -backgroundimage is
    partially transparent.  This is needed because there is no way to tell
    in Tk whether an image contains transparency.  The default is True, so
    if you use a transparent -backgroundimage you must set this to False.
-bgimagescroll
    Controls whether the -backgroundimage scrolls along with the items or
    remains locked in place. The value can be an emptry string for no
    scrolling, "x" for horizontal scrolling only, "y" for vertical
    scrolling only, or "xy" (the default) for scrolling in both directions.
-bgimagetile
    Controls whether the -backgroundimage is tiled along the x and y axes.
    The value can be "", "x", "y" or "xy" (the default).
-buttonbitmap
    Specifies the bitmap to be used as the expand/collapse button to the
    left of an item. This is a per-state option. If a bitmap is specified
    for a certain item state, it overrides the effects of -usetheme.
-buttoncolor
    Specifies the foreground color which should be used for drawing the
    outline and the plus or minus sign of the button to the left of an
    item.
-buttonimage
    Specifies the image to be used as the expand/collapse button to the
    left of an item. This is a per-state option. If an image is specified
    for a certain item state, it overrides the effects of -buttonbitmap and
    -usetheme.
-buttonsize
    Specifies the width and height of the button drawn to the left of an
    item in any of the forms acceptable to Tk_GetPixels.
-buttonthickness
    Specifies the width of the outline and the plus or minus sign of the
    button to the left of an item in any of the forms acceptable to
    Tk_GetPixels.
-buttontracking
    On Mac OS X and Gtk+ the expand/collapse buttons don't toggle when they
    are clicked, only when the mouse button is released over them, like
    regular pushbuttons.  The value of this option is a boolean; when True
    the buttons toggle when the mouse button is released, when False the
    buttons toggle when clicked.  The default is True on Mac OS X and
    Gtk+, False on Win32 and X11.
-canvaspadx
-canvaspady
    These options allow whitespace margins around the edges of the canvas.
    This is useful for 2D views where you don't want the items to butt
    against the window borders.  The value of each option is a list of one
    or two screen distances specifying the width of the left/right margins
    and the height of the top/bottom margins respectively.
-columnprefix
    Specifies an ascii string that changes the way column ids are reported
    and processed. If this option is a non-empty string, the usual integer
    value of a column id is prefixed with the given string. This can aid
    debugging but it is important your code doesn't assume column ids are
    integers if you use it.
-columnproxy
    If this option specifies a non empty value, it should be a screen
    distance in any of the forms acceptable to Tk_GetPixels. Then a 1 pixel
    thick vertical line will be drawn at the specified screen distance from
    the left edge of the treectrl widget, which reaches from top to bottom
    of the treectrl widget and uses an inverting color (i.e black on
    lighter background, white on darker background). This line can be used
    to give the user a visual feedback during column resizing.
-columnresizemode
    Specifies the visual feedback used when resizing columns. The value
    should be one of proxy or realtime. For proxy, a 1-pixel thick vertical
    line is drawn representing where the right edge of the column will be
    after resizing. For realtime, the column's size is changed while the
    user is dragging the right edge of the column.
    Since treectrl-2.3 the default value is "realtime",
    in earlier versions it used to be "proxy".
-columntagexpr
    Specifies a boolean that enables or disables tag expressions in column
    descriptions.
    When the value of this option is False the characters (', ')', '&',
    '|', '^' and '!' have no special significance when using tags in column
    descriptions. This is useful for applications which may have arbitrary
    tags applied to columns or items.
-defaultstyle
    Specifies a list of styles, one per column, to apply to each item
    created by the item create command. The number of styles in the list
    can be different from the number of tree columns. Each list element
    should be a valid style name or an empty string to indicate no style
    should be applied to a specific column. The list of styles is updated
    if a style is deleted or if a column is moved.
    This option is deprecated since treectrl-2.2, use
    column_configure(itemstyle=...) instead.
-doublebuffer
    Specifies if double-buffering should be used to improve displaying. The
    value should be one of none, window, or item. For none no
    double-buffering is used at all, which may be most memory efficient,
    but will probably generate some flickering on the screen. For window
    the complete tree is double-buffered, which requires a buffer big
    enough to contain the complete widget. For item, which is the default,
    every item is separately double-buffered, so it works with a buffer
    size as big as the biggest item.
    This option has no effect since tktreectrl-2.2.10 .
-headerfont
    This is the font used for drawing text in column headers. The default
    value is TkHeadingFont where that font is defined (usually on Tk 8.5+),
    otherwise it is the default listbox font.  On Mac OS X, TkHeadingFont
    is the small system font used for drawing text in the fixed-height
    headers. This new option results in a different default look to column
    text on X11, where TkHeadingFont is a bold font.
-headerfg
-headerforeground
    The foreground text color used when drawing text in column headers.
    On Gtk+, the system theme may override this color.
-height
    Specifies the desired height for the window in any of the forms
    acceptable to Tk_GetPixels. The default is 200 pixels. If this option
    is less than or equal to zero then the window will not request any
    size at all.
-indent
    Specifies the amount of indentation in any of the forms acceptable to
    Tk_GetPixels. The default is 19 pixel. Indentation is the screen
    distance an item is displayed more to the right than its father.
-itemgapx
-itemgapy
    These options allow whitespace gaps between adjacent items. This is
    useful for 2D views such as an icon view in a file browser or an image
    thumbnail list.  The value of each option is a screen distance
    defaulting to zero.
-itemheight
    Specifies a fixed height for every item in any of the forms acceptable
    to Tk_GetPixels. If non-zero, this option overrides the requested
    height of an item and the -minitemheight option. The default is 0,
    which means that every item has the height requested by the
    arrangement of elements in each column. Items are never shorter than
    the maximum height of a button.
-itemprefix
    Specifies an ascii string that changes the way item ids are reported
    and processed. If this option is a non-empty string, the usual integer
    value of an item id is prefixed with the given string. This can aid
    debugging but it is important your code doesn't assume item ids are
    integers if you use it.
-itemtagexpr
    Specifies a boolean that enables or disables tag expressions in item
    descriptions.
    When the value of this option is False the characters (', ')', '&',
    '|', '^' and '!' have no special significance when using tags in item
    descriptions. This is useful for applications which may have arbitrary
    tags applied to columns or items.
-itemwidth
    Specifies a fixed width for every item in any of the forms acceptable
    to Tk_GetPixels. If more than one column is visible, then this option
    has no effect. If the -orient option is vertical, and the -wrap
    option is unspecified, then this option has no effect (in that case
    all items are as wide as the column).
-itemwidthequal
    Specifies a boolean that says whether all items should have the same
    width. If more than one column is visible, then this option has no
    effect. If the -orient option is vertical, and the -wrap option is
    unspecified, then this option has no effect (in that case all items are
    as wide as the column). If the -itemwidth option is specified, then
    this option has no effect.
-itemwidthmultiple
    Specifies a screen distance that every item's width will be evenly
    divisible by in any of the forms acceptable to Tk_GetPixels. If more
    than one column is visible, then this option has no effect. If the
    -orient option is vertical, and the -wrap option is unspecified, then
    this option has no effect (in that case all items are as wide as the
    column).
    If the -itemwidth option is specified, then this option has no effect.
-linecolor
    Specifies the color which should be used for drawing the connecting
    lines between related items.
-linestyle
    Specifies the style of the connecting lines between related items,
    should be dot which is the default, or solid.
-linethickness
    Specifies the thickness of the connecting lines between related items
    in any of the forms acceptable to Tk_GetPixels.
-minitemheight
    Specifies a minimum height for every item in any of the forms
    acceptable to Tk_GetPixels. The default is 0, which means that every
    item has the height requested by the arrangement of elements in each
    column. This option has no effect if the -itemheight option is
    specified. Items are never shorter than the maximum height of a button.
-scrollmargin
    The interpretation of this option is left to Tcl scripts that implement
    scrolling: the widget implementation ignores this option entirely.
    Defaults to 0.
-selectmode
    Specifies one of several styles for manipulating the selection. The
    value of the option may be arbitrary, but the default bindings expect
    it to be either single, browse, multiple, or extended; the default
    value is browse.
-showbuttons
    Specifies a boolean value that determines whether this widget displays
    a button to the left of any item. If the button is actually drawn can
    be configured for every item with the item hasbutton widget command,
    but if this option is set to false, the configuration of an item has
    no effect. The default value is True.
-showheader
    Specifies a boolean value that determines whether this widget should
    display the header line with the column names at the top of the widget.
    The default value is True.
-showlines
    Specifies a boolean value that determines whether this widget should
    draw the connecting lines between related items.
    In versions prior to trectrl-2.3 the default value was True. Since 2.3
    the default value is False on Mac OS X and Gtk+, True on Win32 and X11.
-showroot
    Specifies a boolean value that determines whether this widget should
    draw the root item. By suppressing the drawing of the root item the
    widget can have multiple items that appear as toplevel items.
    The default value is True.
-showrootbutton
    Specifies a boolean value that determines whether this widget should
    draw a button before the root item. The default value is False.
-showrootchildbuttons
    Specifies a boolean value that determines whether this widget should
    draw the expand/collapse buttons next to children of the root item.
    The default value is True.
-showrootlines
    Specifies a boolean value that determines whether this widget should
    draw the connecting lines between children of the root item.
    The default value is True.
-treecolumn
    Specifies a column description that determines which column displays
    the buttons and lines. The default is unspecified.
-usetheme
    Specifies a boolean value that determines whether this widget should
    draw parts of itself using a platform-specific theme manager.
    Since treectrl-2.3 the default value is now True, in earlier versions
    the default used to be False.
-width
    Specifies the desired width for the window in any of the forms
    acceptable to Tk_GetPixels. The default is 200 pixels. If this option
    is less than or equal to zero then the window will not request any size
    at all.
-wrap
    Specifies whether items are arranged in a 1- or 2-dimensional layout.
    If the value is an empty string (the default), then items are arranged
    from top to bottom (orient='vertical') or from left to right (orient=
    'horizontal') in a 1-dimensional layout. If the value is "N items",
    then no more than N items will appear in a vertical group
    (orient='vertical') or horizontal group (orient='horizontal').
    If the value is "N pixels", then no vertical group of items will be
    taller than N pixels (orient='vertical') or no horizontal group of
    items will be wider than N pixels (orient='horizontal').
    If the value is "window", then no vertical group of items will be
    taller than the window (orient='vertical') or no horizontal group of
    items will be wider than the window (orient='horizontal').
-xscrolldelay
    Specifies the amount of time before the default binding should handle
    repeating mouse motion events in horizontal direction with button 1
    pressed. The value should be a sequence of 1 or 2 integers. The first
    integer specifies the timespan in microseconds before the active item
    should be changed to get nearer to the current mouse position.
    If there are two integers specified, the first is only used for the
    first motion event, any repeating motion events are handled after the
    seconds amount of miliseconds is elapsed.
-xscrollincrement
    Specifies an increment for horizontal scrolling, in any of the usual
    forms permitted for screen distances. If the value of this option is
    greater than zero, the horizontal view in the window will be
    constrained so that the x coordinate at the left edge of the window
    is always an even multiple of -xscrollincrement; furthermore, the
    units for scrolling (e.g., the change in view when the left and right
    arrows of a scrollbar are selected) will also be -xscrollincrement.
    If the value of this option is less than or equal to zero, then
    horizontal scrolling is unconstrained.
-xscrollsmoothing
-yscrollsmoothing
    When these options are set to true and the xview or yview commands are
    called to scroll by "units", scrolling occurs according to the
    -xscrollincrement or -yscrollincrement options, and all other
    scrolling is done as if the -xscrollincrement or -yscrollincrement
    options were set to 1.  The effect is that when dragging the scrollbar
    thumb scrolling is very smooth, but when clicking the scrollbar
    buttons scrolling is done in coarser increments.
-yscrolldelay
    Specifies the amount of time before the default binding should handle
    repeating mouse motion events in vertical direction with button 1
    pressed. The value should be a list of 1 or 2 integers. The first
    integer specifies the timespan in microseconds before the active item
    should be changed to get nearer to the current mouse position. If there
    are two integers specified, the first is only used for the first motion
    event, any repeating motion events are handled after the seconds amount
    of miliseconds is elapsed.
-yscrollincrement
    Specifies an increment for vertical scrolling, in any of the usual
    forms permitted for screen distances. If the value of this option is
    greater than zero, the vertical view in the window will be constrained
    so that the y coordinate at the top edge of the window is always an
    even multiple of -yscrollincrement; furthermore, the units for
    scrolling (e.g., the change in view when the top and bottom arrows
    of a scrollbar are selected) will also be -yscrollincrement. If the
    value of this option is less than or equal to zero, then vertical
    scrolling is unconstrained.
 
  Data and other attributes defined here:
TreectrlVersion = None

Methods defined here:
__init__(self, master=None, cnf={}, **kw)
activate(self, itemDesc)
Sets the active item to the one described by ITEMDESC, and
switches on the state ACTIVE for this item. From now on the item
can be retrieved with the item description ACTIVE. An <ActiveItem>
event is generated.
bbox(self, area=None)
Returns a list with four elements giving the bounding box (left,
top, right and bottom) of an area of the window. If AREA is not
specified, then the result is the bounding box of the entire window.
If AREA is CONTENT, then the result is the part of the window not
including borders, headers, or locked columns. If AREA is HEADER, then
the result is the part of the window not including borders where column
titles are displayed. If AREA is LEFT, then the result is the part of
the window not including borders or headers where left-locked columns
are displayed. If AREA is RIGHT, then the result is the part of the
window not including borders or headers where right-locked columns are
displayed. None is returned if the display area has no height or width,
which can be true for various reasons such as the window is too small,
or the header is not displayed, or there aren't any locked columns.
canvasx(self, screenx)
Given a window x-coordinate in the treectrl screenx, this
command returns the treectrl x-coordinate that is displayed
at that location.
canvasy(self, screeny)
Given a window y-coordinate in the treectrl screeny, this
command returns the treectrl y-coordinate that is displayed
at that location.
column_bbox(self, column)
Returns a list with four elements giving the bounding box for the
column header specified by COLUMN. If the treectrl is configured not to
display the column headers by means of the showheader option,
then None is returned instead.
column_cget(self, column, option)
This command returns the current value of the option named OPTION
for the column specified by COLUMN. COLUMN may also be the string TAIL
to specify the tail column. OPTION may have any of the values accepted
by the column_configure() widget command.
column_compare(self, column1, op, column2)
From both columns the index is retrieved (as returned from the
column_order() widget command). Then these indexes are compared using
the operator OP, which must be either <, <=, ==, >=, >, or !=.
The return value of this command is True if the comparison evaluated to
true, False otherwise.
column_config = column_configure(self, column, cnf=None, **kw)
column_configure(self, column, cnf=None, **kw)
This command is similar to the configure() widget command except
that it modifies options associated with the column specified by COLUMN
instead of modifying options for the overall treectrl widget. COLUMN
may be the string TAIL to specify the tail column. If COLUMN is the
string ALL, at least one option-value pair must be given; in this case
all the columns are configured.
Available options are:
    arrow arrowbitmap arrowgravity arrowimage arrowpadx arrowpady
    arrowside background bitmap borderwidth button expand font
    gridleftcolor gridrightcolor image imagepadx imagepady
    itembackground itemjustify itemstyle justify lock maxwidth minwidth
    resize squeeze state stepwidth tags text textcolor textlines
    textpadx textpady uniform visible weight width widthhack
column_count(self, *args)
If no additional argument is given, returns an integer giving the
number of columns created by the column_create() widget command which
haven't been deleted by the column_delete() widget command. The tail
column is not counted in this case. If argument(s) are given, the
result is the number of columns that match the column description.
For example:
    colum_count('visible') will return the number of columns whose
                                -visible option is True, and:
    column_count('tag', 'a^b') will return the number of columns
                            with either tag "a" or "b", but not both.
Multiple column descriptions may be combined, like:
    column_count('tag', 'foo', 'tag', 'bar', 'visible')
column_create(self, *args, **kw)
This command creates a new column in the treectrl widget. The new
column is placed to the right of all other columns (except the tail
column). Any option-value arguments configure the new column according
to the column_configure() command. The return value is the unique
identifier of the new column.
column_delete(self, first, last=None)
Deletes the specified column(s) from the treectrl widget. If either
FIRST or LAST is specified as ALL, then all columns are deleted. The
tail column cannot be deleted and it is an error to specify it. The
order of first and last doesn't matter, and first may be equal to
last.
column_dragcget(self, option)
column_dragconfigure(self, cnf=None, **kw)
The user can move a column within a treectrl by drag-and-drop.
Feedback consists of a semi-transparent photo image of the header of
the column being dragged and a 2-pixel-thick vertical line to indicate
where the column may be dropped. The drag image consists of a colored
background rectangle plus the image and/or text displayed in the column
header. The 2-pixel-thick line will be drawn over the left edge of the
column before which the dragged column may be dropped.
The library scripts generate a <ColumnDrag-accept> event when the user
has successfully drag-and-drop'd a column. You will have to bind a
callback to this event if you want to move the dragged column.
column_id(self, column)
This command resolves the column description COLUMN into a unique
column identifier. If the column described by COLUMN doesn't exist,
this command returns None.
column_list(self, visible=False)
This command returns a list of identifiers for every column (except
the tail) from left to right. If VISIBLE is True, only columns whose
visible option is True are returned.
column_move(self, column, before)
Moves the specified COLUMN to the left of the column specified by
BEFORE. If BEFORE is the string TAIL, the column COLUMN will become the
last column.
column_neededwidth(self, column)
This command returns an integer giving the needed width of the
column specified by COLUMN. The needed width is the maximum of the
width of the column header and the width of the widest currently
visible item.
column_order(self, column, visible=False)
This command returns an integer giving the position of COLUMN in the
list of columns starting from zero for the leftmost column. If VISIBLE
is True, only columns whose visible option is True are considered,
and -1 is returned if COLUMN's visible option is False.
column_tag_add(self, column, *tags)
Adds each tag in TAGS to the columns specified by the column
description COLUMN. Duplicate tags are ignored. The list of tags for a
column can also be changed via column_configure(tags=(...)).
column_tag_expr(self, column, tag)
Evaluates the tag expression TAG against every column specified by
the column description COLUMN. The result is True if the tag expression
evaluates to True for every column, False otherwise.
column_tag_names(self, column)
Returns a list of tag names assigned to the columns specified by the
column description COLUMN. The result is the union of any tags assigned
to the columns.
column_tag_remove(self, column, *tags)
Removes each tag in TAGS from the columns specified by the column
description COLUMN. It is not an error if any of the columns do not use
any of the tags. The list of tags for a column can also be changed via
column_configure(tags=(...).
column_width(self, column)
This command returns an integer giving the width in pixels of the
column specified by COLUMN, even if the treectrl is configured to not
display the column headers by means of the showheader option
contentbox(self)
Returns a tuple with four elements giving the bounding box for the
space used to display the items, i.e. the space of the treectrl window
without the surrounding borders or the column headers. The return value
is None if the content area is totally obscurred by column headers,
borders, and/or locked columns. Typically this will only happen if the
window is too small.
create_column = column_create(self, *args, **kw)
create_element = element_create(self, name=None, type=None, *args, **kw)
create_gradient = gradient_create(self, name=None, *args, **kw)
create_item = item_create(self, *args, **kw)
create_style = style_create(self, name=None, *args, **kw)
debug_cget(self, element, option)
This command returns the current value of the debugging option named
OPTION. OPTION may have any of the values accepted by the debug
configure widget command.
debug_configure(self, element, cnf=None, **kw)
This command is similar to the configure widget command except that
it modifies debugging options instead of modifying options for the
overall treectrl widget. If no option is specified, the command
returns a list describing all of the available debugging options.
debug_dinfo(self)
For every of the treectrl widget a line with some internal values
info about all items is printed to stdout.
debug_scroll(self)
Returns a string useful for debugging vertical scrolling.
delete_column = column_delete(self, first, last=None)
delete_element = element_delete(self, *elements)
delete_gradient = gradient_delete(self, *gradients)
delete_item = item_delete(self, first, last=None)
delete_style = style_delete(self, style)
depth(self, itemDesc=None)
If the additional argument ITEMDESC is specified, returns an integer
giving the depth of the item describing by ITEMDESC, whereas depth is
defined as the number of steps you must go upward to reach to root
item. If no ITEMDESC is specified, the maximum depth of all items in
the treectrl widget is returned instead.
dragimage_add(self, itemDesc, column=None, element=None)
Adds the shapes of the item described by ITEMDESC to the shapes of
the dragimage. Specifying additional arguments reduces the number of
rectangles that are added to the dragimage. If no additional arguments
is specified, for every element of the item in every column a dotted
rectangles is added. If COLUMN is specified, all elements in other
columns are ignored. If also ELEMENT is specified, only a rectangle for
this one element of the specified item in the given column is added.
dragimage_cget(self, option)
This command returns the current value of the dragimage option named
OPTION. OPTION may have any of the values accepted by the
dragimage_configure() widget command.
dragimage_clear(self)
Removes all shapes (if there are any) from the dragimage. This
command does not modify the dragimage offset.
dragimage_config = dragimage_configure(self, cnf=None, **kw)
dragimage_configure(self, cnf=None, **kw)
This command is similar to the configure widget command except that
it modifies the dragimage options instead of modifying options for the
overall treectrl widget. If no option is specified, the command returns
a list describing all of the available dragimage options
dragimage_offset(self, x=None, y=None)
Returns a list containing the x and y offsets of the dragimage, if
no additional arguments are specified. The dragimage offset is the
screen distance, the image is displayed relative to the item its shape
is derived from. If two coordinates are specified, sets the dragimage
offset to the given coordinates X and Y.
element_cget(self, element, option)
This command returns the current value of the option named OPTION
associated with the element given by ELEMENT. OPTION may have any of
the values accepted by the element_configure() widget command.
element_config = element_configure(self, element, cnf=None, **kw)
element_configure(self, element, cnf=None, **kw)
This command is similar to the configure() widget command except
that it modifies options associated with the element given by ELEMENT
instead of modifying options for the overall treectrl widget. If no
option is specified, the command returns a list describing all of the
available options for ELEMENT.
element_create(self, name=None, type=None, *args, **kw)
Create a new elememt in SELF of type TYPE with name NAME. The exact
format of the arguments after type depends on TYPE, but generally
consist of specifications for zero or more element options.
This command returns the name for the new element.
element_delete(self, *elements)
Deletes each of the named ELEMENTS. If an element is deleted while
it is still configured as an element of one or more styles by means of
the style_elements() widget command, it is also removed from the
element lists of these styles.
element_names(self)
Returns a list containing the names of all existing elements.
element_perstate(self, element, option, *statelist)
This command returns the value of the per-state option named option
for element for a certain state. StateList is a list of state names
(static and dynamic) which specifies the state to use.
element_type(self, element)
Returns the type of the elements given by ELEMENT, such as
"rect" or "text".
filelist_emulate_win7(self, win7=None)
Query or change the flag indicating that Windows 7 behavior should
be used. If called without arguments returns True or False depending
on the current state. If called with a boolean value as argument
changes the behavior according to the given value.
gradient_cget(self, gradient, option)
Returns the current value of the configuration option for the
gradient specified by GRADIENT whose name is OPTION. Option may have
any of the values accepted by the gradient_configure() command.
gradient_config = gradient_configure(self, gradient, cnf=None, **kw)
gradient_configure(self, gradient, cnf=None, **kw)
This command is similar to the configure() widget command except
that it modifies options associated with the gradient given by GRADIENT
instead of modifying options for the overall treectrl widget. If no
option is specified, the command returns a list describing all of the
available options for GRADIENT.
The following options are supported (see gradient create for the
meaning of each option):
    bottom left orient right steps stops top
gradient_create(self, name=None, *args, **kw)
Creates a new gradient with the name NAME, which must be a unique
name not used by another gradient created by this treectrl widget.
If NAME is None a unique name will be created by the widget.
The following options are supported:
    -bottom coordSpec
    -left coordSpec
    -right coordSpec
    -top coordSpec
        Each of these options specifies one edge of the gradient brush.
        If the option is specified as an empty string (the default),
        the gradient brush's edge is the same as that of whatever
        rectangle is being painted using the gradient.
        The format of each of these options is a tuple of 2 or more
        values (value, coordType, ?arg ...?), where value is a floating
        point number (usually from 0.0 to 1.0) and coordType is one of
        AREA, CANVAS, COLUMN or ITEM. The AREA keyword must be followed
        by one of the same area names that the bbox command accepts.
        The COLUMN keyword may be followed by a column description
        specifying exactly one column. The ITEM keyword may be followed
        by an item description specifying exactly one item.
    -orient direction
        This option specifies the direction a linear gradient changes
        color in. Must be either horizontal (the default) or vertical
        or an abbreviation of one of these.
    -steps stepCount
        Specifies the number of bands of color drawn for each color
        stop described by the -stops option. The default value is 1,
        the maximum is 25. This option has no effect if gradients are
        drawn using something better than Tk API calls.
    -stops stopsList
        Specifies the color stops along this gradient. The argument
        stopsList has the following form:
        ((offset color ?opacity?), (offset color ?opacity?) ...)
        Each offset is a floating point number from 0.0 to 1.0
        specifying the distance from the start of the gradient
        where the color begins. Each color is a Tk color name or
        description. Each optional opacity is a floating point number
        from 0.0 to 1.0 specifying how transparent the gradient is.
        If stopsList is non-empty there must be at least two stops
        specified, and the first offset must be 0.0 and the last offset
        must be 1.0. Any other stop offsets must be listed in
        increasing order. Specifying opacity has no effect if gradients
        are drawn using Tk API calls.
gradient_delete(self, *gradients)
Deletes each gradient specified in GRADIENTS. If the gradient is
still being used then it is not actually deleted until all elements
etc using the gradient have stopped using it. A deleted-but-in-use
gradient is not recognized by the various gradient commands.
Creating a new gradient with the same name as a deleted-but-in-use
gradient resurrects the deleted gradient.
gradient_names(self)
Returns a list of names of all the gradients that have been
created by this treectrl widget.
gradient_native(self, preference=None)
Without any arguments, this command returns a boolean indicating
whether or not the platform supports native transparent gradients.
The preference argument is a boolean that indicates whether native
gradients should be used; this can be used to test the appearance
of the application.
identify(self, x, y)
Returns a list containing some diagnostics about what is displayed
at the given windows coordinates x and y. The resulting list may be
empty, if nothing is displayed at the given coordinates, otherwise
the first list element is "header" or "item".
If the coordinates are in the header area and thus the first element of
the result is header, the number of the column or the string tail is
the second element in the resulting list; if the x coordinate is near
the left or right end of the header, a third element left or right is
added respectively. If the coordinates are below the header area and
thus the first element of the result is item, the numerical id of the
item is the second element in the resulting list. If the x coordinate
doesn't fall into the column displaying the hierarchical structure,
the elements column and the column number are added. If the
x coordinate is within the column displaying the hierarchical
structure, the following elements are added to the resulting list:
line and the numerical id of the item the line comes from, if the
x coordinate is above an item connecting line; button, if the
x coordinate is above a button; column, the column
number, elem, and the element name, if the x coordinate is above an
element of the item; column and the column number, if the x coordinate
is to the right of the elements; nothing otherwise.
is_sensitive(self, x, y)
Returns True if the given window coordinates are over an element
that should respond to mouse clicks. The list of elements that
respond to mouse clicks is set by calling set_sensitive().
is_sensitive_marquee(self, x, y)
Returns True if the given window coordinates are over an element
that should respond to the marquee. The list of elements that respond
to the marquee is set by calling set_sensitive_marquee(), or if that
list is empty then the same list passed to set_sensitive().
item_ancestors(self, itemDesc)
Returns a list containing the item ids of the ancestors of the item
specified by itemDesc. The first list value is the parent, the second
is the parent's parent, an so on. The last list value will be the root
item if itemDesc is a descendant of the root item.
item_bbox(self, itemDesc, column=None, element=None)
Returns a list with four elements giving the bounding box for the
item described by itemDesc. If no further argument is specified, the
bbox spans the area of the item over all columns. If a column is
specified, only the area of the item in this column is considered, if
an additional element is specified, the area of this element in column
of the specified item is returned.
item_buttonstate(self, itemDesc, state=None)
If STATE is specified, this command sets the state of the
expand/collapse button for the single item specified by ITEMDESC.
The state argument may be one of ACTIVE, NORMAL or PRESSED.
The current (or newly-set) state of the button is returned.
The button state is used by the system theme, if any, to change
the appearance of the button.
item_cget(self, itemDesc, option)
Returns the current value of the configuration option for the item
specified by ITEMDESC whose name is OPTION. OPTION may have any of the
values accepted by the item_configure() command.
item_children(self, itemDesc)
Returns a list containing the item ids of all children of the item
specified by ITEMDESC in the correct order from the first child to the
last child.
item_collapse(self, itemDesc, recurse=False, animate=False)
Switches off the open state of the item(s) described by ITEMDESC. If
the item has descendants, they are no longer displayed. If the item is
configured to have a button, the button will now display the image or
bitmap configured with the widget options -buttonimage or
-buttonbitmap, or a + sign if no image or bitmap is configured.
If the item is already closed, this command has no effect.
ITEMDESC may also be the string ALL, in which case all items of the
treectrl widget are collapsed. If ANIMATE is True, then the item's
button will animate as it transitions between states if the theme
supports it; in this case only one item may be specified.
If RECURSE is True, all descendants of ITEMDESC will also be
collapsed. For every item, that actually will be collapsed, two events
are generated: a <Collapse-before> event before the item state is
changed, and a <Collapse-after> event after the item state was
changed.
item_compare(self, itemDesc1, op, itemDesc2)
From both items described by the ITEMDESCs the index is retrieved
(as returned from the item_order() widget command). Then these indexes
are compared using the operator OP, which must be either
<, <=, ==, >=, >, or != . The return value of this command is True if
the comparison evaluated to true, False otherwise.
item_config = item_configure(self, itemDesc, cnf=None, **kw)
item_configure(self, itemDesc, cnf=None, **kw)
If no option is specified, returns a list describing all of the
available options for the item given by ITEMDESC.
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 item option(s) to have the given value(s);
in this case the command returns an empty string.
The following options are supported by this command (see item_create()
for the meaning of each option):
button    boolean
height    height
tags      tuple
visible   boolean
wrap      boolean
item_count(self, *args)
If no additional argument is given, returns an integer giving the
number of items created by the item_create() widget command which
haven't been deleted by the item_delete() widget command, plus 1 for
the ever-present root item. If argument(s) are given, the result is the
number of items that match the item description. For example:
    item_count('visible') will return the number of items whose
                                -visible option is true, and:
    item_count('tag', 'a^b') will return the number of items with
                                   either tag "a" or "b", but not both.
Multiple item descriptions may be combined, like:
    item_count('tag', 'foo', 'tag', 'bar', 'visible')
item_create(self, *args, **kw)
Creates some new items and optionally returns a list of unique
identifiers for those items. The new items have the states open and
enabled set by default. If the treectrl widget currently has the focus,
the state focus is also set.
The following options are supported by this command:
-button boolean
    Boolean indicates whether or not an expand/collapse button should
    be drawn next to this item, typically to indicate the item has
    children. The button will only be displayed if: a) the column
    specified by the treectrl option -treecolumn is visible;
    and b) the treectrl option -showbuttons is true
-count numItems
    Specifies the number of items to create. Must be >= 0.
    Defaults to 1.
-enabled boolean
    Specifies whether the items should be enabled. Default is true.
-height height
    Specifies a fixed height in any of the forms acceptable to
    Tk_GetPixels. Must be >= 0. If height is zero then the item's
    height is unspecified. Defaults to 0.
-nextsibling itemDesc
    Specifies the item before which the new items will be inserted.
    The new items will have the same parent as itemDesc.
-open boolean
    Specifies whether the items should be open or closed.
    Default is true.
-parent itemDesc
    Specifies the item which the new items will be the children of.
    The new items will be appended to the list of children of itemDesc.
-prevsibling itemDesc
    Specifies the item after which the new items will be inserted. The
    new items will have the same parent as itemDesc.
-returnid boolean
    Specifies whether or not to return a list of item identifiers for
    the newly created items. Specifying false is useful when creating
    a large number of items in the console or to improve performance.
    Default is true.
-tags tuple
    Tags are textual labels applied to items to group them. Tags do
    not affect the appearance or behaviour of items. Tags can be used
    in item descriptions to operate on multiple items.
-visible boolean
    It indicates that the item should be displayed
    in the list. The item will only be displayed if: a) each ancestor
    is a descendant of the root item (not an orphan); and
    b) each ancestor's -visible option is true.
-wrap boolean
    When this option is true an item will be the first in a horizontal
    (when the treectrl option -orient=horizontal) or a vertical (when
    the treectrl option -orient=vertical) range of items.
item_delete(self, first, last=None)
Deletes the specified item(s). FIRST and LAST must be the string
ALL or a valid item description. If either FIRST or LAST is specified
as ALL, then all items are deleted. If FIRST is specified and LAST
isn't specified, the item described by FIRST is deleted. If both FIRST
and LAST are specified, they must decribe items with a common ancestor;
then the range of items between FIRST and LAST is deleted. Deleting an
item deletes any child items of the deleted item recursively. If the
current active item is deleted, the root item becomes the new active
item. If the current selection anchor item is deleted, the root item
becomes the new anchor item. There is no way to delete the root item
of the treectrl widget; in all cases the specification of the root item
is ignored. For each call to this command, two events may be generated.
If any of the deleted items are selected, then a <Selection> event is
generated just before the items are deleted. If any items were actually
deleted, then an <ItemDelete> event is generated just before the items
are deleted.
item_descendants(self, itemDesc)
Returns a tuple containing the item ids of the descendants of the
item specified by itemDesc, i.e. the children, grandchildren,
great-grandchildren etc, of the item.
item_dump(self, itemDesc)
Returns a list with four elements in the form
(index, *index*, indexVis, *indexVis*).
item_enabled(self, itemDesc, enabled=None)
Returns True if the item described by ITEMDESC has the state
"enabled" switched on, False otherwise. If ENABLED is specified, then
the "enabled" state of every item described by the item description
ITEMDESC is set accordingly. All items are enabled when first created.
Disabled items cannot be selected, and are ignored by the default
key-navigation and mouse bindings.
item_expand(self, itemDesc, recurse=False, animate=False)
Switches on the open state of the item(s) described by ITEMDESC. If
the item has descendants, they are now displayed. If the item is
configured to have a button, the button will now display the image or
bitmap configured with the widget options -buttonimage or
-buttonbitmap, or a - sign if no image or bitmap is configured.
If the item is already open, this command has no effect.
If ANIMATE is specified, then the item's button will animate as it
transitions between states if the theme supports it; in this case only
one item may be specified. ItemDesc may also be the string ALL, in
which case all items of the treectrl widget are expanded.
If RECURSE is True, all descendants of ITEMDESC will
also be expanded. For every item, that actually will be expanded,
two events are generated: an <Expand-before> event before the
item state is changed, and an <Expand-after> event after the
item state was changed.
item_firstchild(self, parent, child=None)
If CHILD is not specified, returns the item id of the first child of
the item described by PARENT. If CHILD is specified, it must describe
an item that is not an ancestor of PARENT. Then it will become the new
first child of PARENT.
item_id(self, itemDesc)
New in treectrl-2.2 :
This command resolves the item description ITEMDESC into a
tuple of unique item identifier(s).If ITEMDESC doesn't refer to any
existing items, then this command returns None. For example:
    item_id(ALL) will return a tuple of ids for all items, and:
    item_id(item_children(someItem)) will return the ids of
                                               every child of an item.
On previous versions of the treectrl widget, a tuple containing only
one item id will be returned.
item_image(self, itemDesc, *columnAndImage)
This command sets or retrieves the value of the per-state -image
option for the first image element in one or more columns. If no column
is specified, this command returns a list of values, one per column. If
no image is specified, this command returns the value for column. If
one or more column-image pairs is specified, then the value of the
-image option in each column is set to image. Note that this command is
provided as a convenience. Use the itemelement_configure() or
itemelement_cget() commands if you want to set or retrieve the value
of the -image option for a specific image element.
item_isancestor(self, itemDesc, descendant)
Returns True if the item described by ITEMDESC is a direct or
indirect parent of the item decribed by DESCENDANT, False otherwise.
item_isopen(self, itemDesc)
Returns True if the item described by itemDesc has the state open
switched on, False otherwise.
item_lastchild(self, parent, child=None)
If CHILD is not specified, returns the item id of the last child of
the item described by PARENT. If CHILD is specified, it must describe
an item that is not an ancestor of PARENT. Then it will become the new
last child of PARENT.
item_nextsibling(self, sibling, next=None)
If NEXT is not specified, returns the item id of the next sibling of
the item described by SIBLING. If NEXT is specified, it must describe
an item that is not an ancestor of SIBLING. Then it will become the new
next sibling of SIBLING.
item_numchildren(self, itemDesc)
Returns the number of children of the item described by ITEMDESC.
item_order(self, itemDesc, visible=False)
This command returns the position of the item ITEMDESC relative to
its toplevel ancestor (usually the root item, unless the ancestor is an
orphan). If you imagine all the items flattened into a vertical list,
the result of this command is the row the item falls in. If the
optional argument -visible is given, only the items whose ancestors
are expanded, and whose -visible option is true, get counted; in this
case -1 is returned if the item is not visible.
item_parent(self, itemDesc)
Returns the item id of the parent of the item described by
ITEMDESC.
item_prevsibling(self, sibling, prev=None)
If PREV is not specified, returns the item id of the previous
sibling of the item described by SIBLING. If PREV is specified, it
must describe an item that is not an ancestor of SIBLING. Then it will
become the new previous sibling of SIBLING.
item_range(self, first, last)
Returns a list containing the item ids of all items in the range
between FIRST and LAST, inclusive. The order between FIRST and LAST
doesn't matter, and the result is always sorted by the increasing order
of the items (as returned by the item order command). The items
specified by FIRST and LAST must share a common ancestor.
item_remove(self, itemDesc)
Removes the item described by ITEMDESC from the list of children of
its parent, so that it will become an orphan.
item_rnc(self, itemDesc)
Returns a list of two integers, which corresponds to the row and
column of the item described by ITEMDESC. The row and column
corresponds to the on-screen arrangement of items as determined by
the -orient and -wrap options.
If the item is not displayed, this command returns None.
item_sort(self, itemDesc, column=None, element=None, first=None, last=None, mode=None, command=None, notreally=False)
Sorts the children of the item described by ITEMDESC, and redisplays
the tree with the items in the new order. The range of items which
should be sorted can be restricted by means of the FIRST and/or LAST
options, which should be children of the item described by ITEMDESC;
the order between these two limiting items doesn't matter. The sort
column can be specified by means of the COLUMN option; this option
can be used repeatedly to define a multicolumn sort. The sorting is
done by looking at the text of the element specified by the ELEMENT
option, which must be a text element defined in the style of the
sorting column; by default the first text element is used.
If the NOTREALLY option is True, no rearranging of the items is
done; instead the sorted items are returned as result of the command.
By default ASCII sorting is used with the result returned in increasing
order. Any of the following options (or a sequence of options) may be
specified as MODE to control the sorting process of the previously
specified column (unique abbreviations are accepted):
ascii
    Use string comparison with ASCII collation order.
    This is the default.
command command
    Use command as a comparison command. To compare two items,
    evaluate a command with the numerical ids of the two items passed
    as arguments. The comamnd should return an integer less than,
    equal to, or greater than zero if the first item is to be
    considered less than, equal to, or greater than the second,
    respectively.
decreasing
    Sort the items in decreasing order ("largest" items first).
dictionary
    Use dictionary-style comparison. This is the same as -ascii except
    (a) case is ignored except as a tie-breaker and
    (b) if two strings contain embedded numbers, the numbers compare
    as integers, not characters. For example, in -dictionary mode,
    bigBoy sorts between bigbang and bigboy,
    and x10y sorts between x9y and x11y.
increasing
    Sort the items in increasing order ("smallest" items first).
    This is the default.
integer
    Convert to integers and use integer comparison.
real
    Convert to floating-point values and use floating comparison.
item_span(self, itemDesc, *columnAndNumColumns)
This command sets or retrieves the number of columns that a style
covers. If no column is specified, the return value is a list of spans,
one per column. If no numColumns is specified, the return value is the
span for column. If one or more column-numColumns pairs is specified,
the span for each column is set to numColumns.
item_tag_add(self, itemDesc, *tags)
Adds each tag in TAGS to the items specified by the item description
ITEMDESC. Duplicate tags are ignored. The list of tags for an item can
also be changed via item_configure(tags=(...)).
item_tag_expr(self, itemDesc, tag)
Evaluates the tag expression TAG against every column specified by
the item description ITEMDESC. The result is True if the tag expression
evaluates to true for every item, False otherwise. For example:
    item_tag_expr(itemDesc, 'foo')
returns True if an item has tag "foo". Also:
    item_tag_expr(itemDesc, 'a||b')
returns True if  an item has tag "a" or "b".
item_tag_names(self, itemDesc)
Returns a list of tag names assigned to the items specified by the
item description ITEMDESC. The result is the union of any tags assigned
to the items.
item_tag_remove(self, itemDesc, *tags)
Removes each tag in TAGS from the items specified by the item
description ITEMDESC. It is not an error if any of the items do not use
any of the tags. The list of tags for an item can also be changed via
item_configure(tags=(...).
item_text(self, itemDesc, *columnAndText)
This command sets or retrieves the value of the -text option for the
first text element in one or more columns. If no COLUMN is specified,
this command returns a list of values, one per column. If no TEXT is
specified, this command returns the value for COLUMN. If one or more
column-text pairs is specified, then the value of the -text option in
each column is set to text. Note that this command is provided as a
convenience. Use the itemelement_configure() or itemelement_cget()
commands if you want to set or retrieve the value of the -text option
for a specific text element.
item_toggle(self, itemDesc, recurse=False, animate=False)
Changes the open state of the item(s) described by ITEMDESC. If the
state is currently switched off, this command does the same as the
item_expand() widget command, otherwise the same as the item_collapse()
widget command. If ANIMATE is specified, then the item's button will
animate as it transitions between states if the theme supports it; in
this case only one item may be specified.ITEMDESC may also be the
string ALL, in which case the state of all items of the treectrl widget
are toggled. If RECURSE is specified, the state of all descendants of
ITEMDESC will also be toggled.
itemelement_cget(self, itemDesc, column, element, option)
This command returns the value of the option named OPTION associated
with ELEMENT inside COLUMN of the item described by ITEMDESC, if it
was already configured for the actual item. OPTION may have any of the
values accepted by the type of the specified ELEMENT.
itemelement_config = itemelement_configure(self, itemDesc, column, element, cnf=None, **kw)
itemelement_configure(self, itemDesc, column, element, cnf=None, **kw)
This command is similar to the configure widget command except that
it modifies options associated with ELEMENT inside COLUMN of the item
described by ITEMDESC instead of modifying options for the overall
treectrl widget. If no option is specified, the command returns a list
describing all of the available options for the element
itemelement_perstate(self, itemDesc, column, element, option, *statelist)
This command returns the current value of the per-state option named
OPTION for ELEMENT inside COLUMN of the item described by ITEMDESC.
If STATELIST is specified, the list of state names (static and dynamic)
is used in place of the current state for ITEM and COLUMN.
itemstate_forcolumn(self, itemDesc, column, *statenames)
Just like itemstate_set() but manipulates dynamic states for a
single item column, not the item as a whole. If STATENAME is
unspecified, this command returns a list containing the names of all
the dynamic states which are switched on in COLUMN.
itemstate_get(self, itemDesc, statename=None)
If no STATENAME is specified, returns a list containing the names of
all (static and dynamic) states which are currently switched on for the
item described by ITEMDESC. If a STATENAME is specified, True is
returned if the specified state is currently switched on for the item,
False otherwise.
itemstate_set(self, first, last, *statenames)
Every element of STATENAMES must be the name of a dynamic state,
optionally preceded by a ~ or ! character. Every state with a
leading ! will be switched off for the item described by FIRST, every
state with a leading ~ will be toggled, and every state without
leading ! or ~ will be switched on. If LAST is specified, the state
changes will be made for all items in the range between FIRST and LAST.
If LAST is set to None, only the state(s) of the item described by
FIRST will be changed. If FIRST is the string ALL, then the state
changes are made for all items of the treectrl widget.
itemstyle_elements(self, itemDesc, column)
This command returns a list containing the names of elements which
were configured by the itemelement_configure() command for the item
described by ITEMDESC in COLUMN.
If there is no style assigned to COLUMN, None is returned.
itemstyle_map(self, itemDesc, column, style, *map)
Like the itemstyle_set() command, this command may be used to assign
a style to a specific column of an item. Unlike itemstyle_set(), this
command can transfer configuration values of elements in the current
style to elements in the new style specified by STYLE. MAP must be a
list of elementOld-elementNew pairs, where elementOld is an element in
the current style, and elementNew is an element in the style specified
by style. Both elementOld and elementNew must be of the same
type (bitmap, text etc).
itemstyle_set(self, itemDesc, *columnAndStyle)
This command sets or retrieves the style assigned to one or more
columns. If no COLUMN is specified, this command returns a tuple
containing the names of the styles set for all columns of the item
described by ITEMDESC. If no STYLE is specified, this command returns
the name of the style set for the item described by ITEMDESC in COLUMN.
If one or more column-style pairs is specified, then the style in each
column is set to style.
marquee_anchor(self, x=None, y=None)
Returns a list containing the x and y coordinates of the anchor, if
no additional arguments are specified. If two coordinates are
specified, sets the anchor to the given coordinates X and Y.
marquee_cget(self, option)
This command returns the current value of the marquee option named
OPTION. OPTION may have any of the values accepted by the
marquee_configure() widget command.
marquee_configure(self, cnf=None, **kw)
This command is similar to the configure() widget command except
that it modifies the marquee options instead of modifying options for
the overall treectrl widget.
The following marquee options are supported:
-fill
  Specifies the fill color for the selection rectangle. The value can
  be a Tk color or a gradient name or an empty string (the default).
  When this option isn't an empty string the dotted outline is not
  drawn. By specifying the name of a semi-transparent gradient a
  modern-looking selection rectangle can be achieved.
-outline
  Specifies the outline color for the selection rectangle. The value
  can be a Tk color, a gradient name, or an empty string which is the
  default.  When this option isn't an empty string the dotted outline
  is not drawn.
-visible boolean
  Specifies a boolean value which determines whether the dotted line
  surrounding the region of the marquee should currently be visible.
marquee_coords(self, x1=None, y1=None, x2=None, y2=None)
Returns a list containing the x and y coordinates of the anchor
followed by the x and y coordinates of the corner, if no additional
arguments are specified. If four coordinates are specified, sets the
anchor to the given coordinates x1 and y1 and the corner to the
coordinates x2 and y2.
marquee_corner(self, x=None, y=None)
Returns a list containing the x and y coordinates of the corner,
if no additional arguments are specified. If two coordinates are
specified, sets the corner to the given coordinates x and y.
marquee_identify(self)
Returns a list with information about the items inside the marquee.
The list has as elements a list itself for every item which is
displayed inside the marquee. The first element of these lists is the
numerical item id, followed by another list with information about
every column of the item inside the marque. These lists start with the
column number, followed by the elements of the style defined for the
item in this column if there are any.
notify_bind(self, sequence=None, func=None, object=None, add=None)
This command associates Tcl scripts with events generated by a
treectrl widget. If all three arguments are specified, notify_bind()
will arrange for FUNC to be evaluated whenever the event(s) specified
by SEQUENCE are generated by this treectrl widget. If ADD is True,
then it is appended to any existing binding for SEQUENCE; otherwise
FUNC replaces any existing binding. If FUNC is an empty string, then
the current binding for SEQUENCE is destroyed, leaving SEQUENCE
unbound. If SEQUENCE is specified without a FUNC, then the script
currently bound to SEQUENCE is returned, or an empty string is returned
if there is no binding for SEQUENCE. If neither SEQUENCE nor FUNC is
specified, then the return value is a list whose elements are all the
patterns for which there exist bindings for object. The OBJECT argument
determines which window(s) the binding applies to. If OBJECT begins
with a dot, as in .a.b.c, then it must be the path name for a window;
otherwise it may be an arbitrary string. Like the regular bind command,
bindings on window names are automatically removed if that window is
destroyed.
notify_config = notify_configure(self, object, sequence, cnf=None, **kw)
notify_configure(self, object, sequence, cnf=None, **kw)
This command sets and retrieves options for bindings created by the
notify_bind() command. If no option is specified, the command returns
a list with option-value pairs describing all the available binding
options for SEQUENCE on OBJECT. If option is specified with no value,
then the command returns the current value of that option. If one or
more option-value pairs are specified, then the command modifies the
given option(s) to have the given value(s) for the binding; in this
case the command returns an empty string.
The following binding options are supported:
-active boolean
    Specifies if the binding should be active. As long as this option
    is specified as false, a binding script will not be evaluated
    when the corresponding event is generated.
notify_detailnames(self, eventname)
Returns a list containing the names of all details, which are
installed for the event with the name EVENTNAME by means of the
notify_install() widget command or by the treectrl widget itself.
notify_eventnames(self)
Returns a list containing the names of all events, which are
installed by means of the notify_install() widget command or by the
treectrl widget itself.
notify_generate(self, sequence, charmap=None, percentscommand=None, **kw)
This command causes the treectrl widget to generate an event. This
command is typically used to generate dynamic events created by the
notify_install() command, but may be used to generate static events
also. The event specified by SEQUENCE is generated, and any active
binding scripts on the event are evaluated after undergoing
%-substitution. If there are details defined for the event, SEQUENCE
must describe an <eventName-detail> pair, otherwise SEQUENCE should
be <eventName>. The optional CHARMAP is a tuple of char-value pairs.
Each char has to be exactly one character. The charMap is used in
%-substitution. If PERCENTSCOMMAND is specified, then it will be used
to perform %-substitution on any scripts bound to the event. If
PERCENTSCOMMAND is not specified and the event is dynamic, then the
%-subtitution command passed to notify_install() will be used if it was
provided. If the event is static or no %-substitution command is
available, then all %-substitution is done using CHARMAP only . See
notify_install() for a description of PERCENTSCOMMAND. If no CHARMAP is
specified, a default charmap will be created, that contains information
about the widget and the event pattern, plus optional information
provided by keyword-value pairs; any of the attributes of a
TreectrlEvent instance as created by a notify_bind() callback is
accepted as keyword argument.
notify_install(self, sequence, percentscommand=None)
This command installs a new event or detail specified by SEQUENCE.
Events created by this command are called dynamic, whereas events
created by the treectrl widget itself are called static. This command
may be called to set or retrieve the PERCENTSCOMMAND for an existing
dynamic event. The optional PERCENTSCOMMAND is a list containing the
name of a Tcl command, plus any optional arguments, to which five
additional arguments will be appended. The command will be called to
perform %-substitution on any scripts bound to the event specified by
SEQUENCE. notify_install() returns the current PERCENTSCOMMAND for the
event, or an error if the event is not dynamic.
notify_linkage(self, sequence)
Returns a string indicating whether the specified event or detail
is created by means of the notify_install() widget command (dynamic)
or by the treectrl widget itself (static).
notify_unbind(self, object, sequence=None)
If no SEQUENCE is specified, all bindings on OBJECT are removed.
If SEQUENCE is specified, then the current binding for SEQUENCE is
destroyed, leaving SEQUENCE unbound.
notify_uninstall(self, sequence)
If the event or detail specified by SEQUENCE is static (i.e. created
by the treectrl widget itself), an error is generated. Otherwise the
dynamic event or detail is removed. If an event name is specified
without a detail, all details for that event are also removed.
orphans(self)
Returns a list containing the item ids of all items which have no
parent. When an item is created, it has no parent by default, and can
later become an orphan by means of the item_remove() widget command.
The root item is not returned.
see(self, itemDesc, column=None, center=None)
Adjust the view in the treectrl so that the item described by
ITEMDESC is visible. If the item is already visible then the command
has no effect; otherwise the treectrl scrolls to bring the item into
view, and the corresponding <Scroll-x> and/or <Scroll-y> events are
generated. If COLUMN is specified then a specific column of the item
is scrolled into view instead of the entire item.
CENTER may be a string that contains zero or more of the characters
"x" or "y". This option is used to center the item horizontally and/or
vertically in the window. The item will be centered regardless of
whether it is already visible.
selection_add(self, first, last=None)
FIRST and LAST (if specified) must be the string ALL or a valid
item description. Adds every unselected item in the range between
FIRST and LAST, inclusive, to the selection without affecting the
selection state of items outside that range. If one of the arguments
is the string ALL, every unselected item in the treectrl widget is
added to the selection. A <Selection> event is generated if any
items were added to the selection.
selection_anchor(self, itemDesc=None)
If ITEMDESC is specified, the selection anchor is set to the
described item. The selection anchor is the end of the selection that
is fixed while dragging out a selection with the mouse. The item
description anchor may be used to refer to the anchor item. This
command doesn't modify the selection state of any item. Returns the
numerical id of the selection anchor item.
selection_clear(self, first=None, last=None)
FIRST and LAST (if specified) must be the string ALL or a valid
item description. If any of the items between FIRST and LAST
(inclusive) are selected, they are deselected. The selection state is
not changed for items outside this range. If no additional arguments
are given, or if one of the arguments is the string ALL, then all
items are removed from the selection. A <Selection> event is
generated if any items were removed from the selection.
selection_count(self)
Returns an integer indicating the number of items in the treectrl
that are currently selected.
selection_get(self, first=None, last=None)
Returns a tuple containing the item ids of all of the items in the
treectrl that are currently selected. If there are no items selected
in the treectrl, returns None. The optional arguments FIRST and LAST
are treated as indices into the sorted list of selected items.
For example:
    selection_get(0)          : the first selected item
    selection_get("end")      : the last selected item
    selection_get(1, "end-1") : every selected item except
                                     the first and last
selection_includes(self, itemDesc)
Returns True if the item described by itemDesc is currently
selected, False if it isn't.
selection_modify(self, select=(), deselect=())
Both arguments SELECT and DESELECT must be the string ALL or a
possibly-empty list of item descriptions. Any unselected items in
SELECT are added to the selection, and any selected items in DESELECT
are removed from the selection (except for those items which are also
in SELECT). A <Selection> event is generated if any items were
selected or deselected.
set_dragimage(self, *args)
This command may be used to define elements that should be drawn
as drag images during drag operations.
ARGS must be one or more tuples of the form (COLUMN, STYLE, ELEMENT)
that define the elements that are supposed to be drawn.
For this to take effect, at least calls to
bindtags(('TreeCtrlFileList',)) and set_sensitive(*args)
must be made before.
set_editable(self, *args)
This command may be used to define text cells that should be
user-editable. ARGS must be one or more tuples of the form
(COLUMN, STYLE, ELEMENT) that define the text elements that are
supposed to be editable. For this to take effect, at least calls to
bindtags(('TreeCtrlFileList',)) and set_sensitive(*args)
must be made before.
set_selected_items_sensitive(self, sensitive)
Specifies whether or not entire items are sensitive to mouse clicks
when they are already selected. SENSITIVE must be a boolean value.
set_sensitive(self, *args)
Defines elements that are supposed to respond to mouse events
after file list bindings have been applied to the widget with
bindtags(('TreeCtrlFileList',)). ARGS must be one or more tuples of
the form (COLUMN, STYLE, ELEMENT) that define the desired elements.
set_sensitive_marquee(self, *args)
Just like set_sensitive() but indicates which elements respond to
the selection rectangle. Typically this is the same as the elements
passed to set_sensitive() with the addition of the selection rectangle
elements.
state_define(self, statename)
Defines a new state with the name STATENAME, which must not be the
name of an existing state.
state_linkage(self, statename)
Returns a string indicating whether the specified state is
user-defined by means of the state_define() widget command (dynamic)
or predefined by the treectrl widget itself (static).
state_names(self)
Returns a list containing the names of all user-defined states.
state_undefine(self, statename)
STATENAME must be the name of a user-defined state. Removes this
state from the list of user-defined states.
style_cget(self, style, option)
This command returns the current value of the option named OPTION
associated with the style given by STYLE. OPTION may have any of the
values accepted by the style_configure() widget command.
style_config = style_configure(self, style, cnf=None, **kw)
style_configure(self, style, cnf=None, **kw)
This command is similar to the configure() widget command except
that it modifies options associated with the style given by STYLE
instead of modifying options for the overall treectrl widget. The
options of a style have effect on all elements managed by the style.
The following options are supported:
-buttony offset
    Specifies the distance from the top of the item that the
    expand/collapse button should be drawn. If offset is an empty
    string (the default) then the button is centered vertically in
    the item. The value may have any of the forms acceptable to
    Tk_GetPixels. This option only has effect when the style is
    set in an item in the tree column.
-orient varName
    This option specifies which orientation should be used when
    laying out the elements associated with this style.
    Must be either horizontal (the default) or vertical or an
    abbreviation of one of these.
style_create(self, name=None, *args, **kw)
Create a new style in pathName with name STYLE. After STYLE there
may be any number of option-value pairs, each of which sets one of the
configuration options for the style. These same option-value pairs may
be used in style_configure() widget commands to change the style's
configuration. Returns the name of the new style.
style_delete(self, style)
Deletes each of the named STYLEs. If a style is deleted while it is
still used to display one or more items, it is also removed from the
style list of these items.
style_elements(self, style, *elementList)
Specifies the elements which should be layed out by this style.
Each element of ELEMENTLIST must be the name of an element created by
the widget command element_create(). Duplicate names in ELEMENTLIST
are ignored. An element which was specified in a former call of this
command for STYLE but is not included in ELEMENTLIST, will be deleted
from the elements layed out by STYLE. If the ELEMENTLIST argument is
not specified, a list is returned containing the currently defined
elements of STYLE.
style_layout(self, style, element, cnf=None, **kw)
This command is similar to the configure() widget command except
that it modifies options used by STYLE for laying out ELEMENT instead
of modifying options for the overall treectrl widget. The options of a
layout have effect on exactly the one element ELEMENT managed by STYLE.
The following options are supported:
-detach boolean
    Specifies whether the element should be positioned by itself,
    i.e. independent from the other elements.
-expand flags
    This option allows the external padding around the element to
    increase when a style has more screen space than it needs. Flags
    is a string that contains zero or more of the characters n, s, w
    or e. Each letter refers to the padding on the top, bottom, left,
    or right that should be allowed to increase. This option is
    typically used to justify an element.
-iexpand flags
    This option allows the internal padding of the element and the
    display area of the element to increase when a style has more
    screen space than it needs. Flags is a string that contains zero
    or more of the characters x, y, n, s, w or e. For n, s, w and e,
    each letter refers to the padding on the top, bottom, left, or
    right that should be allowed to increase. For x and y, each letter
    refers to the horizontal and vertical screen space the element can
    display itself in (i.e., the space between the padding). Note that
    if the -union option is specified for this element, then the x and
    y flags have no effect, since the size of an element with -union
    layout is determined by the elements it surrounds.
-indent boolean
    Specifies whether the element should be positioned to the right of
    the button/line area in the tree column.
    This option is ignored unless the -detach option is true.
-ipadx amount
-ipady amount
    Amount specifies how much internal padding to leave on the left
    and right (for -ipadx) or top and bottom (for -ipady) side of the
    element. Amount may be a list of two values to specify padding for
    the two sides separately, it defaults to 0.
-minheight pixels
-height pixels
-maxheight pixels
    Specifies the minimum, fixed, and maximum height of the element.
-minwidth pixels
-width pixels
-maxwidth pixels
    Specifies the minimum, fixed, and maximum width of the element.
-padx amount
-pady amount
    Amount specifies how much external padding to leave on the left
    and right (for -padx) or top and bottom (for -pady) side of the
    element. Amount may be a list of two values to specify padding
    for the two sides separately, it defaults to 0.
-squeeze flags
    This option allows the display area of an element to decrease when
    a style has less space than it needs. Flags is a string that
    contains zero or more of the characters x or y. x allows display
    area to decrease horizontally, y allows display area to decrease
    vertically. This option is typically used for text elements and
    will cause the text element to display an ellipsis (...) and/or
    wrap lines.
-sticky flags
    This option controls how the actual display information
    (image, text, etc) of an element is positioned (or stretched)
    within its display area. Flags is a string that contains zero
    or more of the characters n, s, w or e. Each letter refers to
    the top, bottom, left or right side of the display area that
    the display information should "stick" to.
-union elementList
    Specifies a list of other elements which this element will
    surround. The size of an element with -union layout is determined
    by the size and position of the elements in elementList. The
    -ipadx and -ipady options in this case refer to the distance of
    the edges of the display area of this element from those elements
    it surrounds. This option is typically used to display a
    selection rectangle around a piece of text.
    Since treectrl-2.3 it is ok to include an element with -union
    layout in another element's -union list.
    Previously, nesting -union elements had undefined behavior.
style_names(self)
Returns a list containing the names of all existing styles.
theme_platform(self)
Returns the API used to draw themed parts of the treectrl.
On Mac OS X the result is always aqua. On MS Windows the result is
visualstyles if the uxtheme.dll was loaded and visual themes are
in use, otherwise X11 is returned to indicate the Tk Xlib calls are
drawing the themed parts. On Unix systems the result is gtk if the
Gtk+ version of treectrl was built, otherwise X11 is returned.
theme_setwindowtheme(self, appname)
The command is available on MS Windows only. If appname is
"Explorer" then the item buttons look like those in the Explorer file
browser (disclosure triangles under Windows Vista/7). If appname is an
empty string then the buttons revert to their default appearance
according to the system's current visual style.
xview(self, *what)
Query and change horizontal position of the view.
xview_moveto(self, fraction)
Adjust the view in the window so that FRACTION of the
total width of the entry is off-screen to the left.
xview_scroll(self, number, what)
Shift the x-view according to NUMBER which is measured in
"units" or "pages" (WHAT).
yview(self, *what)
Query and change vertical position of the view.
yview_moveto(self, fraction)
Adjust the view in the window so that FRACTION of the
total width of the entry is off-screen to the top.
yview_scroll(self, number, what)
Shift the y-view according to NUMBER which is measured in
"units" or "pages" (WHAT).

 
class TreectrlEvent
    Container for the properties of an event.
This is very similar to a tkinter.Event, except that it holds a different
set of attributes. Instances of this type are generated if one of the
static or dynamic treectrl events occurs.
 
Static, i.e. installed into the widget by default, events include:
 
<ActiveItem>: Generated whenever the active item changes.
<Collapse-before>: Generated before an item is collapsed.
<Collapse-after>: Generated after an item is collapsed.
<Expand-before>: Generated before an item is expanded. This event is useful
                 if you want to add child items to the item just before the
                 item is expanded.
<Expand-after>: Generated after an item is expanded.
<ItemDelete>: Generated when items are about to be deleted by the
              item_delete() command.
<ItemVisibility>: Generated when items become visible on screen and when
                  items are no longer visible on screen. This event is
                  useful if you have a very large number of items and want
                  to assign styles only when items are actually going to be
                  displayed.
<Scroll-x>: Generated whenever the view in the treectrl changes in such a
            way that a horizontal scrollbar should be redisplayed.
<Scroll-y>: Generated whenever the view in the treectrl changes in such a
            way that a vertical scrollbar should be redisplayed.
<Selection>: Generated whenever the selection changes. This event gives
             information about how the selection changed.
 
In addition to the pre-defined static events such as <ActiveItem> and
<Selection>, new dynamic events can be created by using the
notify_install() command.
The following events may be generated by the library scripts:
 
<ColumnDrag-begin>
<ColumnDrag-receive>
<ColumnDrag-end>: Generated whenever the user drag-and-drops a column
                  header. The library scripts do not actually move a
                  dragged column. You must bind to the receive event to
                  move the column.
<ColumnDrag-indicator>: generated whenever the place to drop a dragged
                        column header is updated.
<Drag-begin>
<Drag-receive>
<Drag-end>: Generated whenever the user drag-and-drops a file into a
            directory. This event is generated by the filelist-bindings.tcl
            library code, which is not used by default.
<Edit-begin>
<Edit-accept>
<Edit-end>: The filelist-bindings.tcl code will display a text-editing
            window if the user clicks on a selected file/folder name.
<Header-invoke>: Generated whenever the user clicks and releases the left
                 mouse button in a column header if the column's -button
                 option is true.
                 You can bind a callback to this event to sort the list.
<Header-state>: generated whenever the state of an individual column
                header is changed during mouse-pointer events.
 
If a callback function for one of these events is registered using
notify_bind(), the callback is called with a TreectrlEvent as first
argument. It will have the following attributes (in braces are the event
types for which the attribute is valid):
 
detail - the detail name, e.g "after" if the event is "<Expand-after>"
        (all static events).
name - the event name, e.g "Expand" if the event is "<Expand-after>"
        (all static events).
pattern - the complete event pattern, either "<name>" or "<name-detail>"
        (all static events).
object - The object argument to the notify_bind() command
        (all static events).
widget - The treectrl widget which generated the event (all static events).
 
item - The item id (<Collapse>, <Expand>, <Drag>, <Edit> events).
 
active - The current active item (<ActiveItem> events).
prevactive - The previous active item (<ActiveItem> events).
 
deleteditems - List of items ids being deleted (<ItemDelete> events).
 
visible- List of items ids which are now visible (<ItemVisibility> events).
nonvisible - List of items ids which are no longer visible
        (<ItemVisibility> events).
 
lower - Same as the first fraction appended to -yscrollcommand
        (<Scroll> events).
upper - Same as the second fraction appended to -yscrollcommand
        (<Scroll> events).
 
selectcount - Same as the selection_count() widget command
        (<Selection> events).
deselected - List of newly-deselected item ids (<Selection> events).
selected - List of newly-selected item ids (<Selection> events).
 
textelement - The name of the edited text element (<Edit> events).
text - The edited text (<Edit> events).
 
column - The column that was dragged or whose header was clicked
         (<ColumnDrag>, <Header-invoke>, <Edit> events).
 
columnbefore - The column to move the dragged column before
        (<ColumnDrag> events).
 
draggeditems - The list of dragged items (<Drag> events).
 
 

 
Data
        __package__ = None
python-tktreectrl-2.0.1/doc/MultiListbox.html0000644000175000017500000004244112052764214021176 0ustar moellermoeller Python: module MultiListbox
 
 
MultiListbox
index
./TkTreectrl/MultiListbox.py

A flexible multi column listbox widget for Tkinter.

 
Classes
       
TkTreectrl.Treectrl.Treectrl(Tkinter.Widget)
MultiListbox

 
class MultiListbox(TkTreectrl.Treectrl.Treectrl)
    A flexible multi column listbox widget for Tkinter.
Based on the Treectrl widget, it offers the following additional
configuration options:
 
    columns -           a sequence of strings that defines the number of
                        columns of the widget. The strings will be used in
                        the columnheader lines (default: (' ',)).
    command -           an optional command that will be executed when the
                        user double-clicks into the listbox or presses the
                        Return key. The listbox index of the item that was
                        clicked on resp. of the currently active item is
                        passed as argument to the callback; if there is no
                        item at the event coordinates resp. no active item
                        exists, this index will be -1 (default: None).
    expandcolumns -     a sequence of integers defining the columns that
                        should expand horizontally beyond the requested
                        size when the widget is resized (note that the
                        rightmost column will always expand) (default: ()).
    selectcmd -         an optional callback that will be executed when the
                        selection of the listbox changes. A tuple
                        containing the indices of the currently selected
                        items as returned by curselection() will be passed
                        to the callback (default: None).
    selectbackground -  the background color to use for the selection
                        rectangle (default: #00008B).
    selectforeground -  the foreground color to use for selected text
                        (default: white).
 
By default, the widget uses one pre-defined style for all columns; the
widget's style() method allows to access and configure the default style,
as well as applying new user-defined styles per column.
The default style defines two elements, "text" and "select" (which
describes attributes of the selection rectangle); these may be accessed
and configured with the element() method. Conversion between listbox
indices and treectrl item descriptors can be done with the item() and
index() widget methods. Besides this, most common operations can be done
with methods identical or very similar to those of a Tkinter.Listbox, with
the exception of the selection_xxx() methods, where the treectrl methods
are kept intact; for Tkinter.Listbox alike methods, use select_xxx().
 
  Methods defined here:
__getitem__ = cget(self, key)
__init__(self, master=None, columns=(' ',), selectcmd=None, command=None, expandcolumns=(), showroot=False, selectforeground='white', selectbackground='#00008B', **kw)
activate(self, index)
Like Tkinter.Listbox.activate(). Note that this overrides the
activate() method inherited from Treectrl.
bbox(self, index, column=None, element=None)
Like item_bbox(), except that it requires a listbox index instead
of a treectrl item descriptor as argument. Note that this overrides the
bbox() method inherited from Treectrl.
cget(self, key)
column(self, index)
Return the column identifier for the column at INDEX.
config = configure(self, cnf=None, **kw)
configure(self, cnf=None, **kw)
curselection(self)
Like Tkinter.Listbox.curselection().
delete(self, first, last=None)
Like Tkinter.Listbox.delete() except that an additional index
descriptor ALL may be used, so that delete(ALL) is equivalent with
delete(0, END).
element(self, element)
Return the treectrl element corresponding to ELEMENT.
ELEMENT may be "text" or "select".
get(self, first, last=None)
Like Tkinter.Listbox.get(), except that each element of the returned
tuple is a tuple instead of a string; each of these tuples contains the
text strings per column of a listbox item.
index(self, which=None, item=None)
Like Tkinter.Listbox.index(), except that if ITEM is specified, the
listbox index for the treectrl item descriptor ITEM is returned.
insert(self, index, *args)
Similar to Tkinter.Listbox.insert(), except that instead of one
string a number of strings equal to the number of columns must be given
as arguments. It is an error to specify more or fewer arguments than
the number of columns. Returns the ID of the newly created item, as
returned by item_create().
item(self, index)
Return the treectrl item descriptor for the item at INDEX.
keys(self)
nearest(self, y)
Like Tkinter.Listbox.nearest().
numcolumns(self)
Return the number of listbox columns.
see(self, index, column=None, center=None)
Like Tkinter.Listbox.see(). Note that this overrides the
see() method inherited from Treectrl.
select_anchor(self, index=None)
Like Tkinter.Listbox.select_anchor(), except that it if no INDEX is
specified the current selection anchor will be returned.
select_clear(self, first=None, last=None)
Like Tkinter.Listbox.select_clear(), except that if no arguments are
specified, all items will be deleted, so that select_clear() is
equivalent with select_clear(0, END).
select_includes(self, index)
Like Tkinter.Listbox.select_includes().
select_set(self, first, last=None)
Like Tkinter.Listbox.select_set().
size(self)
Like Tkinter.Listbox.size().
sort(self, column=None, element=None, first=None, last=None, mode=None, command=None, notreally=False)
Like item_sort(), except that the item descriptor defaults to ROOT
(which is most likely wanted) and that the FIRST and LAST options
require listbox indices instead of treectrl item descriptors.
style(self, index, newstyle=None)
If NEWSTYLE is specified, set the style for the column at INDEX to
NEWSTYLE. Return the style identifier for the column at INDEX.

 
Data
        __package__ = None
python-tktreectrl-2.0.1/doc/ScrolledTreectrl.html0000644000175000017500000002464112052764204022014 0ustar moellermoeller Python: module ScrolledTreectrl
 
 
ScrolledTreectrl
index
./TkTreectrl/ScrolledTreectrl.py

Treectrl and MultiListbox widgets with scrollbars.

 
Modules
       
Tkinter
ttk

 
Classes
       
ttk.Frame(ttk.Widget)
ScrolledWidget
ScrolledMultiListbox
ScrolledTreectrl

 
class ScrolledMultiListbox(ScrolledWidget)
    MultiListbox widget with one or two static or automatic scrollbars.
Subwidgets are:
    listbox - TkTreectrl.MultiListbox widget
    hbar - horizontal Tkinter.Scrollbar or ttk.Scrollbar
    vbar - vertical Tkinter.Scrollbar or ttk.Scrollbar
The widget itself is a Tkinter.Frame or ttk.Frame with one additional
configuration option:
    scrollmode - may be one of "x", "y", "both" or "auto".
 
  Methods defined here:
__init__(self, *args, **kw)

 
class ScrolledTreectrl(ScrolledWidget)
    Treectrl widget with one or two static or automatic scrollbars.
Subwidgets are:
    treectrl - TkTreectrl.Treectrl widget
    hbar - horizontal Tkinter.Scrollbar or ttk.Scrollbar
    vbar - vertical Tkinter.Scrollbar or ttk.Scrollbar
The widget itself is a Tkinter.Frame or ttk.Frame with one additional
configuration option:
    scrollmode - may be one of "x", "y", "both" or "auto".
 
  Methods defined here:
__init__(self, *args, **kw)

 
class ScrolledWidget(ttk.Frame)
    Base class for Tkinter widgets with scrollbars.
The widget is a standard Tkinter.Frame or a ttk.Frame if ttk is available,
with an additional configuration option SCROLLMODE which may be one of
"x", "y", "both" or "auto".
If SCROLLMODE is one of "x", "y" or "both", one or two static scrollbars
will be drawn. If SCROLLMODE is set to "auto", two automatic scrollbars
that appear only if needed will be drawn.
In order to ensure backwards compatibility, ttk-incompatible configuration
options passed to the widget or to the scrollbars will be silently ignored
if ttk widgets are used.
The Scrollbar widgets can be accessed with the hbar and vbar class
attributes. Derived classes must override the _setScrolledWidget() method,
which must return the widget that will be scrolled and should add a class
attribute that allows to access this widget, so the _setScrolledWidget()
method for a ScrolledListbox widget might look like:
 
    def _setScrolledWidget(self):
        self.listbox = Tkinter.Listbox(self)
        return self.listbox
 
Note that although it should be possible to create scrolled widget classes
for virtually any Listbox or Canvas alike Tkinter widget you can *not*
safely use this class to add automatic scrollbars to a Text or Text alike
widget. This is because in a scrolled Text widget the value of the
horizontal scrollbar depends only on the visible part of the Text, not on
it's whole contents. Thus it may happen that it is the last visible line of
text that causes the automatic scrollbar to be mapped which then hides this
last line so it will be unmapped again, but then it is requested again and
gets mapped and so on forever. There are strategies to avoid this, but
usually at the cost that there will be situations where the horizontal
scrollbar remains mapped although it is actually not needed. In order to
acomplish this with the ScrolledWidget class, at least the _scrollXNow()
and _scrollBothNow() methods must be overridden with appropriate handlers.
 
  Methods defined here:
__getitem__ = cget(self, key)
__init__(self, master=None, **kw)
cget(self, key)
config = configure(self, cnf=None, **kw)
configure(self, cnf=None, **kw)
destroy(self)
keys(self)

 
Data
        __package__ = None
python-tktreectrl-2.0.1/ChangeLog0000644000175000017500000001242512141671426016656 0ustar moellermoellerTkinterTreectrl - ChangeLog ################################################################################ Nov. 29 2005: TkinterTreectrl-0.2 This release fixes two typos in the dragimage_add(), resp. dragimage_configure() methods. ################################################################################ Mar. 16 2006: TkinterTreectrl-0.3 Three library commands from FielListBindings.tcl have been added: set_dragimage(), set_editable() and set_sensitive(). These may be used to make text cells user-editable and to add elements to the dragimage for dnd operations. ################################################################################ Mar. 28 2006: TkinterTreectrl-0.4 A few bugs and some interface weirdnesses have been fixed: canvasx() and canvasy() now return integers as they should (not floats). The broken item_firstchild(), item_lastchild(), item_nextsibling() and item_prevsibling() have been fixed. item_children() now returns an empty tuple instead of None if the item in question does not have any children. A typo that stopped item_cget() from working was fixed. This release finally introduces a distutils installer script, so now you should be able to simply do: python setup.py install to do a decent install. ################################################################################ Oct. 04 2006: TkinterTreectrl-0.5 Converting the version number into a float sure does not work with Treectrl-2.1.1 (sigh!) , so I changed TreectrlVersion to be a string. ################################################################################ Nov. 30 2006: TkinterTreectrl-0.6 The major change in this release is the introduction of a few new widget classes: MultiListbox is a Treectrl widget set up to work as a (more or less) full-featured and very flexible multi column listbox widget. The ScrolledTreectrl and ScrolledMultiListbox classes use ideas shamelessly stolen from Pmw.ScrolledListbox to add one or two static or automatic scrollbars to the widgets. They both inherit from the ScrolledWidget class that is supposed to make it easy to add scrollbars to any other Listbox or Canvas alike Tkinter widget. Changes to the Treectrl widget: I added the second (optional) last argument to column_delete(), which is new in treectrl-2.1.1 . A bug in item_sort() was fixed: it is now possible to use the command and mode options together, which may be useful if you want to use the same command in ncreasing and decreasing mode. To enable this, mode now defaults to None instead of ascii. CAUTION: this change may be backwards incompatible in some cases! It is also possible now to specify a sequence of strings as mode, like mode=("integer", "decreasing"). The class variables TreectrlVersion, _last_element and _last_style were accidentally handled as instance variables, this has been fixed. ################################################################################ Jan. 22 2007: TkinterTreectrl-0.7 Added new features from treectrl-2.2 : new methods: bbox(), column_tag_add(), column_tag_expr(), column_tag_names(), column_tag_remove(), item_tag_add(), item_tag_expr(), item_tag_names(), item_tag_remove(), item_descendants(), item_enabled(). methods accepting new (optional) arguments: selection_get(), column_count(), item_count() Bug fixes: item_id() was broken if no matching item exists; item_dump() tried to convert textual strings into integers typo in constant LEFTMOST was fixed. Interface changes: item_id() now returns a tuple of matching ids instead of an integer; this is necessary, so the new feauture of multiple items matching the same tag can be used. CAUTION: this is backwards incompatible! ################################################################################ Nov. 10 2007: TkinterTreectrl-0.8 added __version__ attribute to __init__.py ; "package require treectrl" was only called when creating the first treectrl widget which seemed to fail in some situations; now on every widget creation "package require treectrl" is called. ################################################################################ Aug. 08 2010: TkinterTreectrl-1.0 MultiListbox.insert() now returns the item id of the newly created item; updated the documentation and the Treectrl class to reflect the changes and new features since treectrl-2.2 to treectrl-2.2.10; fixed a bug in Treectrl.selection_get() that caused a TypeError to be raised when selection_get() was called with "first" and/or "last" arguments and a single item was currently selected. ################################################################################ Nov. 20 2012: TkinterTreectrl-2.0 Added new methods from treectrl-2.3 and updated docs; added Python-3 compatibility; ScrolledTreectrl now uses themed widgets if ttk is available; added Treectrl._getboolean() as a workaround for tkapp.getboolean(), to make sure that True/False are always returned as boolean values , not 1/0; fixed a bug in ScrolledWidget._scrollMode() that caused the Scrollbars not to be drawn when the scrollmode changed from "auto" to "x" or "y". ################################################################################ May 06 2013: TkinterTreectrl-2.0.1 Fixed a bug in MultilistBox._configure_multilistbox() that prevented lists from being accepted as argument for the columns option (thanks to ВаÑилий МолоÑтов) python-tktreectrl-2.0.1/setup.py0000644000175000017500000000052112141670506016606 0ustar moellermoellerfrom distutils.core import setup version = '2.0' setup( name="TkinterTreectrl", version=version, description="Tkinter wrapper for TkTreectrl", author="Michael Lange", author_email="klappnase@users.sf.net", packages=['TkTreectrl'], url="http://tkintertreectrl.sourceforge.net", license="Public domain" ) python-tktreectrl-2.0.1/README0000644000175000017500000000121712141670450015755 0ustar moellermoellerTkinterTreectrl - README Python wrapper package for the Tktreectrl Tk extension library ( http://tktreectrl.sourceforge.net ). To install TkinterTreectrl, run: python setup.py install or, in case you have multiple version of Python installed, run (for example): python2.6 setup.py install to install into Python-2.6 . Alternatively you can manually copy the TkTreectrl folder into Python's site-packages folder, usually /usr/lib/python2.x/site-packages on unix or C:\Python2x\Lib\site-packages on windows platforms. License: The TkinterTreectrl package is released in the Public domain. Contact: Michael Lange python-tktreectrl-2.0.1/demo/0000755000175000017500000000000012052761604016023 5ustar moellermoellerpython-tktreectrl-2.0.1/demo/multilistbox.py0000644000175000017500000000451112052761564021142 0ustar moellermoellertry: from Tkinter import * except ImportError: from tkinter import * from TkTreectrl import * root = Tk() root.title('Simple MultiListbox demo') label = Label(root, text='Running self test, please wait...') label.pack(side='top', pady=5) m = MultiListbox(root) m.pack(side='top', fill='both', expand=1) Button(root, text='Close', command=root.quit).pack(side='top', pady=5) m.focus_set() def select_cmd(selected): print('Selected items:', selected) def dblclick_cmd(index): if index >= 0: cont = m.listbox.get(index) else: cont = '' print('Called "command" callback on item:', index, ':', cont) print('Currently selected:', m.listbox.curselection()) m.configure(selectcmd=select_cmd, command=dblclick_cmd, selectmode='extended') print('Nearest item to y-coordinate 80:', m.nearest(80)) def test1(): m.config(columns=('Column 1', 'Column 2', 'Column 3'), expandcolumns=(0, 1)) for x in range(20): m.insert('end', 'Foo', 'Bar', 'blah') def test2(): m.select_set(7) m.config(columns=('Column 1', 'Column 2'), expandcolumns=()) m.delete(5, 10) m.insert(3, 'foo', 'bar') def test3(): m.config(columns=('Foos', 'Bars'), expandcolumns=(0,)) m.delete(0, 'end') for x in range(20): m.insert('end', 'Foo %d' % x, 'Bar %d' % x) m.insert(7, 'Spam', 'Eggs') print('Nearest item to y-coordinate 80:', m.nearest(80), ':', m.get(m.nearest(80))) def test4(): m.sort(column=0, mode='decreasing') m.activate(10) m.select_set(0, 7) def test5(): m.sort(column=0, mode=('dictionary', 'increasing')) m.activate(1) print('index(8) :', m.index(8), ', index("end") :', m.index('end')) print('index("active") :', m.index("active"), ', index("@75,100") :', m.index("@75,100")) m.see('end') def test6(): m.see(0) print(m.select_includes(70), m.select_includes(6)) def test7(): m.sort(0, mode='decreasing', first=1, last=5) print('bbox(4):', m.bbox(4)) alltests = (test1, test2, test3, test4, test5, test6, test7) next = 0 def next_test(): global next try: test = alltests[next] test() next += 1 root.after(1000, next_test) except IndexError: pass if next == len(alltests): label.configure(text='Self test successfully finished') root.after(1000, next_test) root.mainloop() python-tktreectrl-2.0.1/demo/dirtree.py0000644000175000017500000001056112052761206020034 0ustar moellermoellertry: from Tkinter import * except ImportError: from tkinter import * from TkTreectrl import * import os import sys root = Tk() t = Treectrl(root, showrootbutton=1) t.pack(fill=BOTH, expand=1) # create a column and define it as the widget's treecolumn col = t.column_create(text="Basic directory tree browser", expand=1) t.configure(treecolumn=col) # create the elements of which a tree item will consist; use the treectrl's per-state option mechanism # to assign different options for different states where neccessary folder = PhotoImage(file=os.path.join(sys.path[0], 'folder.gif')) openfolder = PhotoImage(file=os.path.join(sys.path[0], 'openfolder.gif')) el_image = t.element_create(type=IMAGE, image=(openfolder, OPEN, folder, '')) el_text = t.element_create(type=TEXT, fill=('white', SELECTED)) el_select = t.element_create(type=RECT, showfocus=1, fill=('blue4', SELECTED)) # put the elements together to make a style st_folder = t.style_create() t.style_elements(st_folder, el_image, el_select, el_text) # layout options for look'n'feel: t.style_layout(st_folder, el_text, padx=8, pady=2) t.style_layout(st_folder, el_image, pady=2) t.style_layout(st_folder, el_select, union=(el_text,), ipadx=2, iexpand=NS) ############################################################ # things to make the text cells editable # ############################################################ # make sure that during editing the Entry widget uses the same colors as the tree elements root.option_add('*Entry*selectBackground', 'blue4') root.option_add('*Entry*selectForeground', 'white') # to enable editable cells define a new state "edit" t.state_define('edit') # hide the text and selection rectangle elements while editing # set the lines option to 1, because if the text element is configured to allow # multiple lines we get a text widget while editing instead of an entry # which does not look so good here t.element_configure(el_text, draw=(0, 'edit'), lines=1) t.element_configure(el_select, draw=(0, 'edit')) # apply the filelist bindings t.bindtags((t, 'TreeCtrlFileList', 'TreeCtrl', t.winfo_toplevel(), 'all')) t.set_sensitive((col, st_folder, el_text)) t.set_editable((col, st_folder, el_text)) # add callbacks for Edit events def edit_begin(event): t.itemstate_set(event.item, '~edit')# toggle "edit" state to "on" def edit_accept(event): t.itemelement_config(event.item, col, el_text, text=event.text)# apply the new text def edit_end(event): t.itemstate_set(event.item, '~edit')# toggle "edit" state to "off" t.notify_install('') t.notify_bind('', edit_begin) t.notify_install('') t.notify_bind('', edit_accept) t.notify_install('') t.notify_bind('', edit_end) ######################################################### # # ######################################################### # this shows how to add a dragimage t.set_dragimage((col, st_folder, el_text), (col, st_folder, el_image)) # define a callback to fill an opened item def open_dir(event): item = event.item if t.item_numchildren(item): # directory has already been drawn, don't bother to track changes to the directory structure here return # that's a trick: store the item's full path in the text element's data option path = t.itemelement_cget(item, col, el_text, 'data') try: dirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))] dirs.sort() except (OSError, IOError): dirs = [] for d in dirs: new = t.create_item(parent=item, button=1, open=0)[0] t.itemstyle_set(new, col, st_folder) t.itemelement_config(new, col, el_text, text=d, datatype=STRING, data=os.path.join(path, d)) # bind the callback to events t.notify_bind('', open_dir) # set up the root item t.itemstyle_set(ROOT, col, st_folder) if sys.platform == "win32": t.itemelement_config(ROOT, col, el_text, text='C:', datatype=STRING, data='C:\\') else: t.itemelement_config(ROOT, col, el_text, text=os.sep, datatype=STRING, data=os.sep) t.item_config(ROOT, button=1) # the root item is expanded by default but doesn't have any children yet, so we need to # generate an event to fill the root-directory t.notify_generate('', item=ROOT) t.see(ROOT) root.mainloop() python-tktreectrl-2.0.1/demo/openfolder.gif0000644000175000017500000000017010412216734020642 0ustar moellermoellerGIF89a Ò„„„ÆÆÆÿÿÿÿÿÿ!ù ,  b: return -1 elif a < b: return 1 else: return 0 elif b > a: return -1 elif b < a: return 1 else: return 0 # now create a common sort command for all columns def sort_list(event): # do the sorting if event.column == 0: m.listbox.sort(column=0, mode=sortorder_flags[0]) elif event.column == 1: m.listbox.sort(column=1, mode=('real', sortorder_flags[1])) else: m.listbox.sort(column=2, command=sort_by_rating, mode=sortorder_flags[2]) # switch the sortorder flag and turn the arrow icons upside down if sortorder_flags[event.column] == 'increasing': m.listbox.column_configure(m.listbox.column(event.column), arrow='up') sortorder_flags[event.column] = 'decreasing' else: m.listbox.column_configure(m.listbox.column(event.column), arrow='down') sortorder_flags[event.column] = 'increasing' # finally register the sort command m.listbox.notify_install('') m.listbox.notify_bind('', sort_list) ################################################################### ############## make the last column editable ###################### ################################################################### # for look'n'feel: while editing, floating Entry widgets are put on top # of cell that is being edited root.option_add('*Entry*selectForeground', m.listbox['selectforeground']) root.option_add('*Entry*selectBackground', m.listbox['selectbackground']) # define edit state and apply filelist bindings m.listbox.state_define('edit') m.listbox.bindtags((m.listbox, 'TreeCtrlFileList', 'TreeCtrl', m.listbox.winfo_toplevel(), 'all')) # make all columns sensitive to mouse events, but only column 2 editable setsensitive = [(m.listbox.column(i), m.listbox.style(i), m.listbox.element('text')) for i in range(m.listbox.numcolumns())] m.listbox.set_sensitive(*setsensitive) m.listbox.set_editable((m.listbox.column(2), m.listbox.style(2), m.listbox.element('text'))) # hide the old text while editing, that's what we need the "edit" state for m.listbox.element_configure(m.listbox.element('text'), draw=(0, 'edit'), lines=1) # a helper function for validating user input: def is_valid(text): # return True if text is a valid "rating" we will accept, else return False # reject empty strings and strings greater than 10 characters: if not (0 < len(text) < 11): return 0 # string must begin with "+" or "-": if not text[0] in ('+', '-'): return 0 # string must either contain only "+" or only "-": for sign in ('+', '-'): if text.startswith(sign): for char in text: if char != sign: return 0 return 1 # now define callbacks for edit event handlers; # the three mandatory handlers for making cells editable with a mouse click: def edit_begin(event): # toggle "edit" state to "on" m.listbox.itemstate_forcolumn(event.item, m.listbox.column(2), 'edit') def edit_accept(event): # if our demo claims to be "fancy", there should be some validating # of the user input... if is_valid(event.text): # apply the new text; we could use the listbox methods here, # but it's really easier with the treectrl method m.listbox.itemelement_config(event.item, m.listbox.column(2), m.listbox.element('text'), text=event.text) else: m.bell() def edit_end(event): # toggle edit state to "off" m.listbox.itemstate_forcolumn(event.item, m.listbox.column(2), '!edit') # a special callback to enable editing with the keyboard; # if you find a more obvious way to do this, send me a mail! def edit_invoke(event): # emulate a mouse-click onto the active "rating"; # in order to achieve this we first have to make the item visible and select it, # then calculate its x and y coords and generate the ButtonPress # and ButtonRelease events there index = m.listbox.index('active') if index > -1: m.listbox.see(index) m.listbox.select_set(index) x0, y0, x1, y1 = m.listbox.item_bbox(m.listbox.item(index), m.listbox.column(2), m.listbox.element('text')) x, y = (x0 + x1) / 2, (y0 + y1) / 2 m.listbox.event_generate('', x=x, y=y) m.listbox.event_generate('', x=x, y=y) # finally install the event handlers m.listbox.notify_install('') m.listbox.notify_bind('', edit_begin) m.listbox.notify_install('') m.listbox.notify_bind('', edit_accept) m.listbox.notify_install('') m.listbox.notify_bind('', edit_end) m.listbox.bind('', edit_invoke) # shows how to identify a clicked list item def on_button_1(event): info = m.listbox.identify(event.x, event.y) if not info: print('You clicked into the void.') elif info[0] == 'item': print('You clicked item', info[1], 'at listbox index', m.listbox.index(item=info[1])) elif info[0] == 'header': print('You clicked the column header of column', info[1]) m.listbox.bind('<1>', on_button_1, add=1) root.mainloop() python-tktreectrl-2.0.1/TkTreectrl/0000755000175000017500000000000012052764514017165 5ustar moellermoellerpython-tktreectrl-2.0.1/TkTreectrl/Treectrl.py0000644000175000017500000036400612052505054021324 0ustar moellermoeller# -*- coding: utf-8 -*- '''Wrapper module for the Tk treectrl widget.''' # TODO: # - methods that need to be fixed: # item_sort(): should accept multiple sets of arguments # itemstate_forcolumn(): should it be possible to pass further options? # itemstate_set(): see function comments # notify_generate() and notify_install() # the marquee_ methods need to be tested # Stand (6.7.12): 2.2.10 ist komplett # 2.3 - 2.3.2 ist komplett, weiter gehts mit 2.4 # aber erst gradient_xxx testen!! # 2.4 events + elements sind fertig -> testen # - weiter mit header methoden try: import tkinter except ImportError: import Tkinter as tkinter class TreectrlEvent: '''Container for the properties of an event. This is very similar to a tkinter.Event, except that it holds a different set of attributes. Instances of this type are generated if one of the static or dynamic treectrl events occurs. Static, i.e. installed into the widget by default, events include: : Generated whenever the active item changes. : Generated before an item is collapsed. : Generated after an item is collapsed. : Generated before an item is expanded. This event is useful if you want to add child items to the item just before the item is expanded. : Generated after an item is expanded. : Generated when items are about to be deleted by the item_delete() command. : Generated when items become visible on screen and when items are no longer visible on screen. This event is useful if you have a very large number of items and want to assign styles only when items are actually going to be displayed. : Generated whenever the view in the treectrl changes in such a way that a horizontal scrollbar should be redisplayed. : Generated whenever the view in the treectrl changes in such a way that a vertical scrollbar should be redisplayed. : Generated whenever the selection changes. This event gives information about how the selection changed. In addition to the pre-defined static events such as and , new dynamic events can be created by using the notify_install() command. The following events may be generated by the library scripts: : Generated whenever the user drag-and-drops a column header. The library scripts do not actually move a dragged column. You must bind to the receive event to move the column. : generated whenever the place to drop a dragged column header is updated. : Generated whenever the user drag-and-drops a file into a directory. This event is generated by the filelist-bindings.tcl library code, which is not used by default. : The filelist-bindings.tcl code will display a text-editing window if the user clicks on a selected file/folder name. : Generated whenever the user clicks and releases the left mouse button in a column header if the column's -button option is true. You can bind a callback to this event to sort the list. : generated whenever the state of an individual column header is changed during mouse-pointer events. If a callback function for one of these events is registered using notify_bind(), the callback is called with a TreectrlEvent as first argument. It will have the following attributes (in braces are the event types for which the attribute is valid): detail - the detail name, e.g "after" if the event is "" (all static events). name - the event name, e.g "Expand" if the event is "" (all static events). pattern - the complete event pattern, either "" or "" (all static events). object - The object argument to the notify_bind() command (all static events). widget - The treectrl widget which generated the event (all static events). item - The item id (, , , events). active - The current active item ( events). prevactive - The previous active item ( events). deleteditems - List of items ids being deleted ( events). visible- List of items ids which are now visible ( events). nonvisible - List of items ids which are no longer visible ( events). lower - Same as the first fraction appended to -yscrollcommand ( events). upper - Same as the second fraction appended to -yscrollcommand ( events). selectcount - Same as the selection_count() widget command ( events). deselected - List of newly-deselected item ids ( events). selected - List of newly-selected item ids ( events). textelement - The name of the edited text element ( events). text - The edited text ( events). column - The column that was dragged or whose header was clicked (, , events). columnbefore - The column to move the dragged column before ( events). draggeditems - The list of dragged items ( events).''' pass class Treectrl(tkinter.Widget): '''A treectrl is a widget which displays items in a one- or two-dimensional arrangement. Items have a parent-child relationship with other items. Items have a set of states, which are boolean properties. Items may be spread about one or more columns. For each column of an item there is a style associated, which determines how to display the item's column taking into account the item's current state set. One column can be defined to display the data in a hierarchical structure. Normally the origin of the coordinate system is at the upper-left corner of the window containing the treectrl. It is possible to adjust the origin of the coordinate system relative to the origin of the window using the xview() and yview() widget commands; this is typically used for scrolling. A treectrl widget can be horizontal or vertical oriented like many other Tk widgets. For displaying hierarchical data only vertical orientation is useful, since only then the children of an item are displayed directly below their parent. If the treectrl widget is used only to display data in a multicolumn listbox, the specification of an orientation will give useful results. STANDARD OPTIONS -background -borderwidth -cursor -font -highlightbackground -highlightcolor -highlightthickness -orient -relief -takefocus -xscrollcommand -yscrollcommand -foreground WIDGET SPECIFIC OPTIONS -backgroundimage Specifies the name of an image to draw as the list background. The image is tiled horizontally and vertically to fill the content area of the list. If the image is transparent it is drawn on top of the background color(s). -backgroundmode Specifies how the background color of items is chosen in each column. The value should be one of row, column, order, or ordervisible. The default is row. This option has only an effect for columns which have -itembackground defined as list of two or more colors (see section COLUMNS below for more on this). If row or column is specified, the background color is chosen based on the location of the item in the 1- or 2-dimensional grid of items as layed out on the screen; this layout of items is affected by the -orient and -wrap options as well as item visibility. When order or ordervisible is specified, the background color is chosen based on the result of the item order command, regardless of the layout of items. -bgimage Synonym for -backgroundimage (since 2.3) -bgimageanchor Controls the alignment of the -backgroundimage. The value is a standard Tk anchor position such as "nw", "se" or "center", etc. The image is aligned to the content area when the image doesn't scroll, otherwise the image is aligned to the canvas. The default is "nw". -bgimageopaque A boolean that indicates whether or not the -backgroundimage is partially transparent. This is needed because there is no way to tell in Tk whether an image contains transparency. The default is True, so if you use a transparent -backgroundimage you must set this to False. -bgimagescroll Controls whether the -backgroundimage scrolls along with the items or remains locked in place. The value can be an emptry string for no scrolling, "x" for horizontal scrolling only, "y" for vertical scrolling only, or "xy" (the default) for scrolling in both directions. -bgimagetile Controls whether the -backgroundimage is tiled along the x and y axes. The value can be "", "x", "y" or "xy" (the default). -buttonbitmap Specifies the bitmap to be used as the expand/collapse button to the left of an item. This is a per-state option. If a bitmap is specified for a certain item state, it overrides the effects of -usetheme. -buttoncolor Specifies the foreground color which should be used for drawing the outline and the plus or minus sign of the button to the left of an item. -buttonimage Specifies the image to be used as the expand/collapse button to the left of an item. This is a per-state option. If an image is specified for a certain item state, it overrides the effects of -buttonbitmap and -usetheme. -buttonsize Specifies the width and height of the button drawn to the left of an item in any of the forms acceptable to Tk_GetPixels. -buttonthickness Specifies the width of the outline and the plus or minus sign of the button to the left of an item in any of the forms acceptable to Tk_GetPixels. -buttontracking On Mac OS X and Gtk+ the expand/collapse buttons don't toggle when they are clicked, only when the mouse button is released over them, like regular pushbuttons. The value of this option is a boolean; when True the buttons toggle when the mouse button is released, when False the buttons toggle when clicked. The default is True on Mac OS X and Gtk+, False on Win32 and X11. -canvaspadx -canvaspady These options allow whitespace margins around the edges of the canvas. This is useful for 2D views where you don't want the items to butt against the window borders. The value of each option is a list of one or two screen distances specifying the width of the left/right margins and the height of the top/bottom margins respectively. -columnprefix Specifies an ascii string that changes the way column ids are reported and processed. If this option is a non-empty string, the usual integer value of a column id is prefixed with the given string. This can aid debugging but it is important your code doesn't assume column ids are integers if you use it. -columnproxy If this option specifies a non empty value, it should be a screen distance in any of the forms acceptable to Tk_GetPixels. Then a 1 pixel thick vertical line will be drawn at the specified screen distance from the left edge of the treectrl widget, which reaches from top to bottom of the treectrl widget and uses an inverting color (i.e black on lighter background, white on darker background). This line can be used to give the user a visual feedback during column resizing. -columnresizemode Specifies the visual feedback used when resizing columns. The value should be one of proxy or realtime. For proxy, a 1-pixel thick vertical line is drawn representing where the right edge of the column will be after resizing. For realtime, the column's size is changed while the user is dragging the right edge of the column. Since treectrl-2.3 the default value is "realtime", in earlier versions it used to be "proxy". -columntagexpr Specifies a boolean that enables or disables tag expressions in column descriptions. When the value of this option is False the characters (', ')', '&', '|', '^' and '!' have no special significance when using tags in column descriptions. This is useful for applications which may have arbitrary tags applied to columns or items. -defaultstyle Specifies a list of styles, one per column, to apply to each item created by the item create command. The number of styles in the list can be different from the number of tree columns. Each list element should be a valid style name or an empty string to indicate no style should be applied to a specific column. The list of styles is updated if a style is deleted or if a column is moved. This option is deprecated since treectrl-2.2, use column_configure(itemstyle=...) instead. -doublebuffer Specifies if double-buffering should be used to improve displaying. The value should be one of none, window, or item. For none no double-buffering is used at all, which may be most memory efficient, but will probably generate some flickering on the screen. For window the complete tree is double-buffered, which requires a buffer big enough to contain the complete widget. For item, which is the default, every item is separately double-buffered, so it works with a buffer size as big as the biggest item. This option has no effect since tktreectrl-2.2.10 . -headerfont This is the font used for drawing text in column headers. The default value is TkHeadingFont where that font is defined (usually on Tk 8.5+), otherwise it is the default listbox font. On Mac OS X, TkHeadingFont is the small system font used for drawing text in the fixed-height headers. This new option results in a different default look to column text on X11, where TkHeadingFont is a bold font. -headerfg -headerforeground The foreground text color used when drawing text in column headers. On Gtk+, the system theme may override this color. -height Specifies the desired height for the window in any of the forms acceptable to Tk_GetPixels. The default is 200 pixels. If this option is less than or equal to zero then the window will not request any size at all. -indent Specifies the amount of indentation in any of the forms acceptable to Tk_GetPixels. The default is 19 pixel. Indentation is the screen distance an item is displayed more to the right than its father. -itemgapx -itemgapy These options allow whitespace gaps between adjacent items. This is useful for 2D views such as an icon view in a file browser or an image thumbnail list. The value of each option is a screen distance defaulting to zero. -itemheight Specifies a fixed height for every item in any of the forms acceptable to Tk_GetPixels. If non-zero, this option overrides the requested height of an item and the -minitemheight option. The default is 0, which means that every item has the height requested by the arrangement of elements in each column. Items are never shorter than the maximum height of a button. -itemprefix Specifies an ascii string that changes the way item ids are reported and processed. If this option is a non-empty string, the usual integer value of an item id is prefixed with the given string. This can aid debugging but it is important your code doesn't assume item ids are integers if you use it. -itemtagexpr Specifies a boolean that enables or disables tag expressions in item descriptions. When the value of this option is False the characters (', ')', '&', '|', '^' and '!' have no special significance when using tags in item descriptions. This is useful for applications which may have arbitrary tags applied to columns or items. -itemwidth Specifies a fixed width for every item in any of the forms acceptable to Tk_GetPixels. If more than one column is visible, then this option has no effect. If the -orient option is vertical, and the -wrap option is unspecified, then this option has no effect (in that case all items are as wide as the column). -itemwidthequal Specifies a boolean that says whether all items should have the same width. If more than one column is visible, then this option has no effect. If the -orient option is vertical, and the -wrap option is unspecified, then this option has no effect (in that case all items are as wide as the column). If the -itemwidth option is specified, then this option has no effect. -itemwidthmultiple Specifies a screen distance that every item's width will be evenly divisible by in any of the forms acceptable to Tk_GetPixels. If more than one column is visible, then this option has no effect. If the -orient option is vertical, and the -wrap option is unspecified, then this option has no effect (in that case all items are as wide as the column). If the -itemwidth option is specified, then this option has no effect. -linecolor Specifies the color which should be used for drawing the connecting lines between related items. -linestyle Specifies the style of the connecting lines between related items, should be dot which is the default, or solid. -linethickness Specifies the thickness of the connecting lines between related items in any of the forms acceptable to Tk_GetPixels. -minitemheight Specifies a minimum height for every item in any of the forms acceptable to Tk_GetPixels. The default is 0, which means that every item has the height requested by the arrangement of elements in each column. This option has no effect if the -itemheight option is specified. Items are never shorter than the maximum height of a button. -scrollmargin The interpretation of this option is left to Tcl scripts that implement scrolling: the widget implementation ignores this option entirely. Defaults to 0. -selectmode Specifies one of several styles for manipulating the selection. The value of the option may be arbitrary, but the default bindings expect it to be either single, browse, multiple, or extended; the default value is browse. -showbuttons Specifies a boolean value that determines whether this widget displays a button to the left of any item. If the button is actually drawn can be configured for every item with the item hasbutton widget command, but if this option is set to false, the configuration of an item has no effect. The default value is True. -showheader Specifies a boolean value that determines whether this widget should display the header line with the column names at the top of the widget. The default value is True. -showlines Specifies a boolean value that determines whether this widget should draw the connecting lines between related items. In versions prior to trectrl-2.3 the default value was True. Since 2.3 the default value is False on Mac OS X and Gtk+, True on Win32 and X11. -showroot Specifies a boolean value that determines whether this widget should draw the root item. By suppressing the drawing of the root item the widget can have multiple items that appear as toplevel items. The default value is True. -showrootbutton Specifies a boolean value that determines whether this widget should draw a button before the root item. The default value is False. -showrootchildbuttons Specifies a boolean value that determines whether this widget should draw the expand/collapse buttons next to children of the root item. The default value is True. -showrootlines Specifies a boolean value that determines whether this widget should draw the connecting lines between children of the root item. The default value is True. -treecolumn Specifies a column description that determines which column displays the buttons and lines. The default is unspecified. -usetheme Specifies a boolean value that determines whether this widget should draw parts of itself using a platform-specific theme manager. Since treectrl-2.3 the default value is now True, in earlier versions the default used to be False. -width Specifies the desired width for the window in any of the forms acceptable to Tk_GetPixels. The default is 200 pixels. If this option is less than or equal to zero then the window will not request any size at all. -wrap Specifies whether items are arranged in a 1- or 2-dimensional layout. If the value is an empty string (the default), then items are arranged from top to bottom (orient='vertical') or from left to right (orient= 'horizontal') in a 1-dimensional layout. If the value is "N items", then no more than N items will appear in a vertical group (orient='vertical') or horizontal group (orient='horizontal'). If the value is "N pixels", then no vertical group of items will be taller than N pixels (orient='vertical') or no horizontal group of items will be wider than N pixels (orient='horizontal'). If the value is "window", then no vertical group of items will be taller than the window (orient='vertical') or no horizontal group of items will be wider than the window (orient='horizontal'). -xscrolldelay Specifies the amount of time before the default binding should handle repeating mouse motion events in horizontal direction with button 1 pressed. The value should be a sequence of 1 or 2 integers. The first integer specifies the timespan in microseconds before the active item should be changed to get nearer to the current mouse position. If there are two integers specified, the first is only used for the first motion event, any repeating motion events are handled after the seconds amount of miliseconds is elapsed. -xscrollincrement Specifies an increment for horizontal scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the horizontal view in the window will be constrained so that the x coordinate at the left edge of the window is always an even multiple of -xscrollincrement; furthermore, the units for scrolling (e.g., the change in view when the left and right arrows of a scrollbar are selected) will also be -xscrollincrement. If the value of this option is less than or equal to zero, then horizontal scrolling is unconstrained. -xscrollsmoothing -yscrollsmoothing When these options are set to true and the xview or yview commands are called to scroll by "units", scrolling occurs according to the -xscrollincrement or -yscrollincrement options, and all other scrolling is done as if the -xscrollincrement or -yscrollincrement options were set to 1. The effect is that when dragging the scrollbar thumb scrolling is very smooth, but when clicking the scrollbar buttons scrolling is done in coarser increments. -yscrolldelay Specifies the amount of time before the default binding should handle repeating mouse motion events in vertical direction with button 1 pressed. The value should be a list of 1 or 2 integers. The first integer specifies the timespan in microseconds before the active item should be changed to get nearer to the current mouse position. If there are two integers specified, the first is only used for the first motion event, any repeating motion events are handled after the seconds amount of miliseconds is elapsed. -yscrollincrement Specifies an increment for vertical scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the vertical view in the window will be constrained so that the y coordinate at the top edge of the window is always an even multiple of -yscrollincrement; furthermore, the units for scrolling (e.g., the change in view when the top and bottom arrows of a scrollbar are selected) will also be -yscrollincrement. If the value of this option is less than or equal to zero, then vertical scrolling is unconstrained.''' TreectrlVersion = None _last_element = 0 _last_gradient = 0 _last_style = 0 def __init__(self, master=None, cnf={}, **kw): if tkinter._support_default_root: if not master: if not tkinter._default_root: tkinter._default_root = tkinter.Tk() master = tkinter._default_root ver = master.tk.call('package', 'require', 'treectrl') if not Treectrl.TreectrlVersion: Treectrl.TreectrlVersion = ver tkinter.Widget.__init__(self, master, 'treectrl', cnf, kw) def _configure(self, cmd, cnf, kw): """Internal function.""" # modified version of Tkinter's _configure() if kw: cnf = tkinter._cnfmerge((cnf, kw)) elif cnf: cnf = tkinter._cnfmerge(cnf) if cnf is None: cnf = {} s = self.tk.split(self.tk.call(tkinter._flatten((self._w, cmd)))) try: for x in s: cnf[x[0][1:]] = (x[0][1:],) + x[1:] except TypeError: # this happens in notify_configure(), where the output doesn't # conform to tk standards; instead of a list of the form: # {-data {} {} {} {}} {-datatype {} {} {} {}}} etc. # we get a string like: -active 1 there s = (s, ) for x in s: cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if isinstance(cnf, str): x = self.tk.split(self.tk.call( tkinter._flatten((self._w, cmd, '-'+cnf)))) return (x[0][1:],) + x[1:] self.tk.call(tkinter._flatten((self._w, cmd)) + self._options(cnf)) def _create(self, itemType, args, kw): """Internal function.""" # mainly stolen from tkinter.Canvas args = tkinter._flatten(args) if args: cnf = args[-1] if isinstance(cnf, (dict, tuple)): args = args[:-1] else: cnf = {} else: cnf = {} return self.tk.call(self._w, itemType, 'create', *(args + self._options(cnf, kw))) def _getboolean(self, value): '''Simple workaround for tkapp.getboolean() which sometimes returns 0/1 and sometimes returns True/False. This always returns either True or False.''' return (self.tk.getboolean(value) and True) or False _subst_format_notify = ('%b', '%c', '%d', '%e', '%i', '%h', '%l', '%p', '%t', '%u', '%v', '%C', '%D', '%E', '%H', '%I', '%P', '%S', '%W', '%T') _subst_format_str_notify = " ".join(_subst_format_notify) def _substitute_notify(self, *args): """Internal function.""" if len(args) != len(self._subst_format_notify): return args def getint_event(s): try: return int(s) except ValueError: return s def getints_event(l): try: return self._getints(l) except ValueError: return l b, c, d, e, i, h, l, p, t, u, v, C, D, E, H, I, P, S, W, T = args ev = TreectrlEvent() # standard attributes ev.detail = d ev.name = e ev.pattern = P # object may be a widget or a column try: ev.object = self._nametowidget(W) except KeyError: ev.object = getint_event(W) try: ev.widget = self._nametowidget(T) except KeyError: ev.widget = T # , , , # , ev.item = getint_event(I) # ev.active = getint_event(c) ev.prevactive = getint_event(p) # ev.deleteditems = getints_event(i) # ev.visible = getints_event(v) ev.nonvisible = getints_event(h) # , ev.lower = l ev.upper = u # ev.selectcount = getint_event(c) ev.deselected = getints_event(D) ev.selected = getints_event(S) # , ev.column = getint_event(C) # ev.columnbefore = getint_event(b) # ev.draggeditems = getints_event(l) # ev.textelement = E ev.text = t # ,

ev.header = getint_event(H) return (ev,) def activate(self, itemDesc): '''Sets the active item to the one described by ITEMDESC, and switches on the state ACTIVE for this item. From now on the item can be retrieved with the item description ACTIVE. An event is generated.''' self.tk.call(self._w, 'activate', itemDesc) def bbox(self, area=None): '''Returns a list with four elements giving the bounding box (left, top, right and bottom) of an area of the window. If AREA is not specified, then the result is the bounding box of the entire window. If AREA is CONTENT, then the result is the part of the window not including borders, headers, or locked columns. If AREA is HEADER, then the result is the part of the window not including borders where column titles are displayed. If AREA is LEFT, then the result is the part of the window not including borders or headers where left-locked columns are displayed. If AREA is RIGHT, then the result is the part of the window not including borders or headers where right-locked columns are displayed. None is returned if the display area has no height or width, which can be true for various reasons such as the window is too small, or the header is not displayed, or there aren't any locked columns.''' return self._getints(self.tk.call(self._w, 'bbox', area)) def canvasx(self, screenx): '''Given a window x-coordinate in the treectrl screenx, this command returns the treectrl x-coordinate that is displayed at that location.''' return int(self.tk.call(self._w, 'canvasx', screenx)) def canvasy(self, screeny): '''Given a window y-coordinate in the treectrl screeny, this command returns the treectrl y-coordinate that is displayed at that location.''' return int(self.tk.call(self._w, 'canvasy', screeny)) def column_bbox(self, column): '''Returns a list with four elements giving the bounding box for the column header specified by COLUMN. If the treectrl is configured not to display the column headers by means of the showheader option, then None is returned instead.''' return self._getints(self.tk.call( self._w, 'column', 'bbox', column)) or None def column_cget(self, column, option): '''This command returns the current value of the option named OPTION for the column specified by COLUMN. COLUMN may also be the string TAIL to specify the tail column. OPTION may have any of the values accepted by the column_configure() widget command.''' return self.tk.call(self._w, 'column', 'cget', column, '-'+option) def column_configure(self, column, cnf=None, **kw): '''This command is similar to the configure() widget command except that it modifies options associated with the column specified by COLUMN instead of modifying options for the overall treectrl widget. COLUMN may be the string TAIL to specify the tail column. If COLUMN is the string ALL, at least one option-value pair must be given; in this case all the columns are configured. Available options are: arrow arrowbitmap arrowgravity arrowimage arrowpadx arrowpady arrowside background bitmap borderwidth button expand font gridleftcolor gridrightcolor image imagepadx imagepady itembackground itemjustify itemstyle justify lock maxwidth minwidth resize squeeze state stepwidth tags text textcolor textlines textpadx textpady uniform visible weight width widthhack''' return self._configure(('column', 'configure', column), cnf, kw) column_config = column_configure def column_compare(self, column1, op, column2): '''From both columns the index is retrieved (as returned from the column_order() widget command). Then these indexes are compared using the operator OP, which must be either <, <=, ==, >=, >, or !=. The return value of this command is True if the comparison evaluated to true, False otherwise.''' return self._getboolean(self.tk.call( self._w, 'column', 'compare', column1, op, column2)) def column_count(self, *args): '''If no additional argument is given, returns an integer giving the number of columns created by the column_create() widget command which haven't been deleted by the column_delete() widget command. The tail column is not counted in this case. If argument(s) are given, the result is the number of columns that match the column description. For example: self.colum_count('visible') will return the number of columns whose -visible option is True, and: self.column_count('tag', 'a^b') will return the number of columns with either tag "a" or "b", but not both. Multiple column descriptions may be combined, like: self.column_count('tag', 'foo', 'tag', 'bar', 'visible')''' return int(self.tk.call(self._w, 'column', 'count', args or None)) def column_create(self, *args, **kw): '''This command creates a new column in the treectrl widget. The new column is placed to the right of all other columns (except the tail column). Any option-value arguments configure the new column according to the column_configure() command. The return value is the unique identifier of the new column.''' return int(self._create('column', args, kw)) create_column = column_create def column_delete(self, first, last=None): '''Deletes the specified column(s) from the treectrl widget. If either FIRST or LAST is specified as ALL, then all columns are deleted. The tail column cannot be deleted and it is an error to specify it. The order of first and last doesn't matter, and first may be equal to last.''' self.tk.call(self._w, 'column', 'delete', first, last) delete_column = column_delete def column_dragcget(self, option): return self.tk.call(self._w, 'column', 'dragcget', option) def column_dragconfigure(self, cnf=None, **kw): '''The user can move a column within a treectrl by drag-and-drop. Feedback consists of a semi-transparent photo image of the header of the column being dragged and a 2-pixel-thick vertical line to indicate where the column may be dropped. The drag image consists of a colored background rectangle plus the image and/or text displayed in the column header. The 2-pixel-thick line will be drawn over the left edge of the column before which the dragged column may be dropped. The library scripts generate a event when the user has successfully drag-and-drop'd a column. You will have to bind a callback to this event if you want to move the dragged column.''' return self._configure(('column', 'dragconfigure'), cnf, kw) def column_id(self, column): '''This command resolves the column description COLUMN into a unique column identifier. If the column described by COLUMN doesn't exist, this command returns None.''' return self.tk.call(self._w, 'column', 'id', column) or None def column_list(self, visible=False): '''This command returns a list of identifiers for every column (except the tail) from left to right. If VISIBLE is True, only columns whose visible option is True are returned.''' if visible: return self.tk.splitlist(self.tk.call( self._w, 'column', 'list', '-visible')) return self.tk.splitlist(self.tk.call(self._w, 'column', 'list')) def column_move(self, column, before): '''Moves the specified COLUMN to the left of the column specified by BEFORE. If BEFORE is the string TAIL, the column COLUMN will become the last column.''' self.tk.call(self._w, 'column', 'move', column, before) def column_neededwidth(self, column): '''This command returns an integer giving the needed width of the column specified by COLUMN. The needed width is the maximum of the width of the column header and the width of the widest currently visible item.''' return int(self.tk.call(self._w, 'column', 'needewidth', column)) def column_order(self, column, visible=False): '''This command returns an integer giving the position of COLUMN in the list of columns starting from zero for the leftmost column. If VISIBLE is True, only columns whose visible option is True are considered, and -1 is returned if COLUMN's visible option is False.''' if visible: return int(self.tk.call( self._w, 'column', 'order', column, '-visible')) return int(self.tk.call(self._w, 'column', 'order', column)) def column_tag_add(self, column, *tags): '''Adds each tag in TAGS to the columns specified by the column description COLUMN. Duplicate tags are ignored. The list of tags for a column can also be changed via column_configure(tags=(...)).''' self.tk.call(self._w, 'column', 'tag', 'add', column, tags) def column_tag_expr(self, column, tag): '''Evaluates the tag expression TAG against every column specified by the column description COLUMN. The result is True if the tag expression evaluates to True for every column, False otherwise.''' return self._getboolean(self.tk.call( self._w, 'column', 'tag', 'expr', column, tag)) def column_tag_names(self, column): '''Returns a list of tag names assigned to the columns specified by the column description COLUMN. The result is the union of any tags assigned to the columns.''' return self.tk.splitlist(self.tk.call( self._w, 'column', 'tag', 'names', column)) def column_tag_remove(self, column, *tags): '''Removes each tag in TAGS from the columns specified by the column description COLUMN. It is not an error if any of the columns do not use any of the tags. The list of tags for a column can also be changed via column_configure(tags=(...).''' self.tk.call(self._w, 'column', 'tag', 'remove', column, tags) def column_width(self, column): '''This command returns an integer giving the width in pixels of the column specified by COLUMN, even if the treectrl is configured to not display the column headers by means of the showheader option''' return int(self.tk.call(self._w, 'column', 'width', column)) def contentbox(self): '''Returns a tuple with four elements giving the bounding box for the space used to display the items, i.e. the space of the treectrl window without the surrounding borders or the column headers. The return value is None if the content area is totally obscurred by column headers, borders, and/or locked columns. Typically this will only happen if the window is too small.''' return self._getints(self.tk.call(self._w, 'contentbox')) def debug_cget(self, element, option): '''This command returns the current value of the debugging option named OPTION. OPTION may have any of the values accepted by the debug configure widget command.''' return self.tk.call(self._w, 'debug', 'cget', element, option) def debug_configure(self, element, cnf=None, **kw): '''This command is similar to the configure widget command except that it modifies debugging options instead of modifying options for the overall treectrl widget. If no option is specified, the command returns a list describing all of the available debugging options.''' return self._configure(('debug', 'configure', element), cnf, kw) def debug_dinfo(self): '''For every of the treectrl widget a line with some internal values info about all items is printed to stdout.''' self.tk.call(self._w, 'debug', 'dinfo') def debug_scroll(self): '''Returns a string useful for debugging vertical scrolling.''' return self.tk.call(self._w, 'debug', 'scroll') def depth(self, itemDesc=None): '''If the additional argument ITEMDESC is specified, returns an integer giving the depth of the item describing by ITEMDESC, whereas depth is defined as the number of steps you must go upward to reach to root item. If no ITEMDESC is specified, the maximum depth of all items in the treectrl widget is returned instead.''' return int(self.tk.call(self._w, 'depth', itemDesc)) def dragimage_add(self, itemDesc, column=None, element=None): '''Adds the shapes of the item described by ITEMDESC to the shapes of the dragimage. Specifying additional arguments reduces the number of rectangles that are added to the dragimage. If no additional arguments is specified, for every element of the item in every column a dotted rectangles is added. If COLUMN is specified, all elements in other columns are ignored. If also ELEMENT is specified, only a rectangle for this one element of the specified item in the given column is added.''' return self.tk.call( self._w, 'dragimage', 'add', itemDesc, column, element) def dragimage_cget(self, option): '''This command returns the current value of the dragimage option named OPTION. OPTION may have any of the values accepted by the dragimage_configure() widget command.''' return self.tk.call(self._w, 'dragimage', 'cget', option) def dragimage_clear(self): '''Removes all shapes (if there are any) from the dragimage. This command does not modify the dragimage offset.''' self.tk.call(self._w, 'dragimage', 'clear') def dragimage_configure(self, cnf=None, **kw): '''This command is similar to the configure widget command except that it modifies the dragimage options instead of modifying options for the overall treectrl widget. If no option is specified, the command returns a list describing all of the available dragimage options ''' return self._configure(('dragimage', 'configure'), cnf, kw) dragimage_config = dragimage_configure def dragimage_offset(self, x=None, y=None): '''Returns a list containing the x and y offsets of the dragimage, if no additional arguments are specified. The dragimage offset is the screen distance, the image is displayed relative to the item its shape is derived from. If two coordinates are specified, sets the dragimage offset to the given coordinates X and Y.''' return self._getints(self.tk.call( self._w, 'dragimage', 'offset', x, y)) def element_cget(self, element, option): '''This command returns the current value of the option named OPTION associated with the element given by ELEMENT. OPTION may have any of the values accepted by the element_configure() widget command.''' return self.tk.call(self._w, 'element', 'cget', element, '-'+option) def element_configure(self, element, cnf=None, **kw): '''This command is similar to the configure() widget command except that it modifies options associated with the element given by ELEMENT instead of modifying options for the overall treectrl widget. If no option is specified, the command returns a list describing all of the available options for ELEMENT.''' return self._configure(('element', 'configure', element), cnf, kw) element_config = element_configure def element_create(self, name=None, type=None, *args, **kw): '''Create a new elememt in SELF of type TYPE with name NAME. The exact format of the arguments after type depends on TYPE, but generally consist of specifications for zero or more element options. This command returns the name for the new element.''' if name is None: Treectrl._last_element += 1 name = 'pyelement' + str(Treectrl._last_element) return self._create('element', (name, type, args), kw) create_element = element_create def element_delete(self, *elements): '''Deletes each of the named ELEMENTS. If an element is deleted while it is still configured as an element of one or more styles by means of the style_elements() widget command, it is also removed from the element lists of these styles.''' self.tk.call(self._w, 'element', 'delete', *elements) delete_element = element_delete def element_names(self): '''Returns a list containing the names of all existing elements.''' return self.tk.splitlist(self.tk.call(self._w, 'element', 'names')) def element_perstate(self, element, option, *statelist): '''This command returns the value of the per-state option named option for element for a certain state. StateList is a list of state names (static and dynamic) which specifies the state to use.''' return self.tk.call( self._w, 'element', 'perstate', element, '-'+option, statelist) def element_type(self, element): '''Returns the type of the elements given by ELEMENT, such as "rect" or "text".''' return self.tk.call(self._w, 'element', 'type', element) def gradient_cget(self, gradient, option): '''Returns the current value of the configuration option for the gradient specified by GRADIENT whose name is OPTION. Option may have any of the values accepted by the gradient_configure() command.''' return self.tk.call(self._w, 'gradient', 'cget', gradient, '-'+option) def gradient_configure(self, gradient, cnf=None, **kw): '''This command is similar to the configure() widget command except that it modifies options associated with the gradient given by GRADIENT instead of modifying options for the overall treectrl widget. If no option is specified, the command returns a list describing all of the available options for GRADIENT. The following options are supported (see gradient create for the meaning of each option): bottom left orient right steps stops top''' return self._configure(('gradient', 'configure', gradient), cnf, kw) gradient_config = gradient_configure def gradient_create(self, name=None, *args, **kw): '''Creates a new gradient with the name NAME, which must be a unique name not used by another gradient created by this treectrl widget. If NAME is None a unique name will be created by the widget. The following options are supported: -bottom coordSpec -left coordSpec -right coordSpec -top coordSpec Each of these options specifies one edge of the gradient brush. If the option is specified as an empty string (the default), the gradient brush's edge is the same as that of whatever rectangle is being painted using the gradient. The format of each of these options is a tuple of 2 or more values (value, coordType, ?arg ...?), where value is a floating point number (usually from 0.0 to 1.0) and coordType is one of AREA, CANVAS, COLUMN or ITEM. The AREA keyword must be followed by one of the same area names that the bbox command accepts. The COLUMN keyword may be followed by a column description specifying exactly one column. The ITEM keyword may be followed by an item description specifying exactly one item. -orient direction This option specifies the direction a linear gradient changes color in. Must be either horizontal (the default) or vertical or an abbreviation of one of these. -steps stepCount Specifies the number of bands of color drawn for each color stop described by the -stops option. The default value is 1, the maximum is 25. This option has no effect if gradients are drawn using something better than Tk API calls. -stops stopsList Specifies the color stops along this gradient. The argument stopsList has the following form: ((offset color ?opacity?), (offset color ?opacity?) ...) Each offset is a floating point number from 0.0 to 1.0 specifying the distance from the start of the gradient where the color begins. Each color is a Tk color name or description. Each optional opacity is a floating point number from 0.0 to 1.0 specifying how transparent the gradient is. If stopsList is non-empty there must be at least two stops specified, and the first offset must be 0.0 and the last offset must be 1.0. Any other stop offsets must be listed in increasing order. Specifying opacity has no effect if gradients are drawn using Tk API calls.''' if name is None: Treectrl._last_gradient += 1 name = 'pygradient' + str(Treectrl._last_gradient) return self._create('gradient', (name, args), kw) create_gradient = gradient_create def gradient_delete(self, *gradients): '''Deletes each gradient specified in GRADIENTS. If the gradient is still being used then it is not actually deleted until all elements etc using the gradient have stopped using it. A deleted-but-in-use gradient is not recognized by the various gradient commands. Creating a new gradient with the same name as a deleted-but-in-use gradient resurrects the deleted gradient.''' self.tk.call(self._w, 'gradient', 'delete', *gradients) delete_gradient = gradient_delete def gradient_names(self): '''Returns a list of names of all the gradients that have been created by this treectrl widget.''' return self.tk.splitlist(self.tk.call(self._w, 'gradient', 'names')) def gradient_native(self, preference=None): '''Without any arguments, this command returns a boolean indicating whether or not the platform supports native transparent gradients. The preference argument is a boolean that indicates whether native gradients should be used; this can be used to test the appearance of the application.''' return self._getboolean(self.tk.call( self._w, 'gradient', 'native', preference)) def identify(self, x, y): '''Returns a list containing some diagnostics about what is displayed at the given windows coordinates x and y. The resulting list may be empty, if nothing is displayed at the given coordinates, otherwise the first list element is "header" or "item". If the coordinates are in the header area and thus the first element of the result is header, the number of the column or the string tail is the second element in the resulting list; if the x coordinate is near the left or right end of the header, a third element left or right is added respectively. If the coordinates are below the header area and thus the first element of the result is item, the numerical id of the item is the second element in the resulting list. If the x coordinate doesn't fall into the column displaying the hierarchical structure, the elements column and the column number are added. If the x coordinate is within the column displaying the hierarchical structure, the following elements are added to the resulting list: line and the numerical id of the item the line comes from, if the x coordinate is above an item connecting line; button, if the x coordinate is above a button; column, the column number, elem, and the element name, if the x coordinate is above an element of the item; column and the column number, if the x coordinate is to the right of the elements; nothing otherwise.''' return self.tk.splitlist(self.tk.call(self._w, 'identify', x, y)) def item_ancestors(self, itemDesc): '''Returns a list containing the item ids of the ancestors of the item specified by itemDesc. The first list value is the parent, the second is the parent's parent, an so on. The last list value will be the root item if itemDesc is a descendant of the root item.''' return self._getints(self.tk.call( self._w, 'item', 'ancestors', itemDesc)) def item_bbox(self, itemDesc, column=None, element=None): '''Returns a list with four elements giving the bounding box for the item described by itemDesc. If no further argument is specified, the bbox spans the area of the item over all columns. If a column is specified, only the area of the item in this column is considered, if an additional element is specified, the area of this element in column of the specified item is returned.''' return self._getints(self.tk.call( self._w, 'item', 'bbox', itemDesc, column, element)) or None def item_buttonstate(self, itemDesc, state=None): '''If STATE is specified, this command sets the state of the expand/collapse button for the single item specified by ITEMDESC. The state argument may be one of ACTIVE, NORMAL or PRESSED. The current (or newly-set) state of the button is returned. The button state is used by the system theme, if any, to change the appearance of the button.''' return self.tk.call(self._w, 'item', 'buttonstate', itemDesc, state) def item_cget(self, itemDesc, option): '''Returns the current value of the configuration option for the item specified by ITEMDESC whose name is OPTION. OPTION may have any of the values accepted by the item_configure() command.''' return self.tk.call(self._w, 'item', 'cget', itemDesc, '-'+option) def item_children(self, itemDesc): '''Returns a list containing the item ids of all children of the item specified by ITEMDESC in the correct order from the first child to the last child.''' return self._getints(self.tk.call( self._w, 'item', 'children', itemDesc)) or () def item_collapse(self, itemDesc, recurse=False, animate=False): '''Switches off the open state of the item(s) described by ITEMDESC. If the item has descendants, they are no longer displayed. If the item is configured to have a button, the button will now display the image or bitmap configured with the widget options -buttonimage or -buttonbitmap, or a + sign if no image or bitmap is configured. If the item is already closed, this command has no effect. ITEMDESC may also be the string ALL, in which case all items of the treectrl widget are collapsed. If ANIMATE is True, then the item's button will animate as it transitions between states if the theme supports it; in this case only one item may be specified. If RECURSE is True, all descendants of ITEMDESC will also be collapsed. For every item, that actually will be collapsed, two events are generated: a event before the item state is changed, and a event after the item state was changed.''' args = (self._w, 'item', 'collapse', itemDesc) if recurse: args += ('-recurse',) if animate: args += ('-animate',) self.tk.call(*args) def item_compare(self, itemDesc1, op, itemDesc2): '''From both items described by the ITEMDESCs the index is retrieved (as returned from the item_order() widget command). Then these indexes are compared using the operator OP, which must be either <, <=, ==, >=, >, or != . The return value of this command is True if the comparison evaluated to true, False otherwise.''' return self._getboolean(self.tk.call( self._w, 'item', 'compare', itemDesc1, op, itemDesc2)) def item_configure(self, itemDesc, cnf=None, **kw): '''If no option is specified, returns a list describing all of the available options for the item given by ITEMDESC. 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 item option(s) to have the given value(s); in this case the command returns an empty string. The following options are supported by this command (see item_create() for the meaning of each option): button boolean height height tags tuple visible boolean wrap boolean''' return self._configure(('item', 'configure', itemDesc), cnf, kw) item_config = item_configure def item_count(self, *args): '''If no additional argument is given, returns an integer giving the number of items created by the item_create() widget command which haven't been deleted by the item_delete() widget command, plus 1 for the ever-present root item. If argument(s) are given, the result is the number of items that match the item description. For example: self.item_count('visible') will return the number of items whose -visible option is true, and: self.item_count('tag', 'a^b') will return the number of items with either tag "a" or "b", but not both. Multiple item descriptions may be combined, like: self.item_count('tag', 'foo', 'tag', 'bar', 'visible')''' return int(self.tk.call(self._w, 'item', 'count', args or None)) def item_create(self, *args, **kw): '''Creates some new items and optionally returns a list of unique identifiers for those items. The new items have the states open and enabled set by default. If the treectrl widget currently has the focus, the state focus is also set. The following options are supported by this command: -button boolean Boolean indicates whether or not an expand/collapse button should be drawn next to this item, typically to indicate the item has children. The button will only be displayed if: a) the column specified by the treectrl option -treecolumn is visible; and b) the treectrl option -showbuttons is true -count numItems Specifies the number of items to create. Must be >= 0. Defaults to 1. -enabled boolean Specifies whether the items should be enabled. Default is true. -height height Specifies a fixed height in any of the forms acceptable to Tk_GetPixels. Must be >= 0. If height is zero then the item's height is unspecified. Defaults to 0. -nextsibling itemDesc Specifies the item before which the new items will be inserted. The new items will have the same parent as itemDesc. -open boolean Specifies whether the items should be open or closed. Default is true. -parent itemDesc Specifies the item which the new items will be the children of. The new items will be appended to the list of children of itemDesc. -prevsibling itemDesc Specifies the item after which the new items will be inserted. The new items will have the same parent as itemDesc. -returnid boolean Specifies whether or not to return a list of item identifiers for the newly created items. Specifying false is useful when creating a large number of items in the console or to improve performance. Default is true. -tags tuple Tags are textual labels applied to items to group them. Tags do not affect the appearance or behaviour of items. Tags can be used in item descriptions to operate on multiple items. -visible boolean It indicates that the item should be displayed in the list. The item will only be displayed if: a) each ancestor is a descendant of the root item (not an orphan); and b) each ancestor's -visible option is true. -wrap boolean When this option is true an item will be the first in a horizontal (when the treectrl option -orient=horizontal) or a vertical (when the treectrl option -orient=vertical) range of items. ''' return self._getints(self._create('item', args, kw)) or None create_item = item_create def item_delete(self, first, last=None): '''Deletes the specified item(s). FIRST and LAST must be the string ALL or a valid item description. If either FIRST or LAST is specified as ALL, then all items are deleted. If FIRST is specified and LAST isn't specified, the item described by FIRST is deleted. If both FIRST and LAST are specified, they must decribe items with a common ancestor; then the range of items between FIRST and LAST is deleted. Deleting an item deletes any child items of the deleted item recursively. If the current active item is deleted, the root item becomes the new active item. If the current selection anchor item is deleted, the root item becomes the new anchor item. There is no way to delete the root item of the treectrl widget; in all cases the specification of the root item is ignored. For each call to this command, two events may be generated. If any of the deleted items are selected, then a event is generated just before the items are deleted. If any items were actually deleted, then an event is generated just before the items are deleted.''' self.tk.call(self._w, 'item', 'delete', first, last) delete_item = item_delete def item_descendants(self, itemDesc): '''Returns a tuple containing the item ids of the descendants of the item specified by itemDesc, i.e. the children, grandchildren, great-grandchildren etc, of the item.''' return self._getints(self.tk.call( self._w, 'item', 'descendants', itemDesc)) def item_dump(self, itemDesc): '''Returns a list with four elements in the form (index, *index*, indexVis, *indexVis*).''' return self.tk.splitlist(self.tk.call( self._w, 'item', 'dump', itemDesc)) def itemelement_cget(self, itemDesc, column, element, option): '''This command returns the value of the option named OPTION associated with ELEMENT inside COLUMN of the item described by ITEMDESC, if it was already configured for the actual item. OPTION may have any of the values accepted by the type of the specified ELEMENT.''' return self.tk.call(self._w, 'item', 'element', 'cget', itemDesc, column, element, '-'+option) def itemelement_configure(self, itemDesc, column, element, cnf=None, **kw): '''This command is similar to the configure widget command except that it modifies options associated with ELEMENT inside COLUMN of the item described by ITEMDESC instead of modifying options for the overall treectrl widget. If no option is specified, the command returns a list describing all of the available options for the element''' return self._configure(('item', 'element', 'configure', itemDesc, column, element), cnf, kw) itemelement_config = itemelement_configure def itemelement_perstate(self, itemDesc, column, element, option, *statelist): '''This command returns the current value of the per-state option named OPTION for ELEMENT inside COLUMN of the item described by ITEMDESC. If STATELIST is specified, the list of state names (static and dynamic) is used in place of the current state for ITEM and COLUMN.''' return self.tk.call(self._w, 'item', 'element', 'perstate', itemDesc, column, element, '-'+option, statelist) def item_enabled(self, itemDesc, enabled=None): '''Returns True if the item described by ITEMDESC has the state "enabled" switched on, False otherwise. If ENABLED is specified, then the "enabled" state of every item described by the item description ITEMDESC is set accordingly. All items are enabled when first created. Disabled items cannot be selected, and are ignored by the default key-navigation and mouse bindings.''' return self._getboolean(self.tk.call( self._w, 'item', 'enabled', itemDesc, enabled)) def item_expand(self, itemDesc, recurse=False, animate=False): '''Switches on the open state of the item(s) described by ITEMDESC. If the item has descendants, they are now displayed. If the item is configured to have a button, the button will now display the image or bitmap configured with the widget options -buttonimage or -buttonbitmap, or a - sign if no image or bitmap is configured. If the item is already open, this command has no effect. If ANIMATE is specified, then the item's button will animate as it transitions between states if the theme supports it; in this case only one item may be specified. ItemDesc may also be the string ALL, in which case all items of the treectrl widget are expanded. If RECURSE is True, all descendants of ITEMDESC will also be expanded. For every item, that actually will be expanded, two events are generated: an event before the item state is changed, and an event after the item state was changed.''' args = (self._w, 'item', 'expand', itemDesc) if recurse: args += ('-recurse',) if animate: args += ('-animate',) self.tk.call(*args) def item_firstchild(self, parent, child=None): '''If CHILD is not specified, returns the item id of the first child of the item described by PARENT. If CHILD is specified, it must describe an item that is not an ancestor of PARENT. Then it will become the new first child of PARENT.''' res = self.tk.call(self._w, 'item', 'firstchild', parent, child) if res == '': return None return int(res) def item_id(self, itemDesc): '''New in treectrl-2.2 : This command resolves the item description ITEMDESC into a tuple of unique item identifier(s).If ITEMDESC doesn't refer to any existing items, then this command returns None. For example: self.item_id(ALL) will return a tuple of ids for all items, and: self.item_id(self.item_children(someItem)) will return the ids of every child of an item. On previous versions of the treectrl widget, a tuple containing only one item id will be returned.''' return self._getints(self.tk.call(self._w, 'item', 'id', itemDesc)) def item_image(self, itemDesc, *columnAndImage): '''This command sets or retrieves the value of the per-state -image option for the first image element in one or more columns. If no column is specified, this command returns a list of values, one per column. If no image is specified, this command returns the value for column. If one or more column-image pairs is specified, then the value of the -image option in each column is set to image. Note that this command is provided as a convenience. Use the itemelement_configure() or itemelement_cget() commands if you want to set or retrieve the value of the -image option for a specific image element.''' return self.tk.splitlist(self.tk.call( self._w, 'item', 'image', itemDesc, *columnAndImage)) or None def item_isancestor(self, itemDesc, descendant): '''Returns True if the item described by ITEMDESC is a direct or indirect parent of the item decribed by DESCENDANT, False otherwise.''' return self._getboolean(self.tk.call( self._w, 'item', 'isancestor', itemDesc, descendant)) def item_isopen(self, itemDesc): '''Returns True if the item described by itemDesc has the state open switched on, False otherwise.''' return self._getboolean(self.tk.call( self._w, 'item', 'isopen', itemDesc)) def item_lastchild(self, parent, child=None): '''If CHILD is not specified, returns the item id of the last child of the item described by PARENT. If CHILD is specified, it must describe an item that is not an ancestor of PARENT. Then it will become the new last child of PARENT.''' res = int(self.tk.call(self._w, 'item', 'lastchild', parent, child)) if res == '': return None return int(res) def item_nextsibling(self, sibling, next=None): '''If NEXT is not specified, returns the item id of the next sibling of the item described by SIBLING. If NEXT is specified, it must describe an item that is not an ancestor of SIBLING. Then it will become the new next sibling of SIBLING.''' res = self.tk.call(self._w, 'item', 'nextsibling', sibling, next) if res == '': return None return int(res) def item_numchildren(self, itemDesc): '''Returns the number of children of the item described by ITEMDESC.''' return int(self.tk.call(self._w, 'item', 'numchildren', itemDesc)) def item_order(self, itemDesc, visible=False): '''This command returns the position of the item ITEMDESC relative to its toplevel ancestor (usually the root item, unless the ancestor is an orphan). If you imagine all the items flattened into a vertical list, the result of this command is the row the item falls in. If the optional argument -visible is given, only the items whose ancestors are expanded, and whose -visible option is true, get counted; in this case -1 is returned if the item is not visible.''' if visible: return int(self.tk.call( self._w, 'item', 'order', itemDesc, '-visible')) return int(self.tk.call(self._w, 'item', 'order', itemDesc)) def item_parent(self, itemDesc): '''Returns the item id of the parent of the item described by ITEMDESC.''' return int(self.tk.call(self._w, 'item', 'parent', itemDesc)) def item_prevsibling(self, sibling, prev=None): '''If PREV is not specified, returns the item id of the previous sibling of the item described by SIBLING. If PREV is specified, it must describe an item that is not an ancestor of SIBLING. Then it will become the new previous sibling of SIBLING.''' res = self.tk.call(self._w, 'item', 'prevsibling', sibling, prev) if res == '': return None return int(res) def item_range(self, first, last): '''Returns a list containing the item ids of all items in the range between FIRST and LAST, inclusive. The order between FIRST and LAST doesn't matter, and the result is always sorted by the increasing order of the items (as returned by the item order command). The items specified by FIRST and LAST must share a common ancestor.''' return self._getints(self.tk.call( self._w, 'item', 'range', first, last)) def item_remove(self, itemDesc): '''Removes the item described by ITEMDESC from the list of children of its parent, so that it will become an orphan.''' self.tk.call(self._w, 'item', 'remove', itemDesc) def item_rnc(self, itemDesc): '''Returns a list of two integers, which corresponds to the row and column of the item described by ITEMDESC. The row and column corresponds to the on-screen arrangement of items as determined by the -orient and -wrap options. If the item is not displayed, this command returns None.''' return self._getints(self.tk.call( self._w, 'item', 'rnc', itemDesc)) or None def item_sort(self, itemDesc, column=None, element=None, first=None, last=None, mode=None, command=None, notreally=False): '''Sorts the children of the item described by ITEMDESC, and redisplays the tree with the items in the new order. The range of items which should be sorted can be restricted by means of the FIRST and/or LAST options, which should be children of the item described by ITEMDESC; the order between these two limiting items doesn't matter. The sort column can be specified by means of the COLUMN option; this option can be used repeatedly to define a multicolumn sort. The sorting is done by looking at the text of the element specified by the ELEMENT option, which must be a text element defined in the style of the sorting column; by default the first text element is used. If the NOTREALLY option is True, no rearranging of the items is done; instead the sorted items are returned as result of the command. By default ASCII sorting is used with the result returned in increasing order. Any of the following options (or a sequence of options) may be specified as MODE to control the sorting process of the previously specified column (unique abbreviations are accepted): ascii Use string comparison with ASCII collation order. This is the default. command command Use command as a comparison command. To compare two items, evaluate a command with the numerical ids of the two items passed as arguments. The comamnd should return an integer less than, equal to, or greater than zero if the first item is to be considered less than, equal to, or greater than the second, respectively. decreasing Sort the items in decreasing order ("largest" items first). dictionary Use dictionary-style comparison. This is the same as -ascii except (a) case is ignored except as a tie-breaker and (b) if two strings contain embedded numbers, the numbers compare as integers, not characters. For example, in -dictionary mode, bigBoy sorts between bigbang and bigboy, and x10y sorts between x9y and x11y. increasing Sort the items in increasing order ("smallest" items first). This is the default. integer Convert to integers and use integer comparison. real Convert to floating-point values and use floating comparison.''' # FIXME: looks ugly, but at least it seems to work now... # the problem is that the order of the args seems to matter here args = (self._w, 'item', 'sort', itemDesc) if column != None: args = args + ('-column', column) if element != None: args = args + ('-element', element) if first != None: args = args + ('-first', first) if last != None: args = args + ('-last', last) if command != None: cmd = self._register(command) args = args + ('-command', cmd) if mode: # mode may be a string or a sequence of strings if isinstance(mode, str): args = args + ('-' + mode,) else: args = args + tuple(['-' + m for m in mode]) if notreally: notreally = '-notreally' else: notreally = None args = args + (notreally,) return self.tk.splitlist(self.tk.call(*args)) or None def item_span(self, itemDesc, *columnAndNumColumns): '''This command sets or retrieves the number of columns that a style covers. If no column is specified, the return value is a list of spans, one per column. If no numColumns is specified, the return value is the span for column. If one or more column-numColumns pairs is specified, the span for each column is set to numColumns.''' if not columnAndNumColumns: return self._getints(self.tk.call( self._w, 'item', 'span', itemDesc)) if not columnAndNumColumns[1:]: return int(self.tk.call( self._w, 'item', 'span', itemDesc, *columnAndNumColumns)) self.tk.call(self._w, 'item', 'span', itemDesc, *columnAndNumColumns) def itemstate_forcolumn(self, itemDesc, column, *statenames): '''Just like itemstate_set() but manipulates dynamic states for a single item column, not the item as a whole. If STATENAME is unspecified, this command returns a list containing the names of all the dynamic states which are switched on in COLUMN.''' return self.tk.splitlist(self.tk.call(self._w, 'item', 'state', 'forcolumn', itemDesc, column, statenames or None)) or None def itemstate_get(self, itemDesc, statename=None): '''If no STATENAME is specified, returns a list containing the names of all (static and dynamic) states which are currently switched on for the item described by ITEMDESC. If a STATENAME is specified, True is returned if the specified state is currently switched on for the item, False otherwise.''' if statename: return self._getboolean(self.tk.call( self._w, 'item', 'state', 'get', itemDesc, statename)) return self.tk.splitlist(self.tk.call( self._w, 'item', 'state', 'get', itemDesc)) def itemstate_set(self, first, last, *statenames): '''Every element of STATENAMES must be the name of a dynamic state, optionally preceded by a ~ or ! character. Every state with a leading ! will be switched off for the item described by FIRST, every state with a leading ~ will be toggled, and every state without leading ! or ~ will be switched on. If LAST is specified, the state changes will be made for all items in the range between FIRST and LAST. If LAST is set to None, only the state(s) of the item described by FIRST will be changed. If FIRST is the string ALL, then the state changes are made for all items of the treectrl widget.''' # Too bad, this was poorly designed in the first version and now we # cannot fix it without making it backwards incompatible; # say we have two states "foo" and "bar", the following works: # tree.itemstate_set(2, '~bar') but # tree.itemstate_set(2, '~foo', '~bar') gives an error: # _tkinter.TclError: item "~foo" doesn't exist # so instead we need to do: # tree.itemstate_set(2, None,'~foo', '~bar') # which seems somewhat clumsy; # tree.itemstate_set(2, 4, '~foo', '~bar') # at least works as expected. # Another odd thing is that if we pass an empty tuple as "statenames" # it will be silently ignored by Tk, however if we pass None, we get: # _tkinter.TclError: wrong # args: should be # ".4128887724.4128887980 item state set item ?last? stateList" , # as one would expect. # The same happens of course in tcl with: # % .t item state set 0 {} -> ok vs. % .t item state set 0 "" -> err. # As this behavior is not documented it is probably better to be strict # about this and not allow empty statenames tuples # To make this all a little less awkward than the first version, # we can differ between three ways to invoke this function: # 1. tree.itemstate_set(2, None,'~foo', '~bar') -> the proper way if last is None: self.tk.call(self._w, 'item', 'state', 'set', first, statenames or None) # 2. tree.itemstate_set(2, 4, '~foo', '~bar') -> the proper way # beware: tree.itemstate_set(2, '~foo', '~bar') will raise a TclError ! elif statenames: self.tk.call(self._w, 'item', 'state', 'set', first, last, statenames) # 3. tree.itemstate_set(2, '~bar') -> bad, but we better keep this # legal, otherwise we would break existing code else: # now "last" actually serves as our statenames tuple self.tk.call(self._w, 'item', 'state', 'set', first, (last,)) def itemstyle_elements(self, itemDesc, column): '''This command returns a list containing the names of elements which were configured by the itemelement_configure() command for the item described by ITEMDESC in COLUMN. If there is no style assigned to COLUMN, None is returned.''' try: return self.tk.splitlist(self.tk.call( self._w, 'item', 'style', 'elements', itemDesc, column)) except tkinter.TclError: return None def itemstyle_map(self, itemDesc, column, style, *map): '''Like the itemstyle_set() command, this command may be used to assign a style to a specific column of an item. Unlike itemstyle_set(), this command can transfer configuration values of elements in the current style to elements in the new style specified by STYLE. MAP must be a list of elementOld-elementNew pairs, where elementOld is an element in the current style, and elementNew is an element in the style specified by style. Both elementOld and elementNew must be of the same type (bitmap, text etc).''' self.tk.call(self._w, 'item', 'style', 'map', itemDesc, column, style, map) def itemstyle_set(self, itemDesc, *columnAndStyle): '''This command sets or retrieves the style assigned to one or more columns. If no COLUMN is specified, this command returns a tuple containing the names of the styles set for all columns of the item described by ITEMDESC. If no STYLE is specified, this command returns the name of the style set for the item described by ITEMDESC in COLUMN. If one or more column-style pairs is specified, then the style in each column is set to style.''' return self.tk.splitlist(self.tk.call(self._w, 'item', 'style', 'set', itemDesc, *columnAndStyle)) or None def item_tag_add(self, itemDesc, *tags): '''Adds each tag in TAGS to the items specified by the item description ITEMDESC. Duplicate tags are ignored. The list of tags for an item can also be changed via item_configure(tags=(...)).''' self.tk.call(self._w, 'item', 'tag', 'add', itemDesc, tags) def item_tag_expr(self, itemDesc, tag): '''Evaluates the tag expression TAG against every column specified by the item description ITEMDESC. The result is True if the tag expression evaluates to true for every item, False otherwise. For example: self.item_tag_expr(itemDesc, 'foo') returns True if an item has tag "foo". Also: self.item_tag_expr(itemDesc, 'a||b') returns True if an item has tag "a" or "b".''' return self._getboolean(self.tk.call( self._w, 'item', 'tag', 'expr', itemDesc, tag)) def item_tag_names(self, itemDesc): '''Returns a list of tag names assigned to the items specified by the item description ITEMDESC. The result is the union of any tags assigned to the items.''' return self.tk.splitlist(self.tk.call( self._w, 'item', 'tag', 'names', itemDesc)) def item_tag_remove(self, itemDesc, *tags): '''Removes each tag in TAGS from the items specified by the item description ITEMDESC. It is not an error if any of the items do not use any of the tags. The list of tags for an item can also be changed via item_configure(tags=(...).''' self.tk.call(self._w, 'item', 'tag', 'remove', itemDesc, tags) def item_text(self, itemDesc, *columnAndText): '''This command sets or retrieves the value of the -text option for the first text element in one or more columns. If no COLUMN is specified, this command returns a list of values, one per column. If no TEXT is specified, this command returns the value for COLUMN. If one or more column-text pairs is specified, then the value of the -text option in each column is set to text. Note that this command is provided as a convenience. Use the itemelement_configure() or itemelement_cget() commands if you want to set or retrieve the value of the -text option for a specific text element.''' return self.tk.splitlist(self.tk.call(self._w, 'item', 'text', itemDesc, *columnAndText)) or None def item_toggle(self, itemDesc, recurse=False, animate=False): '''Changes the open state of the item(s) described by ITEMDESC. If the state is currently switched off, this command does the same as the item_expand() widget command, otherwise the same as the item_collapse() widget command. If ANIMATE is specified, then the item's button will animate as it transitions between states if the theme supports it; in this case only one item may be specified.ITEMDESC may also be the string ALL, in which case the state of all items of the treectrl widget are toggled. If RECURSE is specified, the state of all descendants of ITEMDESC will also be toggled.''' args = (self._w, 'item', 'toggle', itemDesc) if recurse: args += ('-recurse',) if animate: args += ('-animate',) self.tk.call(*args) def marquee_anchor(self, x=None, y=None): '''Returns a list containing the x and y coordinates of the anchor, if no additional arguments are specified. If two coordinates are specified, sets the anchor to the given coordinates X and Y.''' return self._getints(self.tk.call( self._w, 'marquee', 'anchor', x, y)) or None def marquee_cget(self, option): '''This command returns the current value of the marquee option named OPTION. OPTION may have any of the values accepted by the marquee_configure() widget command.''' return self.tk.call(self._w, 'marquee', 'cget', '-'+option) def marquee_configure(self, cnf=None, **kw): '''This command is similar to the configure() widget command except that it modifies the marquee options instead of modifying options for the overall treectrl widget. The following marquee options are supported: -fill Specifies the fill color for the selection rectangle. The value can be a Tk color or a gradient name or an empty string (the default). When this option isn't an empty string the dotted outline is not drawn. By specifying the name of a semi-transparent gradient a modern-looking selection rectangle can be achieved. -outline Specifies the outline color for the selection rectangle. The value can be a Tk color, a gradient name, or an empty string which is the default. When this option isn't an empty string the dotted outline is not drawn. -visible boolean Specifies a boolean value which determines whether the dotted line surrounding the region of the marquee should currently be visible.''' return self._configure(('marquee', 'configure'), cnf, kw) def marquee_coords(self, x1=None, y1=None, x2=None, y2=None): '''Returns a list containing the x and y coordinates of the anchor followed by the x and y coordinates of the corner, if no additional arguments are specified. If four coordinates are specified, sets the anchor to the given coordinates x1 and y1 and the corner to the coordinates x2 and y2. ''' return self._getints(self.tk.call(self._w, 'marquee', 'coords', x1, y1, x2, y2)) or None def marquee_corner(self, x=None, y=None): '''Returns a list containing the x and y coordinates of the corner, if no additional arguments are specified. If two coordinates are specified, sets the corner to the given coordinates x and y.''' return self._getints(self.tk.call( self._w, 'marquee', 'corner', x, y)) or None def marquee_identify(self): '''Returns a list with information about the items inside the marquee. The list has as elements a list itself for every item which is displayed inside the marquee. The first element of these lists is the numerical item id, followed by another list with information about every column of the item inside the marque. These lists start with the column number, followed by the elements of the style defined for the item in this column if there are any.''' return self.tk.splitlist(self.tk.call(self._w, 'marquee', 'identify')) def notify_bind(self, sequence=None, func=None, object=None, add=None): '''This command associates Tcl scripts with events generated by a treectrl widget. If all three arguments are specified, notify_bind() will arrange for FUNC to be evaluated whenever the event(s) specified by SEQUENCE are generated by this treectrl widget. If ADD is True, then it is appended to any existing binding for SEQUENCE; otherwise FUNC replaces any existing binding. If FUNC is an empty string, then the current binding for SEQUENCE is destroyed, leaving SEQUENCE unbound. If SEQUENCE is specified without a FUNC, then the script currently bound to SEQUENCE is returned, or an empty string is returned if there is no binding for SEQUENCE. If neither SEQUENCE nor FUNC is specified, then the return value is a list whose elements are all the patterns for which there exist bindings for object. The OBJECT argument determines which window(s) the binding applies to. If OBJECT begins with a dot, as in .a.b.c, then it must be the path name for a window; otherwise it may be an arbitrary string. Like the regular bind command, bindings on window names are automatically removed if that window is destroyed.''' # mainly stolen from tkinter.Misc._bind() if object in (None, self): object = self._w if isinstance(func, str): self.tk.call(self._w, 'notify','bind', object, sequence, func) elif func: funcid = self._register(func, self._substitute_notify, 1) cmd = ('%sif {"[%s %s]" == "break"} break\n' % ( add and '+' or '', funcid, self._subst_format_str_notify)) self.tk.call(self._w, 'notify','bind', object, sequence, cmd) return funcid elif sequence: return self.tk.call(self._w, 'notify','bind', object, sequence) or None else: return self.tk.splitlist(self.tk.call( self._w, 'notify','bind', object)) def notify_configure(self, object, sequence, cnf=None, **kw): '''This command sets and retrieves options for bindings created by the notify_bind() command. If no option is specified, the command returns a list with option-value pairs describing all the available binding options for SEQUENCE on OBJECT. If option is specified with no value, then the command returns the current value of that option. If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s) for the binding; in this case the command returns an empty string. The following binding options are supported: -active boolean Specifies if the binding should be active. As long as this option is specified as false, a binding script will not be evaluated when the corresponding event is generated.''' return self._configure(('notify', 'configure', object, sequence), cnf, kw) notify_config = notify_configure def notify_detailnames(self, eventname): '''Returns a list containing the names of all details, which are installed for the event with the name EVENTNAME by means of the notify_install() widget command or by the treectrl widget itself.''' return self.tk.splitlist(self.tk.call( self._w, 'notify', 'detailnames', eventname)) def notify_eventnames(self): '''Returns a list containing the names of all events, which are installed by means of the notify_install() widget command or by the treectrl widget itself.''' return self.tk.splitlist(self.tk.call(self._w, 'notify', 'eventnames')) def notify_generate(self, sequence, charmap=None, percentscommand=None, **kw): '''This command causes the treectrl widget to generate an event. This command is typically used to generate dynamic events created by the notify_install() command, but may be used to generate static events also. The event specified by SEQUENCE is generated, and any active binding scripts on the event are evaluated after undergoing %-substitution. If there are details defined for the event, SEQUENCE must describe an pair, otherwise SEQUENCE should be . The optional CHARMAP is a tuple of char-value pairs. Each char has to be exactly one character. The charMap is used in %-substitution. If PERCENTSCOMMAND is specified, then it will be used to perform %-substitution on any scripts bound to the event. If PERCENTSCOMMAND is not specified and the event is dynamic, then the %-subtitution command passed to notify_install() will be used if it was provided. If the event is static or no %-substitution command is available, then all %-substitution is done using CHARMAP only . See notify_install() for a description of PERCENTSCOMMAND. If no CHARMAP is specified, a default charmap will be created, that contains information about the widget and the event pattern, plus optional information provided by keyword-value pairs; any of the attributes of a TreectrlEvent instance as created by a notify_bind() callback is accepted as keyword argument.''' if charmap is None: charmap = ['b', None, 'c', None, 'd', None, 'e', None, 'i', None, 'h', None, 'l', None, 'p', None, 't', None, 'u', None, 'v', None, 'C', None, 'D', None, 'E', None, 'I', None, 'P', sequence, 'S', None, 'W', self._w, 'T', self._w] if 'columnbefore' in kw: charmap[1] = kw['columnbefore'] if 'active' in kw or 'selectcount' in kw: try: charmap[3] = kw['active'] except KeyError: charmap[3] = kw['selectcount'] # get name and detail s = sequence.strip('<').strip('>') try: charmap[5] = s.split('-')[1] except IndexError: pass charmap[7] = s.split('-')[0] if 'deleteditems' in kw: charmap[9] = kw['deleteditems'] if 'nonvisible' in kw: charmap[11] = kw['nonvisible'] if 'lower' in kw or 'draggeditems' in kw: try: charmap[13] = kw['lower'] except KeyError: charmap[13] = kw['draggeditems'] if 'prevactive' in kw: charmap[15] = kw['prevactive'] if 'text' in kw: charmap[17] = kw['text'] if 'upper' in kw: charmap[19] = kw['upper'] if 'visible' in kw: charmap[21] = kw['visible'] if 'column' in kw: charmap[23] = kw['column'] if 'deselected' in kw: charmap[25] = kw['deselected'] if 'textelement' in kw: charmap[27] = kw['textelement'] if 'item' in kw: charmap[29] = kw['item'] if 'selected' in kw: charmap[33] = kw['selected'] if 'object' in kw: charmap[35] = kw['object'] charmap = tuple(charmap) self.tk.call(self._w, 'notify', 'generate', sequence, charmap, percentscommand) def notify_install(self, sequence, percentscommand=None): '''This command installs a new event or detail specified by SEQUENCE. Events created by this command are called dynamic, whereas events created by the treectrl widget itself are called static. This command may be called to set or retrieve the PERCENTSCOMMAND for an existing dynamic event. The optional PERCENTSCOMMAND is a list containing the name of a Tcl command, plus any optional arguments, to which five additional arguments will be appended. The command will be called to perform %-substitution on any scripts bound to the event specified by SEQUENCE. notify_install() returns the current PERCENTSCOMMAND for the event, or an error if the event is not dynamic.''' # FIXME: percentscmd return self.tk.call(self._w, 'notify', 'install', sequence, percentscommand) or None #raise 'Function not yet implemented: "notify_install()"' def notify_linkage(self, sequence): '''Returns a string indicating whether the specified event or detail is created by means of the notify_install() widget command (dynamic) or by the treectrl widget itself (static).''' return self.tk.call(self._w, 'notify', 'linkage', sequence) def notify_unbind(self, object, sequence=None): '''If no SEQUENCE is specified, all bindings on OBJECT are removed. If SEQUENCE is specified, then the current binding for SEQUENCE is destroyed, leaving SEQUENCE unbound.''' self.tk.call(self._w, 'notify', 'unbind', object, sequence) def notify_uninstall(self, sequence): '''If the event or detail specified by SEQUENCE is static (i.e. created by the treectrl widget itself), an error is generated. Otherwise the dynamic event or detail is removed. If an event name is specified without a detail, all details for that event are also removed.''' self.tk.call(self._w, 'notify', 'uninstall', sequence) def orphans(self): '''Returns a list containing the item ids of all items which have no parent. When an item is created, it has no parent by default, and can later become an orphan by means of the item_remove() widget command. The root item is not returned.''' return self._getints(self.tk.call(self._w, 'orphans')) def state_define(self, statename): '''Defines a new state with the name STATENAME, which must not be the name of an existing state.''' self.tk.call(self._w, 'state', 'define', statename) def state_linkage(self, statename): '''Returns a string indicating whether the specified state is user-defined by means of the state_define() widget command (dynamic) or predefined by the treectrl widget itself (static).''' return self.tk.call(self._w, 'state', 'linkage', statename) def state_names(self): '''Returns a list containing the names of all user-defined states.''' return self.tk.splitlist(self.tk.call(self._w, 'state', 'names')) def state_undefine(self, statename): '''STATENAME must be the name of a user-defined state. Removes this state from the list of user-defined states.''' self.tk.call(self._w, 'state', 'undefine', statename) def see(self, itemDesc, column=None, center=None): '''Adjust the view in the treectrl so that the item described by ITEMDESC is visible. If the item is already visible then the command has no effect; otherwise the treectrl scrolls to bring the item into view, and the corresponding and/or events are generated. If COLUMN is specified then a specific column of the item is scrolled into view instead of the entire item. CENTER may be a string that contains zero or more of the characters "x" or "y". This option is used to center the item horizontally and/or vertically in the window. The item will be centered regardless of whether it is already visible.''' args = (itemDesc, column) if not center is None: args += ('-center', center) self.tk.call(self._w, 'see', *args) def selection_add(self, first, last=None): '''FIRST and LAST (if specified) must be the string ALL or a valid item description. Adds every unselected item in the range between FIRST and LAST, inclusive, to the selection without affecting the selection state of items outside that range. If one of the arguments is the string ALL, every unselected item in the treectrl widget is added to the selection. A event is generated if any items were added to the selection.''' self.tk.call(self._w, 'selection', 'add', first, last) def selection_anchor(self, itemDesc=None): '''If ITEMDESC is specified, the selection anchor is set to the described item. The selection anchor is the end of the selection that is fixed while dragging out a selection with the mouse. The item description anchor may be used to refer to the anchor item. This command doesn't modify the selection state of any item. Returns the numerical id of the selection anchor item.''' return int(self.tk.call(self._w, 'selection', 'anchor', itemDesc)) or None def selection_clear(self, first=None, last=None): '''FIRST and LAST (if specified) must be the string ALL or a valid item description. If any of the items between FIRST and LAST (inclusive) are selected, they are deselected. The selection state is not changed for items outside this range. If no additional arguments are given, or if one of the arguments is the string ALL, then all items are removed from the selection. A event is generated if any items were removed from the selection.''' self.tk.call(self._w, 'selection', 'clear', first, last) def selection_count(self): '''Returns an integer indicating the number of items in the treectrl that are currently selected.''' return int(self.tk.call(self._w, 'selection', 'count')) def selection_get(self, first=None, last=None): '''Returns a tuple containing the item ids of all of the items in the treectrl that are currently selected. If there are no items selected in the treectrl, returns None. The optional arguments FIRST and LAST are treated as indices into the sorted list of selected items. For example: self.selection_get(0) : the first selected item self.selection_get("end") : the last selected item self.selection_get(1, "end-1") : every selected item except the first and last''' # at least with treectrl-2.2.9 # self.tk.call(self._w, 'selection', 'get', 0, "end") returns an # integer instead of a tuple when a single item is selected, # so we cannot simply use: # self._getints(self.tk.call(self._w, 'selection', 'get', first, last)) # or we get a TypeError in that case sel = self.tk.call(self._w, 'selection', 'get', first, last) if isinstance(sel, int): return (sel, ) else: return self._getints(sel) def selection_includes(self, itemDesc): '''Returns True if the item described by itemDesc is currently selected, False if it isn't.''' return self._getboolean(self.tk.call( self._w, 'selection', 'includes', itemDesc)) def selection_modify(self, select=(), deselect=()): '''Both arguments SELECT and DESELECT must be the string ALL or a possibly-empty list of item descriptions. Any unselected items in SELECT are added to the selection, and any selected items in DESELECT are removed from the selection (except for those items which are also in SELECT). A event is generated if any items were selected or deselected.''' self.tk.call(self._w, 'selection', 'modify', select or (), deselect or ()) def style_cget(self, style, option): '''This command returns the current value of the option named OPTION associated with the style given by STYLE. OPTION may have any of the values accepted by the style_configure() widget command.''' return self.tk.call(self._w, 'style', 'cget', style, option) def style_configure(self, style, cnf=None, **kw): '''This command is similar to the configure() widget command except that it modifies options associated with the style given by STYLE instead of modifying options for the overall treectrl widget. The options of a style have effect on all elements managed by the style. The following options are supported: -buttony offset Specifies the distance from the top of the item that the expand/collapse button should be drawn. If offset is an empty string (the default) then the button is centered vertically in the item. The value may have any of the forms acceptable to Tk_GetPixels. This option only has effect when the style is set in an item in the tree column. -orient varName This option specifies which orientation should be used when laying out the elements associated with this style. Must be either horizontal (the default) or vertical or an abbreviation of one of these.''' return self._configure(('style', 'configure', style), cnf, kw) style_config = style_configure def style_create(self, name=None, *args, **kw): '''Create a new style in pathName with name STYLE. After STYLE there may be any number of option-value pairs, each of which sets one of the configuration options for the style. These same option-value pairs may be used in style_configure() widget commands to change the style's configuration. Returns the name of the new style.''' if name is None: Treectrl._last_style += 1 name = 'pystyle' + str(Treectrl._last_style) return self._create('style', (name, args), kw) create_style = style_create def style_delete(self, style): '''Deletes each of the named STYLEs. If a style is deleted while it is still used to display one or more items, it is also removed from the style list of these items.''' self.tk.call(self._w, 'style', 'delete', style) delete_style = style_delete def style_elements(self, style, *elementList): '''Specifies the elements which should be layed out by this style. Each element of ELEMENTLIST must be the name of an element created by the widget command element_create(). Duplicate names in ELEMENTLIST are ignored. An element which was specified in a former call of this command for STYLE but is not included in ELEMENTLIST, will be deleted from the elements layed out by STYLE. If the ELEMENTLIST argument is not specified, a list is returned containing the currently defined elements of STYLE.''' if elementList: return self.tk.call(self._w, 'style', 'elements', style, elementList) or None return self.tk.splitlist(self.tk.call( self._w, 'style', 'elements', style)) def style_layout(self, style, element, cnf=None, **kw): '''This command is similar to the configure() widget command except that it modifies options used by STYLE for laying out ELEMENT instead of modifying options for the overall treectrl widget. The options of a layout have effect on exactly the one element ELEMENT managed by STYLE. The following options are supported: -detach boolean Specifies whether the element should be positioned by itself, i.e. independent from the other elements. -expand flags This option allows the external padding around the element to increase when a style has more screen space than it needs. Flags is a string that contains zero or more of the characters n, s, w or e. Each letter refers to the padding on the top, bottom, left, or right that should be allowed to increase. This option is typically used to justify an element. -iexpand flags This option allows the internal padding of the element and the display area of the element to increase when a style has more screen space than it needs. Flags is a string that contains zero or more of the characters x, y, n, s, w or e. For n, s, w and e, each letter refers to the padding on the top, bottom, left, or right that should be allowed to increase. For x and y, each letter refers to the horizontal and vertical screen space the element can display itself in (i.e., the space between the padding). Note that if the -union option is specified for this element, then the x and y flags have no effect, since the size of an element with -union layout is determined by the elements it surrounds. -indent boolean Specifies whether the element should be positioned to the right of the button/line area in the tree column. This option is ignored unless the -detach option is true. -ipadx amount -ipady amount Amount specifies how much internal padding to leave on the left and right (for -ipadx) or top and bottom (for -ipady) side of the element. Amount may be a list of two values to specify padding for the two sides separately, it defaults to 0. -minheight pixels -height pixels -maxheight pixels Specifies the minimum, fixed, and maximum height of the element. -minwidth pixels -width pixels -maxwidth pixels Specifies the minimum, fixed, and maximum width of the element. -padx amount -pady amount Amount specifies how much external padding to leave on the left and right (for -padx) or top and bottom (for -pady) side of the element. Amount may be a list of two values to specify padding for the two sides separately, it defaults to 0. -squeeze flags This option allows the display area of an element to decrease when a style has less space than it needs. Flags is a string that contains zero or more of the characters x or y. x allows display area to decrease horizontally, y allows display area to decrease vertically. This option is typically used for text elements and will cause the text element to display an ellipsis (...) and/or wrap lines. -sticky flags This option controls how the actual display information (image, text, etc) of an element is positioned (or stretched) within its display area. Flags is a string that contains zero or more of the characters n, s, w or e. Each letter refers to the top, bottom, left or right side of the display area that the display information should "stick" to. -union elementList Specifies a list of other elements which this element will surround. The size of an element with -union layout is determined by the size and position of the elements in elementList. The -ipadx and -ipady options in this case refer to the distance of the edges of the display area of this element from those elements it surrounds. This option is typically used to display a selection rectangle around a piece of text. Since treectrl-2.3 it is ok to include an element with -union layout in another element's -union list. Previously, nesting -union elements had undefined behavior.''' return self._configure(('style', 'layout', style, element), cnf, kw) def style_names(self): '''Returns a list containing the names of all existing styles.''' return self.tk.splitlist(self.tk.call(self._w, 'style', 'names')) def theme_platform(self): '''Returns the API used to draw themed parts of the treectrl. On Mac OS X the result is always aqua. On MS Windows the result is visualstyles if the uxtheme.dll was loaded and visual themes are in use, otherwise X11 is returned to indicate the Tk Xlib calls are drawing the themed parts. On Unix systems the result is gtk if the Gtk+ version of treectrl was built, otherwise X11 is returned.''' return self.tk.call(self._w, 'theme', 'platform') def theme_setwindowtheme(self, appname): '''The command is available on MS Windows only. If appname is "Explorer" then the item buttons look like those in the Explorer file browser (disclosure triangles under Windows Vista/7). If appname is an empty string then the buttons revert to their default appearance according to the system's current visual style.''' return self.tk.call(self._w, 'theme', 'setwindowtheme', appname) def xview(self, *what): """Query and change horizontal position of the view.""" if not what: return self._getdoubles(self.tk.call(self._w, 'xview')) self.tk.call((self._w, 'xview') + what) def xview_moveto(self, fraction): """Adjust the view in the window so that FRACTION of the total width of the entry is off-screen to the left.""" self.tk.call(self._w, 'xview', 'moveto', fraction) def xview_scroll(self, number, what): """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'xview', 'scroll', number, what) def yview(self, *what): """Query and change vertical position of the view.""" if not what: return self._getdoubles(self.tk.call(self._w, 'yview')) self.tk.call((self._w, 'yview') + what) def yview_moveto(self, fraction): """Adjust the view in the window so that FRACTION of the total width of the entry is off-screen to the top.""" self.tk.call(self._w, 'yview', 'moveto', fraction) def yview_scroll(self, number, what): """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'yview', 'scroll', number, what) ######################################################################### # library commands from FileListBindings.tcl # ######################################################################### def filelist_emulate_win7(self, win7=None): '''Query or change the flag indicating that Windows 7 behavior should be used. If called without arguments returns True or False depending on the current state. If called with a boolean value as argument changes the behavior according to the given value.''' if win7 is None: return self._getboolean( self.tk.call('TreeCtrl::FileListEmulateWin7', self._w)) self.tk.call('TreeCtrl::FileListEmulateWin7', self._w, win7) def is_sensitive(self, x, y): '''Returns True if the given window coordinates are over an element that should respond to mouse clicks. The list of elements that respond to mouse clicks is set by calling set_sensitive().''' return self._getboolean( self.tk.call('TreeCtrl::IsSensitive', self._w, x, y)) def is_sensitive_marquee(self, x, y): '''Returns True if the given window coordinates are over an element that should respond to the marquee. The list of elements that respond to the marquee is set by calling set_sensitive_marquee(), or if that list is empty then the same list passed to set_sensitive().''' return self._getboolean( self.tk.call('TreeCtrl::IsSensitiveMarquee', self._w, x, y)) def set_dragimage(self, *args): '''This command may be used to define elements that should be drawn as drag images during drag operations. ARGS must be one or more tuples of the form (COLUMN, STYLE, ELEMENT) that define the elements that are supposed to be drawn. For this to take effect, at least calls to self.bindtags(('TreeCtrlFileList',)) and self.set_sensitive(*args) must be made before.''' self.tk.call('TreeCtrl::SetDragImage', self._w, (args)) def set_editable(self, *args): '''This command may be used to define text cells that should be user-editable. ARGS must be one or more tuples of the form (COLUMN, STYLE, ELEMENT) that define the text elements that are supposed to be editable. For this to take effect, at least calls to self.bindtags(('TreeCtrlFileList',)) and self.set_sensitive(*args) must be made before.''' self.tk.call('TreeCtrl::SetEditable', self._w, (args)) def set_selected_items_sensitive(self, sensitive): '''Specifies whether or not entire items are sensitive to mouse clicks when they are already selected. SENSITIVE must be a boolean value.''' # does not return anything and does not seem to have any # effect either self.tk.call( 'TreeCtrl::SetSelectedItemsSensitive', self._w, sensitive) def set_sensitive(self, *args): '''Defines elements that are supposed to respond to mouse events after file list bindings have been applied to the widget with bindtags(('TreeCtrlFileList',)). ARGS must be one or more tuples of the form (COLUMN, STYLE, ELEMENT) that define the desired elements.''' self.tk.call('TreeCtrl::SetSensitive', self._w, (args)) def set_sensitive_marquee(self, *args): '''Just like set_sensitive() but indicates which elements respond to the selection rectangle. Typically this is the same as the elements passed to set_sensitive() with the addition of the selection rectangle elements.''' self.tk.call('TreeCtrl::SetSensitiveMarquee', self._w, (args)) python-tktreectrl-2.0.1/TkTreectrl/ScrolledTreectrl.py0000644000175000017500000003743612052756574023037 0ustar moellermoeller# -*- coding: utf-8 -*- '''Treectrl and MultiListbox widgets with scrollbars.''' try: import tkinter except ImportError: import Tkinter as tkinter from TkTreectrl.Treectrl import Treectrl from TkTreectrl.MultiListbox import MultiListbox # see if we have ttk available try: # typically the Python2 variant: import ttk _have_ttk = True except ImportError: try: from tkinter import ttk _have_ttk = True except ImportError: _have_ttk = False # use themed widgets, if available if _have_ttk: _Frame = ttk.Frame _Scrollbar = ttk.Scrollbar else: _Frame = tkinter.Frame _Scrollbar = tkinter.Scrollbar class _UniScrollbar(_Scrollbar): '''Internal class. A "universal" Scrollbar widget that uses a ttk.Scrollbar if ttk is available, else a tkinter.Scrollbar. If a ttk.Scrollbar is used, ttk-incompatible configuration options are silently ignored, to keep backwards compatibility intact.''' def __init__(self, master=None, **kw): if _Scrollbar == ttk.Scrollbar: # some opts that aren't legal in ttk, ignore them silently: for opt in ('activebackground', 'activerelief', 'background', 'bg', 'bd', 'borderwidth', 'elementborderwidth', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'jump', 'relief', 'repeatdelay', 'repeatinterval', 'troughcolor', 'width'): if opt in kw: del(kw[opt]) _Scrollbar.__init__(self, master, **kw) def cget(self, key): if _Scrollbar == ttk.Scrollbar: if key in ('activebackground', 'activerelief', 'background', 'bg', 'bd', 'borderwidth', 'elementborderwidth', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'jump', 'relief', 'repeatdelay', 'repeatinterval', 'troughcolor', 'width'): return None return _Scrollbar.cget(self, key) __getitem__ = cget def configure(self, cnf=None, **kw): if _Scrollbar == ttk.Scrollbar: for opt in ('activebackground', 'activerelief', 'background', 'bg', 'bd', 'borderwidth', 'elementborderwidth', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'jump', 'relief', 'repeatdelay', 'repeatinterval', 'troughcolor', 'width'): if not cnf is None and opt in cnf: del(cnf[opt]) if opt in kw: del(kw[opt]) return _Scrollbar.configure(self, cnf, **kw) config = configure ############################################################################### ############################################################################### class ScrolledWidget(_Frame): '''Base class for Tkinter widgets with scrollbars. The widget is a standard Tkinter.Frame or a ttk.Frame if ttk is available, with an additional configuration option SCROLLMODE which may be one of "x", "y", "both" or "auto". If SCROLLMODE is one of "x", "y" or "both", one or two static scrollbars will be drawn. If SCROLLMODE is set to "auto", two automatic scrollbars that appear only if needed will be drawn. In order to ensure backwards compatibility, ttk-incompatible configuration options passed to the widget or to the scrollbars will be silently ignored if ttk widgets are used. The Scrollbar widgets can be accessed with the hbar and vbar class attributes. Derived classes must override the _setScrolledWidget() method, which must return the widget that will be scrolled and should add a class attribute that allows to access this widget, so the _setScrolledWidget() method for a ScrolledListbox widget might look like: def _setScrolledWidget(self): self.listbox = Tkinter.Listbox(self) return self.listbox Note that although it should be possible to create scrolled widget classes for virtually any Listbox or Canvas alike Tkinter widget you can *not* safely use this class to add automatic scrollbars to a Text or Text alike widget. This is because in a scrolled Text widget the value of the horizontal scrollbar depends only on the visible part of the Text, not on it's whole contents. Thus it may happen that it is the last visible line of text that causes the automatic scrollbar to be mapped which then hides this last line so it will be unmapped again, but then it is requested again and gets mapped and so on forever. There are strategies to avoid this, but usually at the cost that there will be situations where the horizontal scrollbar remains mapped although it is actually not needed. In order to acomplish this with the ScrolledWidget class, at least the _scrollXNow() and _scrollBothNow() methods must be overridden with appropriate handlers. ''' def __init__(self, master=None, **kw): if 'scrollmode' in kw: scrollmode = kw['scrollmode'] del(kw['scrollmode']) else: scrollmode = 'auto' if not 'width' in kw: kw['width'] = 400 if not 'height' in kw: kw['height'] = 300 if _Frame == ttk.Frame: # "bd" is not valid in ttk if 'bd' in kw: kw['borderwidth'] = kw['bd'] del(kw['bd']) # some more opts that aren't legal in ttk, ignore them silently: for opt in ('background', 'bg', 'colormap', 'container', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'visual'): if opt in kw: del(kw[opt]) _Frame.__init__(self, master, **kw) # call grid_propagate(0) so the widget will not change its size # when the scrollbars are mapped or unmapped; that is why we need # to specify width and height in any case self.grid_propagate(0) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self._scrollmode = scrollmode self._scrolledWidget = self._setScrolledWidget() self._scrolledWidget.grid(row=0, column=0, sticky='news') self.vbar = _UniScrollbar(self, orient='vertical', command=self._scrolledWidget.yview) self.vbar.grid(row=0, column=1, sticky='ns') self.hbar = _UniScrollbar(self, orient='horizontal', command=self._scrolledWidget.xview) self.hbar.grid(row=1, column=0, sticky='ew') # Initialise instance variables. self._hbarOn = 1 self._vbarOn = 1 self._scrollTimer = None self._scrollRecurse = 0 self._hbarNeeded = 0 self._vbarNeeded = 0 self._scrollMode(scrollmode) def _setScrolledWidget(self): '''This method must be overridden in derived classes. It must return the widget that should be scrolled and should add a reference to the ScrolledWidget object, so it can be accessed by the user. For example, to create a scrolled Listbox, do: self.listbox = Tkinter.Listbox(self) return self.listbox''' pass def configure(self, cnf=None, **kw): # hack: add "scrollmode" to user configurable options if not cnf is None and 'scrollmode' in cnf: self._scrollMode(cnf['scrollmode']) del(cnf['scrollmode']) if 'scrollmode' in kw: self._scrollMode(kw['scrollmode']) del(kw['scrollmode']) if _Frame == ttk.Frame: # "bd" is not valid in ttk if not cnf is None and 'bd' in cnf: cnf['borderwidth'] = cnf['bd'] del(cnf['bd']) if 'bd' in kw: kw['borderwidth'] = kw['bd'] del(kw['bd']) # some more opts that aren't legal in ttk, # ignore them silently: for opt in ('bg', 'background', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady'): if not cnf is None and opt in cnf: del(cnf[opt]) if opt in kw: del(kw[opt]) return _Frame.configure(self, cnf, **kw) config = configure def cget(self, key): if key == 'scrollmode': return self._scrollmode if _Frame == ttk.Frame: if key == 'bd': key = 'borderwidth' elif key in ('bg', 'background', 'colormap', 'container', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'visual'): return None return _Frame.cget(self, key) __getitem__ = cget def keys(self): keys = _Frame.keys(self) + ['scrollmode'] keys.sort() return keys # methods to control the scrollbars; # these are mainly stolen from Pmw.ScrolledListbox def _scrollMode(self, mode): if mode == 'both': if not self._hbarOn: self._toggleHbar() if not self._vbarOn: self._toggleVbar() elif mode == 'auto': if self._hbarNeeded != self._hbarOn: self._toggleHbar() if self._vbarNeeded != self._vbarOn: self._toggleVbar() elif mode == 'x': if not self._hbarOn: self._toggleHbar() if self._vbarOn: self._toggleVbar() elif mode == 'y': if not self._vbarOn: self._toggleVbar() if self._hbarOn: self._toggleHbar() else: raise ValueError('bad value for option scrollmode: ' +\ '"%s"; should be "x", "y", "both" or "auto".' % mode ) self._scrollmode = mode self._configureScrollCommands() def _configureScrollCommands(self): # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._scrolledWidget.cget('xscrollcommand')) if tclCommandName != '': self._scrolledWidget.deletecommand(tclCommandName) tclCommandName = str(self._scrolledWidget.cget('yscrollcommand')) if tclCommandName != '': self._scrolledWidget.deletecommand(tclCommandName) # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. if self._scrollmode == 'auto': self._scrolledWidget.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater) else: self._scrolledWidget.configure(xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow) def _scrollXNow(self, first, last): first, last = str(first), str(last) self.hbar.set(first, last) self._hbarNeeded = ((first, last) not in (('0', '1'), ('0.0', '1.0'))) if self._scrollmode == 'auto': if self._hbarNeeded != self._hbarOn: self._toggleHbar() def _scrollYNow(self, first, last): first, last = str(first), str(last) self.vbar.set(first, last) self._vbarNeeded = ((first, last) not in (('0', '1'), ('0.0', '1.0'))) if self._scrollmode == 'auto': if self._vbarNeeded != self._vbarOn: self._toggleVbar() def _scrollBothLater(self, first, last): # Called by the listbox to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self._scrollTimer is None: self._scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self._scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview, yview = self._scrolledWidget.xview(),\ self._scrolledWidget.yview() self.hbar.set(*xview) self.vbar.set(*yview) self._hbarNeeded = (xview != (0.0, 1.0)) self._vbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self._scrollmode == 'auto' and self._hbarNeeded != self._hbarOn and self._vbarNeeded != self._vbarOn and self._vbarOn != self._hbarOn): if self._hbarOn: self._toggleHbar() else: self._toggleVbar() return if self._scrollmode == 'auto': if self._hbarNeeded != self._hbarOn: self._toggleHbar() if self._vbarNeeded != self._vbarOn: self._toggleVbar() def _toggleHbar(self): self._hbarOn = not self._hbarOn if self._hbarOn: self.hbar.grid(row=1, column=0, sticky='ew') else: self.hbar.grid_forget() def _toggleVbar(self): self._vbarOn = not self._vbarOn if self._vbarOn: self.vbar.grid(row=0, column=1, sticky='ns') else: self.vbar.grid_forget() def destroy(self): if self._scrollTimer is not None: self.after_cancel(self._scrollTimer) self._scrollTimer = None _Frame.destroy(self) ############################################################################### ############################################################################### class ScrolledTreectrl(ScrolledWidget): '''Treectrl widget with one or two static or automatic scrollbars. Subwidgets are: treectrl - TkTreectrl.Treectrl widget hbar - horizontal Tkinter.Scrollbar or ttk.Scrollbar vbar - vertical Tkinter.Scrollbar or ttk.Scrollbar The widget itself is a Tkinter.Frame or ttk.Frame with one additional configuration option: scrollmode - may be one of "x", "y", "both" or "auto".''' def __init__(self, *args, **kw): ScrolledWidget.__init__(self, *args, **kw) def _setScrolledWidget(self): self.treectrl = Treectrl(self) return self.treectrl ############################################################################### ############################################################################### class ScrolledMultiListbox(ScrolledWidget): '''MultiListbox widget with one or two static or automatic scrollbars. Subwidgets are: listbox - TkTreectrl.MultiListbox widget hbar - horizontal Tkinter.Scrollbar or ttk.Scrollbar vbar - vertical Tkinter.Scrollbar or ttk.Scrollbar The widget itself is a Tkinter.Frame or ttk.Frame with one additional configuration option: scrollmode - may be one of "x", "y", "both" or "auto".''' def __init__(self, *args, **kw): ScrolledWidget.__init__(self, *args, **kw) def _setScrolledWidget(self): self.listbox = MultiListbox(self) return self.listbox python-tktreectrl-2.0.1/TkTreectrl/__init__.py0000644000175000017500000000333312052762310021270 0ustar moellermoeller# -*- coding: utf-8 -*- #v.0.7 #added LEFT,RIGHT,HEADER and CONTENT, fixed typo with LEFTMOST #v.0.8: added __version__ '''Main module of the TkTreectrl package. Once the TkTreectrl package is installed, it is safe to do : from TkTreectrl import * This will add a number of constants and the following widget classes to the current namespace: Treectrl, MultiListbox, ScrolledTreectrl, ScrolledMultiListbox, ScrolledWidget ''' __version__ = '2.0' ABOVE = 'above' ACTIVE = 'active' ALL = 'all' ASCII = 'ascii' AREA = 'area' BELOW = 'below' BITMAP = 'bitmap' BORDER = 'border' CANVAS = 'canvas' COLUMN = 'column' CONTENT = 'content' DECREASING = 'decreasing' DICTIONARY = 'dictionary' DOUBLE = 'double' DOT = 'dot' DYNAMIC = 'dynamic' ENABLED = 'enabled' FIRST = 'first' FIRSTCHILD = 'firstchild' FOCUS = 'focus' HEADER = 'header' IMAGE = 'image' INCREASING = 'increasing' INTEGER = 'integer' ITEM = 'item' LAST = 'last' LASTCHILD = 'lastchild' LEFT = 'left' LEFTMOST = 'leftmost' LONG = 'long' NEXT = 'next' NEXTSIBLING = 'nextsibling' NORMAL = 'normal' OPEN = 'open' PARENT = 'parent' PRESSED = 'pressed' PREV = 'prev' PREVSIBLING = 'prevsibling' REAL = 'real' RECT = 'rect' RIGHT = 'right' RIGHTMOST = 'rightmost' ROOT = 'root' SELECT = 'select' SELECTED = 'selected' STATIC = 'static' STRING = 'string' TAIL = 'tail' TEXT = 'text' TIME = 'time' TREE = 'tree' WINDOW = 'window' from TkTreectrl.Treectrl import Treectrl from TkTreectrl.MultiListbox import MultiListbox from TkTreectrl.ScrolledTreectrl import ScrolledTreectrl from TkTreectrl.ScrolledTreectrl import ScrolledMultiListbox # put the ScrolledWidget class in the global namespace so people can easily # create custom subclasses from TkTreectrl.ScrolledTreectrl import ScrolledWidget python-tktreectrl-2.0.1/TkTreectrl/MultiListbox.py0000644000175000017500000005057512141670242022203 0ustar moellermoeller# -*- coding: utf-8 -*- '''A flexible multi column listbox widget for Tkinter.''' from TkTreectrl.Treectrl import Treectrl class MultiListbox(Treectrl): '''A flexible multi column listbox widget for Tkinter. Based on the Treectrl widget, it offers the following additional configuration options: columns - a sequence of strings that defines the number of columns of the widget. The strings will be used in the columnheader lines (default: (' ',)). command - an optional command that will be executed when the user double-clicks into the listbox or presses the Return key. The listbox index of the item that was clicked on resp. of the currently active item is passed as argument to the callback; if there is no item at the event coordinates resp. no active item exists, this index will be -1 (default: None). expandcolumns - a sequence of integers defining the columns that should expand horizontally beyond the requested size when the widget is resized (note that the rightmost column will always expand) (default: ()). selectcmd - an optional callback that will be executed when the selection of the listbox changes. A tuple containing the indices of the currently selected items as returned by curselection() will be passed to the callback (default: None). selectbackground - the background color to use for the selection rectangle (default: #00008B). selectforeground - the foreground color to use for selected text (default: white). By default, the widget uses one pre-defined style for all columns; the widget's style() method allows to access and configure the default style, as well as applying new user-defined styles per column. The default style defines two elements, "text" and "select" (which describes attributes of the selection rectangle); these may be accessed and configured with the element() method. Conversion between listbox indices and treectrl item descriptors can be done with the item() and index() widget methods. Besides this, most common operations can be done with methods identical or very similar to those of a Tkinter.Listbox, with the exception of the selection_xxx() methods, where the treectrl methods are kept intact; for Tkinter.Listbox alike methods, use select_xxx(). ''' def __init__(self, master=None, columns=(' ',), selectcmd=None, command=None, expandcolumns=(), showroot=False, selectforeground='white', selectbackground='#00008B', **kw): Treectrl.__init__(self, master, showroot=showroot, **kw) self._multilistbox_opts = {'selectcmd' : selectcmd, 'command' : command, 'expandcolumns' : expandcolumns, 'columns' : columns, 'selectforeground' : selectforeground, 'selectbackground' : selectbackground} self._el_text = self.element_create(type='text', fill=(self._multilistbox_opts['selectforeground'], 'selected'), lines=1) self._el_select = self.element_create(type='rect', showfocus=1, fill=(self._multilistbox_opts['selectbackground'], 'selected')) self._defaultstyle = self.style_create() self.style_elements(self._defaultstyle, self._el_select, self._el_text) self.style_layout(self._defaultstyle, self._el_text, padx=4, iexpand='e', expand='ns') self.style_layout(self._defaultstyle, self._el_select, union=(self._el_text,), ipady=1, iexpand='nsew') self._columns = [] self._styles = [] self.configure(columns=columns, expandcolumns=expandcolumns, selectcmd=selectcmd, command=command) self.notify_bind('', self._call_selectcmd) self.bind('', self._call_command) self.bind('', self._call_command) ########################################################################### ## hackish implementation of configure() and friends ## for special widget options ########################################################################### def _configure_multilistbox(self, option, value): if option in ('selectcmd', 'command'): if not (value is None or hasattr(value, '__call__')): raise ValueError('bad value for "%s" option: ' % option +\ 'must be callable or None.') elif option =='selectforeground': self.element_configure(self._el_text, fill=(value, 'selected')) elif option == 'selectbackground': self.element_configure(self._el_select, fill=(value, 'selected')) elif option == 'expandcolumns': if not (isinstance(value, tuple) or isinstance(value, list)): raise ValueError('bad value for "expandcolumns" option: ' +\ 'must be tuple or list.') value = tuple(value) # the last column should always expand expandcolumns = [x for x in value] + [len(self._columns) - 1] for column in self._columns: if self._columns.index(column) in expandcolumns: self.column_config(column, expand=1) else: self.column_config(column, expand=0) elif option == 'columns': # if the number of strings in value is identical with the number # of already existing columns, simply update the columnheader # strings if there are more items in value, add the missing columns # else remove the excess columns if not (isinstance(value, tuple) or isinstance(value, list)): raise ValueError('bad value for "columns" option: ' +\ 'must be tuple or list.') if not value: raise ValueError('bad value for "columns" option: ' +\ 'at least one column must be specified.') value = tuple(value) index = 0 while index < len(value) and index < len(self._columns): # change title of existing columns self.column_config(self.column(index), text=value[index]) index += 1 if len(value) != len(self._columns): while self._columns[index:]: # remove the no longer wanted columns self.column_delete(self.column(index)) del self._columns[index] del self._styles[index] while value[index:]: # create newly requested columns newcol = self.column_create(text=value[index], minwidth=35) self._styles.append(self._defaultstyle) self._columns.append(newcol) index += 1 # the number of columns has changed, so we need to update the # resize and expand options for each column and update the # widget's defaultstyle option self.configure(defaultstyle=tuple(self._styles)) for col in self._columns[:-1]: self.column_configure(col, resize=1) self.column_configure(self.column('end'), resize=0) self._configure_multilistbox('expandcolumns', self._multilistbox_opts['expandcolumns']) # apply the new value to the option dict self._multilistbox_opts[option] = value def configure(self, cnf=None, **kw): for opt in self._multilistbox_opts.keys(): if not cnf is None and opt in cnf: self._configure_multilistbox(opt, cnf[opt]) del cnf[opt] if opt in kw: self._configure_multilistbox(opt, kw[opt]) del kw[opt] return Treectrl.configure(self, cnf, **kw) config = configure def cget(self, key): if key in self._multilistbox_opts.keys(): return self._multilistbox_opts[key] return Treectrl.cget(self, key) __getitem__ = cget def keys(self): keys = Treectrl.keys(self) + self._multilistbox_opts.keys() keys.sort() return keys ######################################################################## # miscellaneous helper methods # ######################################################################## def _call_selectcmd(self, event): if self._multilistbox_opts['selectcmd']: sel = self.curselection() self._multilistbox_opts['selectcmd'](sel) return 'break' def _call_command(self, event): if self._multilistbox_opts['command']: if event.keysym == 'Return': index = self.index('active') else: index = self._event_index(event) self._multilistbox_opts['command'](index) return 'break' def _event_index(self, event): '''Return the listbox index where mouse event EVENT occured, or -1 if it occured in an empty listbox or below the last item.''' x, y = event.x, event.y xy = '@%d,%d' % (x, y) return self.index(xy) def _index2item(self, index): try: # index may be e.g. "2" or 2 or "end" index = int(index) except ValueError: pass if isinstance(index, int) and index < 0: return None if index == 'end': index = self.size() - 1 items = self.item_children('root') if not items: return None try: item = items[index] except IndexError: item = None return item def _item2index(self, item): # some treectrl methods return item descriptors as strings # so try to convert item into an integer first try: item = int(item) except ValueError: pass items = list(self.item_children('root')) index = -1 if item in items: index = items.index(item) return index def _get(self, index): item = self._index2item(index) res = [] i = 0 for column in self._columns: t = self.itemelement_cget(item, column, self._el_text, 'text') res.append(t) return tuple(res) ########################################################################### # PUBLIC METHODS # ########################################################################### def column(self, index): '''Return the column identifier for the column at INDEX.''' if index == 'end': index = len(self._columns) - 1 return self._columns[index] def element(self, element): '''Return the treectrl element corresponding to ELEMENT. ELEMENT may be "text" or "select".''' if element == 'text': return self._el_text elif element == 'select': return self._el_select def item(self, index): '''Return the treectrl item descriptor for the item at INDEX.''' return self._index2item(index) def numcolumns(self): '''Return the number of listbox columns.''' return len(self._columns) def sort(self, column=None, element=None, first=None, last=None, mode=None, command=None, notreally=False): '''Like item_sort(), except that the item descriptor defaults to ROOT (which is most likely wanted) and that the FIRST and LAST options require listbox indices instead of treectrl item descriptors.''' if not first is None: first = self._index2item(first) if not last is None: last = self._index2item(last) self.item_sort('root', column, element, first, last, mode, command, notreally) def style(self, index, newstyle=None): '''If NEWSTYLE is specified, set the style for the column at INDEX to NEWSTYLE. Return the style identifier for the column at INDEX.''' if not newstyle is None: self._styles[index] = newstyle self.configure(defaultstyle=tuple(self._styles)) return self._styles[index] ########################################################################### # Standard Listbox methods # ########################################################################### def activate(self, index): '''Like Tkinter.Listbox.activate(). Note that this overrides the activate() method inherited from Treectrl.''' item = self._index2item(index) if not item is None: Treectrl.activate(self, item) def bbox(self, index, column=None, element=None): '''Like item_bbox(), except that it requires a listbox index instead of a treectrl item descriptor as argument. Note that this overrides the bbox() method inherited from Treectrl.''' item = self._index2item(index) if not item is None: return self.item_bbox(item, column, element) def curselection(self): '''Like Tkinter.Listbox.curselection().''' selected = self.selection_get() if not selected: return () selected = list(selected) if 0 in selected: # happens if showroot == 1 and the root item is selected selected.remove(0) allitems = list(self.item_children('root')) sel = [] for s in selected: sel.append(allitems.index(s)) sel.sort() return tuple(sel) def delete(self, first, last=None): '''Like Tkinter.Listbox.delete() except that an additional index descriptor ALL may be used, so that delete(ALL) is equivalent with delete(0, END).''' if first == 'all': self.item_delete('all') elif (first == 0) and (last == 'end'): self.item_delete('all') elif last is None: self.item_delete(self._index2item(first)) else: if last == 'end': last = self.size() - 1 self.item_delete(self._index2item(first), self._index2item(last)) def get(self, first, last=None): '''Like Tkinter.Listbox.get(), except that each element of the returned tuple is a tuple instead of a string; each of these tuples contains the text strings per column of a listbox item.''' if self.size() == 0: return () if last is None: return (self._get(first),) if last == 'end': last = self.size() - 1 res = [] while first <= last: res.append(self._get(first)) first += 1 return tuple(res) def index(self, which=None, item=None): ''' Like Tkinter.Listbox.index(), except that if ITEM is specified, the listbox index for the treectrl item descriptor ITEM is returned. ''' if not item is None: return self._item2index(item) items = self.item_children('root') if items: if which == 'active': for item in items: if self.itemstate_get(item, 'active'): return self._item2index(item) elif which == 'end': return self.size() elif isinstance(which, int): return which elif which.startswith('@'): which = which[1:] x, y = which.split(',') x, y = int(x.strip()), int(y.strip()) info = self.identify(x, y) if info and info[0] == 'item': item = info[1] return self._item2index(int(item)) return -1 def insert(self, index, *args): '''Similar to Tkinter.Listbox.insert(), except that instead of one string a number of strings equal to the number of columns must be given as arguments. It is an error to specify more or fewer arguments than the number of columns. Returns the ID of the newly created item, as returned by item_create().''' olditems = self.item_children('root') if not olditems: newitem = self.item_create(parent='root')[0] elif (index == 'end') or (index > self.size() - 1): newitem = self.item_create(prevsibling=olditems[-1])[0] else: newitem = self.item_create(nextsibling=olditems[index])[0] i = 0 for column in self._columns: newtext = args[i] self.itemelement_config(newitem, column, self._el_text, text=newtext) i += 1 return newitem def nearest(self, y): '''Like Tkinter.Listbox.nearest().''' size = self.size() # if the listbox is empty this will always return -1 if size == 0: return -1 # if there is only one item, always return 0 elif size == 1: return 0 # listbox contains two or more items, find if y hits one of them # exactly; if the x coord for identify() is in the border decoration, # identify returns (), so we cannot use x=0 here, but have to move a # few pixels further; sometimes cget() returns TclObjects instead of # strings, so do str() here first: x = int(str(self['borderwidth'])) +\ int(str(self['highlightthickness'])) + 1 info = self.identify(x, y) if info and info[0] == 'item': return self._item2index(int(info[1])) # y must be above the first or below the last item x0, y0, x1, y1 = self.bbox(0) if y <= y0: return 0 return size - 1 def see(self, index, column=None, center=None): '''Like Tkinter.Listbox.see(). Note that this overrides the see() method inherited from Treectrl.''' item = self._index2item(index) if not item is None: Treectrl.see(self, item, column, center) def select_anchor(self, index=None): '''Like Tkinter.Listbox.select_anchor(), except that it if no INDEX is specified the current selection anchor will be returned.''' if index is None: anchor = self.selection_anchor() else: item = self._index2item(index) anchor = self.selection_anchor(item) if not anchor is None: return self._item2index(anchor) def select_clear(self, first=None, last=None): '''Like Tkinter.Listbox.select_clear(), except that if no arguments are specified, all items will be deleted, so that select_clear() is equivalent with select_clear(0, END).''' if first == 'all': self.selection_clear('all') if not first is None: first = self._index2item(first) if not last is None: last = self._index2item(last) self.selection_clear(first, last) def select_includes(self, index): '''Like Tkinter.Listbox.select_includes().''' item = self._index2item(index) if not item is None: return self.selection_includes(item) return 0 def select_set(self, first, last=None): '''Like Tkinter.Listbox.select_set().''' if first == 'all': self.selection_modify(select='all') elif (first == 0) and (last == 'end'): self.selection_modify(select='all') elif last is None: self.selection_modify(select=(self._index2item(first),)) else: if last == 'end': last = self.size() - 1 newsel = self.item_children('root')[first:last+1] self.selection_modify(select=newsel) def size(self): '''Like Tkinter.Listbox.size().''' return len(self.item_children('root'))