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.AbstractContainerWidget[source]¶
Bases:
CanvasWidget
An abstract class for canvas widgets that contain a single child, such as
BoxWidget
andOvalWidget
. Subclasses must define a constructor, which should create any new graphical elements and then call theAbstractCanvasContainer
constructor. Subclasses must also define the_update
method and the_tags
method; 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.
child
must 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.
child
must not have a parent.- Return type
None
- class nltk.draw.util.BoxWidget[source]¶
Bases:
AbstractContainerWidget
A 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.
child
must not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.BracketWidget[source]¶
Bases:
AbstractContainerWidget
A 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.
child
must not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.CanvasFrame[source]¶
Bases:
object
A
Tkinter
frame containing a canvas and scrollbars.CanvasFrame
uses aScrollWatcherWidget
to ensure that all of the canvas widgets contained on its canvas are within its scrollregion. In order forCanvasFrame
to make these checks, all canvas widgets must be registered withadd_widget
when they are added to the canvas; and destroyed withdestroy_widget
when they are no longer needed.If a
CanvasFrame
is 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
Tkinter
widget. If no parent is specified, thenCanvasFrame
will create a new main window.kw – Keyword arguments for the new
Canvas
. See the documentation forTkinter.Canvas
for more information.
- add_widget(canvaswidget, x=None, y=None)[source]¶
Register a canvas widget with this
CanvasFrame
. TheCanvasFrame
will ensure that this canvas widget is always within theCanvas
’s scrollregion. If no coordinates are given for the canvas widget, then theCanvasFrame
will attempt to find a clear area of the canvas for it.- Parameters
canvaswidget (CanvasWidget) – The new canvas widget.
canvaswidget
must 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(*e)[source]¶
Destroy this
CanvasFrame
. If thisCanvasFrame
created a top-level window, then this will close that window.
- destroy_widget(canvaswidget)[source]¶
Remove a canvas widget from this
CanvasFrame
. This deregisters the canvas widget, and destroys it.
- mainloop(*args, **kwargs)[source]¶
Enter the Tkinter mainloop. This function must be called if this frame is created from a non-interactive program (e.g. from a secript); otherwise, the frame will close as soon as the script completes.
- pack(cnf={}, **kw)[source]¶
Pack this
CanvasFrame
. See the documentation forTkinter.Pack
for more information.
- class nltk.draw.util.CanvasWidget[source]¶
Bases:
object
A collection of graphical elements and bindings used to display a complex object on a Tkinter
Canvas
. A canvas widget is responsible for managing theCanvas
tags 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
. ThisCanvas
is 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(Canvas(), '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.CanvasWidget
provides callback support for two types of user interaction: clicking and dragging. The methodbind_click
registers a callback function that is called whenever the canvas widget is clicked. The methodbind_drag
registers 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_click
andunbind_drag
methods.Subclassing.
CanvasWidget
is 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_widget
on each child widget.Call the
CanvasWidget
constructor.
_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
CanvasWidget
with no child widgets, the default definitions for_manage
and_update
may 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
CanvasWidget
in 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 theCanvasWidget
that 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)
- bind_click(callback, button=1)[source]¶
Register a new callback that will be called whenever this
CanvasWidget
is clicked on.- Parameters
callback (function) – The callback function that will be called whenever this
CanvasWidget
is clicked. This function will be called with thisCanvasWidget
as 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
CanvasWidget
is dragged. This implicitly makes thisCanvasWidget
draggable.- Parameters
callback (function) – The callback function that will be called whenever this
CanvasWidget
is clicked. This function will be called with thisCanvasWidget
as its argument.
- canvas()[source]¶
- Returns
The canvas that this canvas widget is bound to.
- Return type
Tkinter.Canvas
- child_widgets()[source]¶
- Returns
A list of the hierarchical children of this canvas widget. These children are considered part of
self
for purposes of user interaction.- Return type
list of CanvasWidget
- destroy()[source]¶
Remove this
CanvasWidget
from itsCanvas
. After aCanvasWidget
has 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
CanvasWidget
has a parent.- Return type
None
- height()[source]¶
- Returns
The height of this canvas widget’s bounding box, in its
Canvas
’s coordinate space.- Return type
int
- Returns
True if this canvas widget is hidden.
- Return type
bool
- move(dx, dy)[source]¶
Move this canvas widget by a given distance. In particular, shift the canvas widget right by
dx
pixels, and down bydy
pixels. Bothdx
anddy
may 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
anchor
is 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.
- parent()[source]¶
- Returns
The hierarchical parent of this canvas widget.
self
is considered a subpart of its parent for purposes of user interaction.- Return type
CanvasWidget or None
- 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
- unbind_click(button=1)[source]¶
Remove a callback that was registered with
bind_click
.- Parameters
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).
- 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.
- class nltk.draw.util.ColorizedList[source]¶
Bases:
object
An 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 callsmark
on 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 –
- 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.
func
will be called with a single item as its argument. (The item selected or the item moved to).
- mark(item)[source]¶
Highlight the given item. :raise ValueError: If
item
is not contained in the list.
- markonly(item)[source]¶
Remove any current highlighting, and mark the given item. :raise ValueError: If
item
is not contained in the list.
- remove_callback(event, func=None)[source]¶
Deregister a callback function. If
func
is none, then all callbacks are removed for the given event.
- class nltk.draw.util.MutableOptionMenu[source]¶
Bases:
Menubutton
- class nltk.draw.util.OvalWidget[source]¶
Bases:
AbstractContainerWidget
A 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.
- RATIO = 1.414213562373095¶
- __init__(canvas, child, **attribs)[source]¶
Create a new oval widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
child (CanvasWidget) – The child widget.
child
must not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.ParenWidget[source]¶
Bases:
AbstractContainerWidget
A 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.
child
must not have a parent.attribs – The new canvas widget’s attributes.
- class nltk.draw.util.ScrollWatcherWidget[source]¶
Bases:
CanvasWidget
A 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.SequenceWidget[source]¶
Bases:
CanvasWidget
A 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()¶
- Returns
A list of the hierarchical children of this canvas widget. These children are considered part of
self
for purposes of user interaction.- Return type
list of CanvasWidget
- 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
child
will beindex
; and the index of any children whose indices were greater than equal toindex
beforechild
was inserted will be incremented by one.
- 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.
- replace_child(oldchild, newchild)[source]¶
Replace the child canvas widget
oldchild
withnewchild
.newchild
must 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
.
- class nltk.draw.util.ShowText[source]¶
Bases:
object
A
Tkinter
window used to display a text.ShowText
is typically used by graphical tools to display help text, or similar information.
- class nltk.draw.util.SpaceWidget[source]¶
Bases:
CanvasWidget
A canvas widget that takes up space but does not display anything. A
SpaceWidget
can 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.StackWidget[source]¶
Bases:
CanvasWidget
A 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()¶
- Returns
A list of the hierarchical children of this canvas widget. These children are considered part of
self
for purposes of user interaction.- Return type
list of CanvasWidget
- 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
child
will beindex
; and the index of any children whose indices were greater than equal toindex
beforechild
was inserted will be incremented by one.
- 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.
- replace_child(oldchild, newchild)[source]¶
Replace the child canvas widget
oldchild
withnewchild
.newchild
must 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
.
- class nltk.draw.util.SymbolWidget[source]¶
Bases:
TextWidget
A 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
symbol
font 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.
- set_symbol(symbol)[source]¶
Change the symbol that is displayed by this symbol widget.
- Parameters
symbol (str) – The name of the symbol to display.
- class nltk.draw.util.TextWidget[source]¶
Bases:
CanvasWidget
A 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.
- __init__(canvas, text, **attribs)[source]¶
Create a new text widget.
- Parameters
canvas (Tkinter.Canvas) – This canvas widget’s canvas.
text (str) – The string of text to display.
attribs – The new canvas widget’s attributes.