nltk.draw.util module¶
Tools for graphically displaying and interacting with the objects and processing classes defined by the Toolkit. These tools are primarily intended to help students visualize the objects that they create.
The graphical tools are typically built using “canvas widgets”, each
of which encapsulates the graphical elements and bindings used to
display a complex object on a Tkinter Canvas. For example, NLTK
defines canvas widgets for displaying trees and directed graphs, as
well as a number of simpler widgets. These canvas widgets make it
easier to build new graphical tools and demos. See the class
documentation for CanvasWidget for more information.
The nltk.draw module defines the abstract CanvasWidget base
class, and a number of simple canvas widgets. The remaining canvas
widgets are defined by submodules, such as nltk.draw.tree.
The nltk.draw module also defines CanvasFrame, which
encapsulates a Canvas and its scrollbars. It uses a
ScrollWatcherWidget to ensure that all canvas widgets contained on
its canvas are within the scroll region.
Acknowledgements: Many of the ideas behind the canvas widget system
are derived from CLIG, a Tk-based grapher for linguistic data
structures. For more information, see the CLIG
homepage (http://www.ags.uni-sb.de/~konrad/clig.html).
- class nltk.draw.util.CanvasWidget[source]¶
Bases:
objectA collection of graphical elements and bindings used to display a complex object on a Tkinter
Canvas. A canvas widget is responsible for managing theCanvastags and callback bindings necessary to display and interact with the object. Canvas widgets are often organized into hierarchies, where parent canvas widgets control aspects of their child widgets.Each canvas widget is bound to a single
Canvas. ThisCanvasis specified as the first argument to theCanvasWidget’s constructor.Attributes. Each canvas widget can support a variety of “attributes”, which control how the canvas widget is displayed. Some typical examples attributes are
color,font, andradius. Each attribute has a default value. This default value can be overridden in the constructor, using keyword arguments of the formattribute=value:>>> from nltk.draw.util import TextWidget >>> cn = TextWidget(c, 'test', color='red')
Attribute values can also be changed after a canvas widget has been constructed, using the
__setitem__operator:>>> cn['font'] = 'times'
The current value of an attribute value can be queried using the
__getitem__operator:>>> cn['color'] red
For a list of the attributes supported by a type of canvas widget, see its class documentation.
Interaction. The attribute
'draggable'controls whether the user can drag a canvas widget around the canvas. By default, canvas widgets are not draggable.CanvasWidgetprovides callback support for two types of user interaction: clicking and dragging. The methodbind_clickregisters a callback function that is called whenever the canvas widget is clicked. The methodbind_dragregisters a callback function that is called after the canvas widget is dragged. If the user clicks or drags a canvas widget with no registered callback function, then the interaction event will propagate to its parent. For each canvas widget, only one callback function may be registered for an interaction event. Callback functions can be deregistered with theunbind_clickandunbind_dragmethods.Subclassing.
CanvasWidgetis an abstract class. Subclasses are required to implement the following methods:__init__: Builds a new canvas widget. It must perform the following three tasks (in order):Create any new graphical elements.
Call
_add_child_widgeton each child widget.Call the
CanvasWidgetconstructor.
_tags: Returns a list of the canvas tags for all graphical elements managed by this canvas widget, not including graphical elements managed by its child widgets._manage: Arranges the child widgets of this canvas widget. This is typically only called when the canvas widget is created._update: Update this canvas widget in response to a change in a single child.
For a
CanvasWidgetwith no child widgets, the default definitions for_manageand_updatemay be used.If a subclass defines any attributes, then it should implement
__getitem__and__setitem__. If either of these methods is called with an unknown attribute, then they should propagate the request toCanvasWidget.Most subclasses implement a number of additional methods that modify the
CanvasWidgetin some way. These methods must callparent.update(self)after making any changes to the canvas widget’s graphical elements. The canvas widget must also callparent.update(self)after changing any attribute value that affects the shape or position of the canvas widget’s graphical elements.- Variables
__canvas – This
CanvasWidget’s canvas.__parent – This
CanvasWidget’s hierarchical parent widget.__children – This
CanvasWidget’s hierarchical child widgets.__updating – Is this canvas widget currently performing an update? If it is, then it will ignore any new update requests from child widgets.
__draggable – Is this canvas widget draggable?
__press – The ButtonPress event that we’re currently handling.
__drag_x – Where it’s been moved to (to find dx)
__drag_y – Where it’s been moved to (to find dy)
__callbacks – Registered callbacks. Currently, four keys are used:
1,2,3, and'drag'. The values are callback functions. Each callback function takes a single argument, which is theCanvasWidgetthat triggered the callback.
- __init__(canvas, parent=None, **attribs)[source]¶
Create a new canvas widget. This constructor should only be called by subclass constructors; and it should be called only “after” the subclass has constructed all graphical canvas objects and registered all child widgets.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
parent (CanvasWidget) – This canvas widget’s hierarchical parent.
attribs – The new canvas widget’s attributes.
- bbox()[source]¶
- Returns
A bounding box for this
CanvasWidget. The bounding box is a tuple of four coordinates, (xmin, ymin, xmax, ymax), for a rectangle which encloses all of the canvas widget’s graphical elements. Bounding box coordinates are specified with respect to the coordinate space of theCanvas.- Return type
tuple(int, int, int, int)
- width()[source]¶
- Returns
The width of this canvas widget’s bounding box, in its
Canvas’s coordinate space.- Return type
int
- height()[source]¶
- Returns
The height of this canvas widget’s bounding box, in its
Canvas’s coordinate space.- Return type
int
- parent()[source]¶
- Returns
The hierarchical parent of this canvas widget.
selfis considered a subpart of its parent for purposes of user interaction.- Return type
CanvasWidget or None
- child_widgets()[source]¶
- Returns
A list of the hierarchical children of this canvas widget. These children are considered part of
selffor purposes of user interaction.- Return type
list of CanvasWidget
- canvas()[source]¶
- Returns
The canvas that this canvas widget is bound to.
- Return type
Tkinter.Canvas
- move(dx, dy)[source]¶
Move this canvas widget by a given distance. In particular, shift the canvas widget right by
dxpixels, and down bydypixels. Bothdxanddymay be negative, resulting in leftward or upward movement.- Parameters
dx (int) – The number of pixels to move this canvas widget rightwards.
dy (int) – The number of pixels to move this canvas widget downwards.
- Return type
None
- moveto(x, y, anchor='NW')[source]¶
Move this canvas widget to the given location. In particular, shift the canvas widget such that the corner or side of the bounding box specified by
anchoris at location (x,y).- Parameters
x,y – The location that the canvas widget should be moved to.
anchor – The corner or side of the canvas widget that should be moved to the specified location.
'N'specifies the top center;'NE'specifies the top right corner; etc.
- destroy()[source]¶
Remove this
CanvasWidgetfrom itsCanvas. After aCanvasWidgethas been destroyed, it should not be accessed.Note that you only need to destroy a top-level
CanvasWidget; its child widgets will be destroyed automatically. If you destroy a non-top-levelCanvasWidget, then the entire top-level widget will be destroyed.- Raises
ValueError – if this
CanvasWidgethas a parent.- Return type
None
- update(child)[source]¶
Update the graphical display of this canvas widget, and all of its ancestors, in response to a change in one of this canvas widget’s children.
- Parameters
child (CanvasWidget) – The child widget that changed.
- tags()[source]¶
- Returns
a list of the canvas tags for all graphical elements managed by this canvas widget, including graphical elements managed by its child widgets.
- Return type
list of int
- Returns
True if this canvas widget is hidden.
- Return type
bool
- bind_click(callback, button=1)[source]¶
Register a new callback that will be called whenever this
CanvasWidgetis clicked on.- Parameters
callback (function) – The callback function that will be called whenever this
CanvasWidgetis clicked. This function will be called with thisCanvasWidgetas its argument.button (int) – Which button the user should use to click on this
CanvasWidget. Typically, this should be 1 (left button), 3 (right button), or 2 (middle button).
- bind_drag(callback)[source]¶
Register a new callback that will be called after this
CanvasWidgetis dragged. This implicitly makes thisCanvasWidgetdraggable.- Parameters
callback (function) – The callback function that will be called whenever this
CanvasWidgetis clicked. This function will be called with thisCanvasWidgetas its argument.
- class nltk.draw.util.TextWidget[source]¶
Bases:
CanvasWidgetA canvas widget that displays a single string of text.
- Attributes:
color: the color of the text.font: the font used to display the text.justify: justification for multi-line texts. Valid values areleft,center, andright.width: the width of the text. If the text is wider than this width, it will be line-wrapped at whitespace.draggable: whether the text can be dragged by the user.
- class nltk.draw.util.SymbolWidget[source]¶
Bases:
TextWidgetA canvas widget that displays special symbols, such as the negation sign and the exists operator. Symbols are specified by name. Currently, the following symbol names are defined:
neg,disj,conj,lambda,merge,forall,exists,subseteq,subset,notsubset,emptyset,imp,rightarrow,equal,notequal,epsilon.Attributes:
color: the color of the text.draggable: whether the text can be dragged by the user.
- Variables
SYMBOLS – A dictionary mapping from symbols to the character in the
symbolfont used to render them.
- SYMBOLS = {'conj': 'Ù', 'disj': 'Ú', 'emptyset': 'Æ', 'epsilon': 'e', 'equal': '=', 'exists': '$', 'forall': '"', 'imp': 'Þ', 'intersection': 'Ç', 'lambda': 'l', 'merge': 'Ä', 'neg': 'Ø', 'notequal': '¹', 'notsubset': 'Ë', 'rightarrow': 'Þ', 'subset': 'Ì', 'subseteq': 'Í', 'union': 'È'}¶
- __init__(canvas, symbol, **attribs)[source]¶
Create a new symbol widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
symbol (str) – The name of the symbol to display.
attribs – The new canvas widget’s attributes.
- symbol()[source]¶
- Returns
the name of the symbol that is displayed by this symbol widget.
- Return type
str
- class nltk.draw.util.AbstractContainerWidget[source]¶
Bases:
CanvasWidgetAn abstract class for canvas widgets that contain a single child, such as
BoxWidgetandOvalWidget. Subclasses must define a constructor, which should create any new graphical elements and then call theAbstractCanvasContainerconstructor. Subclasses must also define the_updatemethod and the_tagsmethod; and any subclasses that define attributes should define__setitem__and__getitem__.- __init__(canvas, child, **attribs)[source]¶
Create a new container widget. This constructor should only be called by subclass constructors.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
child (CanvasWidget) – The container’s child widget.
childmust not have a parent.attribs – The new canvas widget’s attributes.
- set_child(child)[source]¶
Change the child widget contained by this container widget.
- Parameters
child (CanvasWidget) – The new child widget.
childmust not have a parent.- Return type
None
- class nltk.draw.util.BoxWidget[source]¶
Bases:
AbstractContainerWidgetA canvas widget that places a box around a child widget.
- Attributes:
fill: The color used to fill the interior of the box.outline: The color used to draw the outline of the box.width: The width of the outline of the box.margin: The number of pixels space left between the child and the box.draggable: whether the text can be dragged by the user.
- __init__(canvas, child, **attribs)[source]¶
Create a new box widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
child (CanvasWidget) – The child widget.
childmust not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.OvalWidget[source]¶
Bases:
AbstractContainerWidgetA canvas widget that places a oval around a child widget.
- Attributes:
fill: The color used to fill the interior of the oval.outline: The color used to draw the outline of the oval.width: The width of the outline of the oval.margin: The number of pixels space left between the child and the oval.draggable: whether the text can be dragged by the user.double: If true, then a double-oval is drawn.
- __init__(canvas, child, **attribs)[source]¶
Create a new oval widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
child (CanvasWidget) – The child widget.
childmust not have a parent.attribs – The new canvas widget’s attributes.
- RATIO = 1.414213562373095¶
- class nltk.draw.util.ParenWidget[source]¶
Bases:
AbstractContainerWidgetA canvas widget that places a pair of parenthases around a child widget.
- Attributes:
color: The color used to draw the parenthases.width: The width of the parenthases.draggable: whether the text can be dragged by the user.
- __init__(canvas, child, **attribs)[source]¶
Create a new parenthasis widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
child (CanvasWidget) – The child widget.
childmust not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.BracketWidget[source]¶
Bases:
AbstractContainerWidgetA canvas widget that places a pair of brackets around a child widget.
- Attributes:
color: The color used to draw the brackets.width: The width of the brackets.draggable: whether the text can be dragged by the user.
- __init__(canvas, child, **attribs)[source]¶
Create a new bracket widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
child (CanvasWidget) – The child widget.
childmust not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.SequenceWidget[source]¶
Bases:
CanvasWidgetA canvas widget that keeps a list of canvas widgets in a horizontal line.
- Attributes:
align: The vertical alignment of the children. Possible values are'top','center', and'bottom'. By default, children are center-aligned.space: The amount of horizontal space to place between children. By default, one pixel of space is used.ordered: If true, then keep the children in their original order.
- __init__(canvas, *children, **attribs)[source]¶
Create a new sequence widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
children (list(CanvasWidget)) – The widgets that should be aligned horizontally. Each child must not have a parent.
attribs – The new canvas widget’s attributes.
- children()[source]¶
- Returns
A list of the hierarchical children of this canvas widget. These children are considered part of
selffor purposes of user interaction.- Return type
list of CanvasWidget
- replace_child(oldchild, newchild)[source]¶
Replace the child canvas widget
oldchildwithnewchild.newchildmust not have a parent.oldchild’s parent will be set to None.- Parameters
oldchild (CanvasWidget) – The child canvas widget to remove.
newchild (CanvasWidget) – The canvas widget that should replace
oldchild.
- remove_child(child)[source]¶
Remove the given child canvas widget.
child’s parent will be set to None.- Parameters
child (CanvasWidget) – The child canvas widget to remove.
- insert_child(index, child)[source]¶
Insert a child canvas widget before a given index.
- Parameters
child (CanvasWidget) – The canvas widget that should be inserted.
index (int) – The index where the child widget should be inserted. In particular, the index of
childwill beindex; and the index of any children whose indices were greater than equal toindexbeforechildwas inserted will be incremented by one.
- class nltk.draw.util.StackWidget[source]¶
Bases:
CanvasWidgetA canvas widget that keeps a list of canvas widgets in a vertical line.
- Attributes:
align: The horizontal alignment of the children. Possible values are'left','center', and'right'. By default, children are center-aligned.space: The amount of vertical space to place between children. By default, one pixel of space is used.ordered: If true, then keep the children in their original order.
- __init__(canvas, *children, **attribs)[source]¶
Create a new stack widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
children (list(CanvasWidget)) – The widgets that should be aligned vertically. Each child must not have a parent.
attribs – The new canvas widget’s attributes.
- children()[source]¶
- Returns
A list of the hierarchical children of this canvas widget. These children are considered part of
selffor purposes of user interaction.- Return type
list of CanvasWidget
- replace_child(oldchild, newchild)[source]¶
Replace the child canvas widget
oldchildwithnewchild.newchildmust not have a parent.oldchild’s parent will be set to None.- Parameters
oldchild (CanvasWidget) – The child canvas widget to remove.
newchild (CanvasWidget) – The canvas widget that should replace
oldchild.
- remove_child(child)[source]¶
Remove the given child canvas widget.
child’s parent will be set to None.- Parameters
child (CanvasWidget) – The child canvas widget to remove.
- insert_child(index, child)[source]¶
Insert a child canvas widget before a given index.
- Parameters
child (CanvasWidget) – The canvas widget that should be inserted.
index (int) – The index where the child widget should be inserted. In particular, the index of
childwill beindex; and the index of any children whose indices were greater than equal toindexbeforechildwas inserted will be incremented by one.
- class nltk.draw.util.SpaceWidget[source]¶
Bases:
CanvasWidgetA canvas widget that takes up space but does not display anything. A
SpaceWidgetcan be used to add space between elements. Each space widget is characterized by a width and a height. If you wish to only create horizontal space, then use a height of zero; and if you wish to only create vertical space, use a width of zero.- __init__(canvas, width, height, **attribs)[source]¶
Create a new space widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
width (int) – The width of the new space widget.
height (int) – The height of the new space widget.
attribs – The new canvas widget’s attributes.
- class nltk.draw.util.ScrollWatcherWidget[source]¶
Bases:
CanvasWidgetA special canvas widget that adjusts its
Canvas’s scrollregion to always include the bounding boxes of all of its children. The scroll-watcher widget will only increase the size of theCanvas’s scrollregion; it will never decrease it.- __init__(canvas, *children, **attribs)[source]¶
Create a new scroll-watcher widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
children (list(CanvasWidget)) – The canvas widgets watched by the scroll-watcher. The scroll-watcher will ensure that these canvas widgets are always contained in their canvas’s scrollregion.
attribs – The new canvas widget’s attributes.
- add_child(canvaswidget)[source]¶
Add a new canvas widget to the scroll-watcher. The scroll-watcher will ensure that the new canvas widget is always contained in its canvas’s scrollregion.
- Parameters
canvaswidget (CanvasWidget) – The new canvas widget.
- Return type
None
- remove_child(canvaswidget)[source]¶
Remove a canvas widget from the scroll-watcher. The scroll-watcher will no longer ensure that the new canvas widget is always contained in its canvas’s scrollregion.
- Parameters
canvaswidget (CanvasWidget) – The canvas widget to remove.
- Return type
None
- class nltk.draw.util.CanvasFrame[source]¶
Bases:
objectA
Tkinterframe containing a canvas and scrollbars.CanvasFrameuses aScrollWatcherWidgetto ensure that all of the canvas widgets contained on its canvas are within its scrollregion. In order forCanvasFrameto make these checks, all canvas widgets must be registered withadd_widgetwhen they are added to the canvas; and destroyed withdestroy_widgetwhen they are no longer needed.If a
CanvasFrameis created with no parent, then it will create its own main window, including a “Done” button and a “Print” button.- __init__(parent=None, **kw)[source]¶
Create a new
CanvasFrame.- Parameters
parent (Tkinter.BaseWidget or Tkinter.Tk) – The parent
Tkinterwidget. If no parent is specified, thenCanvasFramewill create a new main window.kw – Keyword arguments for the new
Canvas. See the documentation forTkinter.Canvasfor more information.
- print_to_file(filename=None)[source]¶
Print the contents of this
CanvasFrameto a postscript file. If no filename is given, then prompt the user for one.- Parameters
filename (str) – The name of the file to print the tree to.
- Return type
None
- scrollregion()[source]¶
- Returns
The current scroll region for the canvas managed by this
CanvasFrame.- Return type
4-tuple of int
- add_widget(canvaswidget, x=None, y=None)[source]¶
Register a canvas widget with this
CanvasFrame. TheCanvasFramewill ensure that this canvas widget is always within theCanvas’s scrollregion. If no coordinates are given for the canvas widget, then theCanvasFramewill attempt to find a clear area of the canvas for it.- Parameters
canvaswidget (CanvasWidget) – The new canvas widget.
canvaswidgetmust have been created on thisCanvasFrame’s canvas.x (int) – The initial x coordinate for the upper left hand corner of
canvaswidget, in the canvas’s coordinate space.y (int) – The initial y coordinate for the upper left hand corner of
canvaswidget, in the canvas’s coordinate space.
- destroy_widget(canvaswidget)[source]¶
Remove a canvas widget from this
CanvasFrame. This deregisters the canvas widget, and destroys it.
- pack(cnf={}, **kw)[source]¶
Pack this
CanvasFrame. See the documentation forTkinter.Packfor more information.
- class nltk.draw.util.ShowText[source]¶
Bases:
objectA
Tkinterwindow used to display a text.ShowTextis typically used by graphical tools to display help text, or similar information.
- class nltk.draw.util.ColorizedList[source]¶
Bases:
objectAn abstract base class for displaying a colorized list of items. Subclasses should define:
_init_colortags, which sets up Text color tags that will be used by the list._item_repr, which returns a list of (text,colortag) tuples that make up the colorized representation of the item.
- Note
Typically, you will want to register a callback for
'select'that callsmarkon the given item.
- __init__(parent, items=[], **options)[source]¶
Construct a new list.
- Parameters
parent – The Tk widget that contains the colorized list
items – The initial contents of the colorized list.
options –
- unmark(item=None)[source]¶
Remove highlighting from the given item; or from every item, if no item is given. :raise ValueError: If
itemis not contained in the list. :raise KeyError: Ifitemis not marked.
- mark(item)[source]¶
Highlight the given item. :raise ValueError: If
itemis not contained in the list.
- markonly(item)[source]¶
Remove any current highlighting, and mark the given item. :raise ValueError: If
itemis not contained in the list.
- view(item)[source]¶
Adjust the view such that the given item is visible. If the item is already visible, then do nothing.
- add_callback(event, func)[source]¶
Register a callback function with the list. This function will be called whenever the given event occurs.
- Parameters
event – The event that will trigger the callback function. Valid events are: click1, click2, click3, space, return, select, up, down, next, prior, move
func – The function that should be called when the event occurs.
funcwill be called with a single item as its argument. (The item selected or the item moved to).