nltk.draw package

Submodules

nltk.draw.cfg module

Visualization tools for CFGs.

class nltk.draw.cfg.CFGDemo(grammar, text)[source]

Bases: object

destroy(*args)[source]
mainloop(*args, **kwargs)[source]
reset_workspace()[source]
workspace_markprod(production)[source]
class nltk.draw.cfg.CFGEditor(parent, cfg=None, set_cfg_callback=None)[source]

Bases: object

A dialog window for creating and editing context free grammars. CFGEditor imposes the following restrictions:

  • All nonterminals must be strings consisting of word characters.
  • All terminals must be strings consisting of word characters and space characters.
ARROW = 'Þ'
class nltk.draw.cfg.ProductionList(parent, items=[], **options)[source]

Bases: nltk.draw.util.ColorizedList

ARROW = 'Þ'
nltk.draw.cfg.demo()[source]
nltk.draw.cfg.demo2()[source]
nltk.draw.cfg.demo3()[source]

nltk.draw.dispersion module

A utility for displaying lexical dispersion.

nltk.draw.dispersion.dispersion_plot(text, words, ignore_case=False, title='Lexical Dispersion Plot')[source]

Generate a lexical dispersion plot.

Parameters:
  • text (list(str) or enum(str)) – The source text
  • words (list of str) – The target words
  • ignore_case (bool) – flag to set if case should be ignored when searching text

nltk.draw.table module

Tkinter widgets for displaying multi-column listboxes and tables.

class nltk.draw.table.MultiListbox(master, columns, column_weights=None, cnf={}, **kw)[source]

Bases: tkinter.Frame

