Chimera extensions typically can be divided into two parts: data manipulation and user interface. For example, the code in Toolbar Buttons defines a function which changes the display status of some atoms (the data manipulation code) and then creates a toolbar button that invokes the function when pressed (the user interface code). The data manipulation code often may be reused when building a new extension, but the user interface code typically is not needed. Separating the parts into multiple source files simplifies reusing the data manipulation code, but complicates managing the extension code as a unit. Fortunately, Python supports the package concept for just such a situation.
A Python package consists of a set of modules (.py files) stored in the same directory in the file system. One of the modules must be named __init__.py, which is the initialization module that is automatically executed when the package is imported. By convention, Chimera extension packages implement the data manipulation code in __init__.py and the user interface code in a module named gui.py. Implementors of new functionality can access the data manipulation code by:
import extension
and end users can display the user interface by:
import extension.gui
where extension
is the name of the package. The code in
Toolbar Buttons is divided in such a
manner below:
The contents of ToolbarButtonPackage/__init__.py is
identical to the first section of code in Toolbar Buttons,
with the exception that module
The contents of ToolbarButtonPackage/gui.py is similar to
the last section of code in Toolbar Buttons, with the
exception that the The example code files must be saved in a directory named The effect should be identical to running the Toolbar
Buttons example.os
is not imported.
import re
import chimera
def mainchain():
for m in chimera.openModels.list(modelTypes=[chimera.Molecule]):
Example ToolbarButtonPackage/gui.py
mainchain
function is now referenced as
ToolbarButtonPackage.mainchain
. The reason for the change is
that gui.py
is a submodule, while the mainchain
function is in
the main package. Since a submodule cannot directly access items
defined in the main package, gui.py
must first import the package
import ToolbarButtonPackage
and refer to the function by prepending
the package name (ToolbarButtonPackage.mainchain
in the call to
chimera.tkgui.app.toolbar.add
).
import os
import chimera
import ToolbarButtonPackage
dir, file = os.path.split(__file__)
icon = os.path.join(dir, 'ToolbarButton.tiff')
chimera.tkgui.app.toolbar.add(icon, ToolbarButtonPackage.mainchain, 'Show Main Chain', None)
Running the Example
ToolbarButtonPackage
.
To run the example, start chimera in the directory above the package
directory and type the following command into the IDLE command line:
import ToolbarButtonPackage.gui