A multi-column listbox, where the current selection applies to an entire row. Based on the MultiListbox Tkinter widget recipe from the Python Cookbook (http://code.activestate.com/recipes/52266/)

For the most part, MultiListbox methods delegate to its contained listboxes. For any methods that do not have docstrings, see Tkinter.Listbox for a description of what that method does.

FRAME_CONFIG = {'background': '#888', 'highlightthickness': 1, 'takefocus': True}

Default configuration values for the frame.

LABEL_CONFIG = {'background': '#444', 'borderwidth': 1, 'font': 'helvetica -16 bold', 'foreground': 'white', 'relief': 'raised'}

Default configurations for the column labels.

LISTBOX_CONFIG = {'activestyle': 'none', 'borderwidth': 1, 'exportselection': False, 'highlightthickness': 0, 'selectbackground': '#888', 'selectborderwidth': 0, 'takefocus': False}

Default configuration for the column listboxes.

activate(*args, **kwargs)[source]
bbox(row, col)[source]

Return the bounding box for the given table cell, relative to this widget’s top-left corner. The bounding box is a tuple of integers (left, top, width, height).

bind_to_columns(sequence=None, func=None, add=None)[source]

Add a binding to each Tkinter.Label and Tkinter.Listbox widget in this mult-column listbox that will call func in response to the event sequence.

Returns:A list of the identifiers of replaced binding functions (if any), allowing for their deletion (to prevent a memory leak).
bind_to_labels(sequence=None, func=None, add=None)[source]

Add a binding to each Tkinter.Label widget in this mult-column listbox that will call func in response to the event sequence.

Returns:A list of the identifiers of replaced binding functions (if any), allowing for their deletion (to prevent a memory leak).
bind_to_listboxes(sequence=None, func=None, add=None)[source]

Add a binding to each Tkinter.Listbox widget in this mult-column listbox that will call func in response to the event sequence.

Returns:A list of the identifiers of replaced binding functions (if any), allowing for their deletion (to prevent a memory leak).
column_labels

A tuple containing the Tkinter.Label widgets used to display the label of each column. If this multi-column listbox was created without labels, then this will be an empty tuple. These widgets will all be augmented with a column_index attribute, which can be used to determine which column they correspond to. This can be convenient, e.g., when defining callbacks for bound events.

column_names

A tuple containing the names of the columns used by this multi-column listbox.

columnconfig(col_index, cnf={}, **kw)

Configure all table cells in the given column. Valid keyword arguments are: background, bg, foreground, fg, selectbackground, selectforeground.

columnconfigure(col_index, cnf={}, **kw)[source]

Configure all table cells in the given column. Valid keyword arguments are: background, bg, foreground, fg, selectbackground, selectforeground.

configure(cnf={}, **kw)[source]

Configure this widget. Use label_* to configure all labels; and listbox_* to configure all listboxes. E.g.:

>>> mlb = MultiListbox(master, 5)
>>> mlb.configure(label_foreground='red')
>>> mlb.configure(listbox_foreground='red')
curselection(*args, **kwargs)[source]
delete(*args, **kwargs)[source]
get(first, last=None)[source]

Return the value(s) of the specified row(s). If last is not specified, then return a single row value; otherwise, return a list of row values. Each row value is a tuple of cell values, one for each column in the row.

hide_column(col_index)[source]

Hide the given column. The column’s state is still maintained: its values will still be returned by get(), and you must supply its values when calling insert(). It is safe to call this on a column that is already hidden.

See:show_column()
index(*args, **kwargs)[source]
insert(index, *rows)[source]

Insert the given row or rows into the table, at the given index. Each row value should be a tuple of cell values, one for each column in the row. Index may be an integer or any of the special strings (such as 'end') accepted by Tkinter.Listbox.

itemcget(*args, **kwargs)[source]
itemconfig(row_index, col_index, cnf=None, **kw)

Configure the table cell at the given row and column. Valid keyword arguments are: background, bg, foreground, fg, selectbackground, selectforeground.

itemconfigure(row_index, col_index, cnf=None, **kw)[source]

Configure the table cell at the given row and column. Valid keyword arguments are: background, bg, foreground, fg, selectbackground, selectforeground.

listboxes

A tuple containing the Tkinter.Listbox widgets used to display individual columns. These widgets will all be augmented with a column_index attribute, which can be used to determine which column they correspond to. This can be convenient, e.g., when defining callbacks for bound events.

nearest(*args, **kwargs)[source]
rowconfig(row_index, cnf={}, **kw)

Configure all table cells in the given row. Valid keyword arguments are: background, bg, foreground, fg, selectbackground, selectforeground.

rowconfigure(row_index, cnf={}, **kw)[source]

Configure all table cells in the given row. Valid keyword arguments are: background, bg, foreground, fg, selectbackground, selectforeground.

scan_dragto(*args, **kwargs)[source]
scan_mark(*args, **kwargs)[source]
see(*args, **kwargs)[source]
select(index=None, delta=None, see=True)[source]

Set the selected row. If index is specified, then select row index. Otherwise, if delta is specified, then move the current selection by delta (negative numbers for up, positive numbers for down). This will not move the selection past the top or the bottom of the list.

Parameters:see – If true, then call self.see() with the newly selected index, to ensure that it is visible.
select_anchor(*args, **kwargs)
select_clear(*args, **kwargs)

Clear the current X selection.

select_includes(*args, **kwargs)
select_set(*args, **kwargs)
selection_anchor(*args, **kwargs)[source]
selection_clear(*args, **kwargs)[source]

Clear the current X selection.

selection_includes(*args, **kwargs)[source]
selection_set(*args, **kwargs)[source]
show_column(col_index)[source]

Display a column that has been hidden using hide_column(). It is safe to call this on a column that is not hidden.

size(*args, **kwargs)[source]

Return a tuple of the number of column and rows in the grid.

yview(*args, **kwargs)[source]
yview_moveto(*args, **kwargs)[source]
yview_scroll(*args, **kwargs)[source]
class nltk.draw.table.Table(master, column_names, rows=None, column_weights=None, scrollbar=True, click_to_sort=True, reprfunc=None, cnf={}, **kw)[source]

Bases: object

A display widget for a table of values, based on a MultiListbox widget. For many purposes, Table can be treated as a list-of-lists. E.g., table[i] is a list of the values for row i; and table.append(row) adds a new row with the given lits of values. Individual cells can be accessed using table[i,j], which refers to the j-th column of the i-th row. This can be used to both read and write values from the table. E.g.:

>>> table[i,j] = 'hello'

The column (j) can be given either as an index number, or as a column name. E.g., the following prints the value in the 3rd row for the ‘First Name’ column:

>>> print(table[3, 'First Name'])
John

You can configure the colors for individual rows, columns, or cells using rowconfig(), columnconfig(), and itemconfig(). The color configuration for each row will be preserved if the table is modified; however, when new rows are added, any color configurations that have been made for columns will not be applied to the new row.

Note: Although Table acts like a widget in some ways (e.g., it defines grid(), pack(), and bind()), it is not itself a widget; it just contains one. This is because widgets need to define __getitem__(), __setitem__(), and __nonzero__() in a way that’s incompatible with the fact that Table behaves as a list-of-lists.

Variables:
  • _mlb – The multi-column listbox used to display this table’s data.
  • _rows – A list-of-lists used to hold the cell values of this table. Each element of _rows is a row value, i.e., a list of cell values, one for each column in the row.
append(rowvalue)[source]

Add a new row to the end of the table.

Parameters:rowvalue – A tuple of cell values, one for each column in the new row.
bind(sequence=None, func=None, add=None)[source]

Add a binding to this table’s main frame that will call func in response to the event sequence.

bind_to_columns(sequence=None, func=None, add=None)[source]
See:MultiListbox.bind_to_columns()
bind_to_labels(sequence=None, func=None, add=None)[source]
See:MultiListbox.bind_to_labels()
bind_to_listboxes(sequence=None, func=None, add=None)[source]
See:MultiListbox.bind_to_listboxes()
clear()[source]

Delete all rows in this table.

column_index(i)[source]

If i is a valid column index integer, then return it as is. Otherwise, check if i is used as the name for any column; if so, return that column’s index. Otherwise, raise a KeyError exception.

column_names

A list of the names of the columns in this table.

columnconfig(col_index, cnf={}, **kw)
See:MultiListbox.columnconfigure()
columnconfigure(col_index, cnf={}, **kw)[source]
See:MultiListbox.columnconfigure()
extend(rowvalues)[source]

Add new rows at the end of the table.

Parameters:rowvalues – A list of row values used to initialze the table. Each row value should be a tuple of cell values, one for each column in the row.
focus()[source]

Direct (keyboard) input foxus to this widget.

grid(*args, **kwargs)[source]

Position this table’s main frame widget in its parent widget. See Tkinter.Frame.grid() for more info.

hide_column(column_index)[source]
See:MultiListbox.hide_column()
insert(row_index, rowvalue)[source]

Insert a new row into the table, so that its row index will be row_index. If the table contains any rows whose row index is greater than or equal to row_index, then they will be shifted down.

Parameters:rowvalue – A tuple of cell values, one for each column in the new row.
itemconfig(row_index, col_index, cnf=None, **kw)
See:MultiListbox.itemconfigure()
itemconfigure(row_index, col_index, cnf=None, **kw)[source]
See:MultiListbox.itemconfigure()
pack(*args, **kwargs)[source]

Position this table’s main frame widget in its parent widget. See Tkinter.Frame.pack() for more info.

rowconfig(row_index, cnf={}, **kw)
See:MultiListbox.rowconfigure()
rowconfigure(row_index, cnf={}, **kw)[source]
See:MultiListbox.rowconfigure()
select(index=None, delta=None, see=True)[source]
See:MultiListbox.select()
selected_row()[source]

Return the index of the currently selected row, or None if no row is selected. To get the row value itself, use table[table.selected_row()].

show_column(column_index)[source]
See:MultiListbox.show_column()
sort_by(column_index, order='toggle')[source]

Sort the rows in this table, using the specified column’s values as a sort key.

Parameters:
  • column_index – Specifies which column to sort, using either a column index (int) or a column’s label name (str).
  • order

    Specifies whether to sort the values in ascending or descending order:

    • 'ascending': Sort from least to greatest.
    • 'descending': Sort from greatest to least.
    • 'toggle': If the most recent call to sort_by() sorted the table by the same column (column_index), then reverse the rows; otherwise sort in ascending order.
nltk.draw.table.demo()[source]

nltk.draw.tree module

Graphically display a Tree.

class nltk.draw.tree.TreeSegmentWidget(canvas, label, subtrees, **attribs)[source]

Bases: nltk.draw.util.CanvasWidget

A canvas widget that displays a single segment of a hierarchical tree. Each TreeSegmentWidget connects a single “node widget” to a sequence of zero or more “subtree widgets”. By default, the bottom of the node is connected to the top of each subtree by a single line. However, if the roof attribute is set, then a single triangular “roof” will connect the node to all of its children.

Attributes:
  • roof: What sort of connection to draw between the node and its subtrees. If roof is true, draw a single triangular “roof” over the subtrees. If roof is false, draw a line between each subtree and the node. Default value is false.
  • xspace: The amount of horizontal space to leave between subtrees when managing this widget. Default value is 10.
  • yspace: The amount of space to place between the node and its children when managing this widget. Default value is 15.
  • color: The color of the lines connecting the node to its subtrees; and of the outline of the triangular roof. Default value is '#006060'.
  • fill: The fill color for the triangular roof. Default value is '' (no fill).
  • width: The width of the lines connecting the node to its subtrees; and of the outline of the triangular roof. Default value is 1.
  • orientation: Determines whether the tree branches downwards or rightwards. Possible values are 'horizontal' and 'vertical'. The default value is 'vertical' (i.e., branch downwards).
  • draggable: whether the widget can be dragged by the user.
insert_child(index, child)[source]
label()[source]
remove_child(child)[source]
replace_child(oldchild, newchild)[source]

Replace the child oldchild with newchild.

set_label(label)[source]

Set the node label to label.

subtrees()[source]
class nltk.draw.tree.TreeView(*trees)[source]

Bases: object

destroy(*e)[source]
mainloop(*args, **kwargs)[source]

Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes.

resize(*e)[source]
class nltk.draw.tree.TreeWidget(canvas, t, make_node=<class 'nltk.draw.util.TextWidget'>, make_leaf=<class 'nltk.draw.util.TextWidget'>, **attribs)[source]

Bases: nltk.draw.util.CanvasWidget

A canvas widget that displays a single Tree. TreeWidget manages a group of TreeSegmentWidgets that are used to display a Tree.

Attributes:

  • node_attr: Sets the attribute attr on all of the node widgets for this TreeWidget.
  • node_attr: Sets the attribute attr on all of the leaf widgets for this TreeWidget.
  • loc_attr: Sets the attribute attr on all of the location widgets for this TreeWidget (if it was built from a Tree). Note that a location widget is a TextWidget.
  • xspace: The amount of horizontal space to leave between subtrees when managing this widget. Default value is 10.
  • yspace: The amount of space to place between the node and its children when managing this widget. Default value is 15.
  • line_color: The color of the lines connecting each expanded node to its subtrees.
  • roof_color: The color of the outline of the triangular roof for collapsed trees.
  • roof_fill: The fill color for the triangular roof for collapsed trees.
  • width
  • orientation: Determines whether the tree branches downwards or rightwards. Possible values are 'horizontal' and 'vertical'. The default value is 'vertical' (i.e., branch downwards).
  • shapeable: whether the subtrees can be independently dragged by the user. THIS property simply sets the DRAGGABLE property on all of the TreeWidget’s tree segments.
  • draggable: whether the widget can be dragged by the user.
bind_click_leaves(callback, button=1)[source]

Add a binding to all leaves.

bind_click_nodes(callback, button=1)[source]

Add a binding to all nodes.

bind_click_trees(callback, button=1)[source]

Add a binding to all tree segments.

bind_drag_leaves(callback, button=1)[source]

Add a binding to all leaves.

bind_drag_nodes(callback, button=1)[source]

Add a binding to all nodes.

bind_drag_trees(callback, button=1)[source]

Add a binding to all tree segments.

collapsed_tree(*path_to_tree)[source]

Return the TreeSegmentWidget for the specified subtree.

Parameters:path_to_tree – A list of indices i1, i2, …, in, where the desired widget is the widget corresponding to tree.children()[i1].children()[i2]....children()[in]. For the root, the path is ().
expanded_tree(*path_to_tree)[source]

Return the TreeSegmentWidget for the specified subtree.

Parameters:path_to_tree – A list of indices i1, i2, …, in, where the desired widget is the widget corresponding to tree.children()[i1].children()[i2]....children()[in]. For the root, the path is ().
toggle_collapsed(treeseg)[source]

Collapse/expand a tree.

nltk.draw.tree.demo()[source]
nltk.draw.tree.draw_trees(*trees)[source]

Open a new window containing a graphical diagram of the given trees.

Return type:None
nltk.draw.tree.tree_to_treesegment(canvas, t, make_node=<class 'nltk.draw.util.TextWidget'>, make_leaf=<class 'nltk.draw.util.TextWidget'>, **attribs)[source]

Convert a Tree into a TreeSegmentWidget.

Parameters:
  • make_node – A CanvasWidget constructor or a function that creates CanvasWidgets. make_node is used to convert the Tree’s nodes into CanvasWidgets. If no constructor is specified, then TextWidget will be used.
  • make_leaf – A CanvasWidget constructor or a function that creates CanvasWidgets. make_leaf is used to convert the Tree’s leafs into CanvasWidgets. If no constructor is specified, then TextWidget will be used.
  • attribs – Attributes for the canvas widgets that make up the returned TreeSegmentWidget. Any attribute beginning with 'tree_' will be passed to all TreeSegmentWidgets (with the 'tree_' prefix removed. Any attribute beginning with 'node_' will be passed to all nodes. Any attribute beginning with 'leaf_' will be passed to all leaves. And any attribute beginning with 'loc_' will be passed to all text locations (for Trees).

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(canvas, child, **attribs)[source]

Bases: nltk.draw.util.CanvasWidget

An abstract class for canvas widgets that contain a single child, such as BoxWidget and OvalWidget. Subclasses must define a constructor, which should create any new graphical elements and then call the AbstractCanvasContainer constructor. Subclasses must also define the _update method and the _tags method; and any subclasses that define attributes should define __setitem__ and __getitem__.

child()[source]
Returns:The child widget contained by this container widget.
Return type:CanvasWidget
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(canvas, child, **attribs)[source]

Bases: nltk.draw.util.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.
class nltk.draw.util.BracketWidget(canvas, child, **attribs)[source]

Bases: nltk.draw.util.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.
class nltk.draw.util.CanvasFrame(parent=None, **kw)[source]

Bases: object

A Tkinter frame containing a canvas and scrollbars. CanvasFrame uses a ScrollWatcherWidget to ensure that all of the canvas widgets contained on its canvas are within its scrollregion. In order for CanvasFrame to make these checks, all canvas widgets must be registered with add_widget when they are added to the canvas; and destroyed with destroy_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.

add_widget(canvaswidget, x=None, y=None)[source]

Register a canvas widget with this CanvasFrame. The CanvasFrame will ensure that this canvas widget is always within the Canvas’s scrollregion. If no coordinates are given for the canvas widget, then the CanvasFrame 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 this CanvasFrame’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.
canvas()[source]
Returns:The canvas managed by this CanvasFrame.
Return type:Tkinter.Canvas
destroy(*e)[source]

Destroy this CanvasFrame. If this CanvasFrame 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 for Tkinter.Pack for more information.

print_to_file(filename=None)[source]

Print the contents of this CanvasFrame to 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
remove_widget(canvaswidget)[source]
scrollregion()[source]
Returns:The current scroll region for the canvas managed by this CanvasFrame.
Return type:4-tuple of int
class nltk.draw.util.CanvasWidget(canvas, parent=None, **attribs)[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 the Canvas 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. This Canvas is specified as the first argument to the CanvasWidget’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, and radius. Each attribute has a default value. This default value can be overridden in the constructor, using keyword arguments of the form attribute=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.

CanvasWidget provides callback support for two types of user interaction: clicking and dragging. The method bind_click registers a callback function that is called whenever the canvas widget is clicked. The method bind_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 the unbind_click and unbind_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 to CanvasWidget.

Most subclasses implement a number of additional methods that modify the CanvasWidget in some way. These methods must call parent.update(self) after making any changes to the canvas widget’s graphical elements. The canvas widget must also call parent.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 the CanvasWidget that triggered the callback.
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 the Canvas.
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 this CanvasWidget 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 this CanvasWidget draggable.

Parameters:callback (function) – The callback function that will be called whenever this CanvasWidget is clicked. This function will be called with this CanvasWidget 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 its Canvas. After a CanvasWidget 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-level CanvasWidget, 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
hidden()[source]
Returns:True if this canvas widget is hidden.
Return type:bool
hide()[source]

Temporarily hide this canvas widget.

Return type:None
manage()[source]

Arrange this canvas widget and all of its descendants.

Return type:None
move(dx, dy)[source]

Move this canvas widget by a given distance. In particular, shift the canvas widget right by dx pixels, and down by dy pixels. Both dx and dy 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
show()[source]

Show a hidden canvas widget.

Return type: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).
unbind_drag()[source]

Remove a callback that was registered with bind_drag.

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.
width()[source]
Returns:The width of this canvas widget’s bounding box, in its Canvas’s coordinate space.
Return type:int
class nltk.draw.util.ColorizedList(parent, items=[], **options)[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 calls mark on the given item.
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).
focus()[source]
get(index=None)[source]
Returns:A list of the items contained by this list.
grid(cnf={}, **kw)[source]
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.

pack(cnf={}, **kw)[source]
remove_callback(event, func=None)[source]

Deregister a callback function. If func is none, then all callbacks are removed for the given event.

set(items)[source]

Modify the list of items contained by this list.

unmark(item=None)[source]

Remove highlighting from the given item; or from every item, if no item is given. :raise ValueError: If item is not contained in the list. :raise KeyError: If item is not marked.

view(item)[source]

Adjust the view such that the given item is visible. If the item is already visible, then do nothing.

class nltk.draw.util.EntryDialog(parent, original_text='', instructions='', set_callback=None, title=None)[source]

Bases: object

A dialog box for entering

class nltk.draw.util.MutableOptionMenu(master, values, **options)[source]

Bases: tkinter.Menubutton

add(value)[source]
destroy()[source]

Destroy this widget and the associated menu.

remove(value)[source]
set(value)[source]
class nltk.draw.util.OvalWidget(canvas, child, **attribs)[source]

Bases: nltk.draw.util.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
class nltk.draw.util.ParenWidget(canvas, child, **attribs)[source]

Bases: nltk.draw.util.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.
class nltk.draw.util.ScrollWatcherWidget(canvas, *children, **attribs)[source]

Bases: nltk.draw.util.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 the Canvas’s scrollregion; it will never decrease it.

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(canvas, *children, **attribs)[source]

Bases: nltk.draw.util.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.
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 be index; and the index of any children whose indices were greater than equal to index before child was inserted will be incremented by one.
remove_child(child)[source]

Remove the given child canvas widget. child’s parent will be set ot None.

Parameters:child (CanvasWidget) – The child canvas widget to remove.
replace_child(oldchild, newchild)[source]

Replace the child canvas widget oldchild with newchild. 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(root, title, text, width=None, height=None, **textbox_options)[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.

destroy(*e)[source]
find_dimentions(text, width, height)[source]
mainloop(*args, **kwargs)[source]

Enter the Tkinter mainloop. This function must be called if this window is created from a non-interactive program (e.g. from a secript); otherwise, the window will close as soon as the script completes.

class nltk.draw.util.SpaceWidget(canvas, width, height, **attribs)[source]

Bases: nltk.draw.util.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.

set_height(height)[source]

Change the height of this space widget.

Parameters:height (int) – The new height.
Return type:None
set_width(width)[source]

Change the width of this space widget.

Parameters:width (int) – The new width.
Return type:None
class nltk.draw.util.StackWidget(canvas, *children, **attribs)[source]

Bases: nltk.draw.util.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.
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 be index; and the index of any children whose indices were greater than equal to index before child was inserted will be incremented by one.
remove_child(child)[source]

Remove the given child canvas widget. child’s parent will be set ot None.

Parameters:child (CanvasWidget) – The child canvas widget to remove.
replace_child(oldchild, newchild)[source]

Replace the child canvas widget oldchild with newchild. 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(canvas, symbol, **attribs)[source]

Bases: nltk.draw.util.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': 'È'}
set_symbol(symbol)[source]

Change the symbol that is displayed by this symbol widget.

Parameters:symbol (str) – The name of the symbol to display.
symbol()[source]
Returns:the name of the symbol that is displayed by this symbol widget.
Return type:str
static symbolsheet(size=20)[source]

Open a new Tkinter window that displays the entire alphabet for the symbol font. This is useful for constructing the SymbolWidget.SYMBOLS dictionary.

class nltk.draw.util.TextWidget(canvas, text, **attribs)[source]

Bases: nltk.draw.util.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 are left, center, and right.
  • 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.
set_text(text)[source]

Change the text that is displayed by this text widget.

Parameters:text (str) – The string of text to display.
Return type:None
text()[source]
Returns:The text displayed by this text widget.
Return type:str
nltk.draw.util.demo()[source]

A simple demonstration showing how to use canvas widgets.

Module contents

nltk.draw.setup_module(module)[source]