paramtk

Module

Classes linking Parameters to Tkinter.

TkParameterized allows flexible graphical representation and manipulation of the parameters of a Parameterized instance or class.

ParametersFrame and ParametersFrameWithApply extend TkParameterized, displaying all the Parameters together in a list. Both allow these Parameters to be edited; ParametersFrame applies changes immediately as they are made, whereas ParametersFrameWithApply makes no changes until a confirmation is given (by pressing the ‘Apply’ button).

Using these classes to display parameters has several benefits, including that, automatically:

  • changes to the Parameters in the GUI are reflected in the objects themselves without any additional code;
  • each Parameter is represented by an appropriate widget (e.g. slider for a Number);
  • type and range checking is handled (by virtue of using parameters);
  • doc strings are displayed as pop-up help for each parameter;
  • parameter names are formatted nicely for display;
  • changes to parameter values in the GUI can be associated with function calls.

Examples

  1. Display the parameters of an object inside an existing window

You want to display all parameters of a parameterized instance inside an existing container (e.g. a window or a frame):

# existing Parameterized instance g from topo import pattern g = pattern.Gaussian()

# existing window t import Tkinter t = Tkinter.Toplevel()

# display all the parameters of g in t from topo.param.tk import ParametersFrame ParametersFrame(t,g) #should be ParametersFrame(t,g).pack(); see ALERT in ParametersFrame

  1. Display the parameters of an object in a standalone window

You want a new window displaying only the parameters of your object:

# existing Parameterized instance g from topo import pattern g = pattern.Gaussian()

# display all the parameters of g in a new window from topo.param.tk import edit_parameters edit_parameters(g)

  1. Flexible GUI layout using TkParameterized

You want to display only some of the parameters of one or more Parameterized instances:

## Existing, non-GUI code from topo import param

class Object1(param.Parameterized):
duration = param.Number(2.0,bounds=(0,None),doc=’Duration of measurement’) displacement = param.Number(0.0,bounds=(-1,1),doc=’Displacement from point A’)
class Object2(param.Parameterized):
active_today = param.Boolean(True,doc=’Whether or not to count today’) operator_name = param.String(‘A. Person’,doc=’Operator today’)

o1 = Object1() o2 = Object2()

## Existing window import Tkinter t = Tkinter.Toplevel()

## Flexible GUI representation: display o1.duration, o1.displacement, ## and o2.active_today inside t, ignoring o2.operator_name from topo.param.tk import TkParameterized

t1 = TkParameterized(t,o1) t2 = TkParameterized(t,o2)

t1.pack_param(‘duration’,side=’left’) t1.pack_param(‘displacement’,side=’bottom’) t2.pack_param(‘active_today’,side=’right’)

  1. ?

TkParameterized is itself a subclass of Parameterized, so a TkParameterized class can have its own parameters (in addition to representing those of an external parameterized instance or class).

## Existing class from topo import params

class X(param.Parameterized):
one = param.Boolean(True) two = param.Boolean(True)

## Panel to represent an instance of X from Tkinter import Frame from topo.param.tk import TkParameterized

class XPanel(TkParameterized,Frame):

dock = param.Boolean(False,doc=’Whether to attach this Panel’)

def __init__(self,master,x):
self.pack_param(‘dock’,side=’top’,on_set=self.handle_dock) self.pack_param(‘one’,side=’left’) self.pack_param(‘two’,side=’right’)
def handle_dock(self):
if self.dock:
# dock the window
else:
# undock the window

## Running the code t = Tkinter.Toplevel() x = X() XPanel(t,x)

class paramtk.AppWindow(parent, status=False, **config)[source]

Bases: paramtk.ScrolledWindow

A ScrolledWindow with extra features intended to be common to all windows of an application.

Currently this only includes a window icon, but we intend to add a right-click menu and possibly more.

paramtk.Button[source]

A GUI-specific parameter to display a button.

Can be associated with an image by specifying an image_path (i.e. location of an image suitable for PIL, e.g. a PNG, TIFF, or JPEG image) and optionally a size (width,height) tuple.

Note that the button size can also be set when there is no image, but instead of being presumed to be in pixels, it is presumed to be in text units (a Tkinter feature: see e.g. http://effbot.org/tkinterbook/button.htm). Therefore, to place two identically sized buttons next to each other, with one displaying text and the other an image, you first have to convert one of the sizes to the other’s units.

class paramtk.DoNothingTranslator(param, initial_value=None)[source]

Bases: paramtk.Translator

Performs no translation. For use with Parameter types such as Boolean and String, where the representation of the object in the GUI is the object itself.

class paramtk.Eval_ReprTranslator(param, initial_value=None)[source]

Bases: paramtk.Translator

Translates a string to an object by eval()ing the string in __main__.__dict__ (i.e. as if the string were typed at the commandline), and translates an object to a string by repr(object).

class paramtk.FocusTakingButton(master=None, cnf={}, **kw)[source]

Bases: Tkinter.Button

A Tkinter Button that takes the focus when the mouse <Enter>s.

(Tkinter.Button doesn’t get focus even when it’s clicked, and only <Enter> and <Leave> events work for buttons.)

class paramtk.Menu(master=None, cnf={}, **kw)[source]

Bases: Tkinter.Menu

Tkinter Menu, but with a way to access entries by name.

Entries can be accessed via the label supplied when the entry is add()ed or insert()ed. For an entry whose label could change, you can supply ‘indexname’, which can then be used to access the entry no matter what the label might have become.

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

See Tkinter.Menu.add(), but ‘indexname’ can also be supplied.

If supplied, indexname must be unique. If label is supplied without indexname, then label must be unique.

delete(index1, index2=None)[source]

If index2 is not specified, deletes the menu item at index1 (an indexname or tk integer index).

If index2 is specified, deletes menu items in range(index1,index2+1).

entryconfig(index, cnf=None, **kw)

Configure a menu item at INDEX.

entryconfigure(index, cnf=None, **kw)[source]

Configure a menu item at INDEX.

get_indexname(index)[source]

Return the indexname, whether given an indexname or index (where index could be an int or Tkinter position e.g. ‘end’).

The returned value will be None if index refers to an unnamed entry.

get_tkinter_index(index)[source]

Return the Tkinter index, whether given an indexname or index (where index could be an int or Tkinter position e.g. ‘end’).

insert(index, itemType, cnf={}, **kw)[source]

See Tkinter.Menu.insert(), but index can also be specified as text.

invoke(index)[source]

Invoke a menu item identified by INDEX and execute the associated command.

class paramtk.ParametersFrame(master, parameterized_object=None, on_set=None, on_modify=None, msg_handler=None, on_close=None, **params)[source]

Bases: paramtk.TkParameterized, Tkinter.Frame

Displays and allows instantaneous editing of the Parameters of a supplied Parameterized.

Changes made to Parameter representations on the GUI are immediately applied to the underlying object.

param Boolean show_labels (allow_None=False, bounds=(0, 1), constant=False, default=True, instantiate=False, pickle_default_value=True, precedence=None, readonly=False)

param Number display_threshold (allow_None=False, bounds=None, constant=False, default=0, inclusive_bounds=(True, True), instantiate=False, pickle_default_value=True, precedence=-10, readonly=False, time_dependent=False, time_fn=<Time Time00001>)
Parameters with precedence below this value are not displayed.
param Button Refresh (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Return values to those currently set on the object (or, if editing a class, to those currently set on the class).
param Button Defaults (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Return values to class defaults.
param Button Close (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Close the window. (If applicable, asks if unsaved changes should be saved).
param Boolean pretty_parameters (allow_None=False, bounds=(0, 1), constant=False, default=True, instantiate=False, pickle_default_value=True, precedence=-1, readonly=False)
Whether to format parameter names, or display the variable names instead. Example use: TkParameterized.pretty_parameters=False (This causes all Parameters throughout the GUI to be displayed with variable names.)
hidden_param(name)[source]

Return True if a parameter’s precedence is below the display threshold.

class paramtk.ParametersFrameWithApply(master, parameterized_object=None, on_set=None, on_modify=None, **params)[source]

Bases: paramtk.ParametersFrame

Displays and allows editing of the Parameters of a supplied Parameterized.

Changes made to Parameter representations in the GUI are not applied to the underlying object until Apply is pressed.

param Boolean show_labels (allow_None=False, bounds=(0, 1), constant=False, default=True, instantiate=False, pickle_default_value=True, precedence=None, readonly=False)

param Number display_threshold (allow_None=False, bounds=None, constant=False, default=0, inclusive_bounds=(True, True), instantiate=False, pickle_default_value=True, precedence=-10, readonly=False, time_dependent=False, time_fn=<Time Time00001>)
Parameters with precedence below this value are not displayed.
param Button Refresh (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Return values to those currently set on the object (or, if editing a class, to those currently set on the class).
param Button Defaults (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Return values to class defaults.
param Button Apply (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Set object’s Parameters to displayed values. When editing a class, sets the class defaults (i.e. acts on the class object).
param Button Close (constant=False, default=None, image_path=None, instantiate=False, pickle_default_value=True, precedence=None, readonly=False, size=None)
Close the window. (If applicable, asks if unsaved changes should be saved).
param Boolean pretty_parameters (allow_None=False, bounds=(0, 1), constant=False, default=True, instantiate=False, pickle_default_value=True, precedence=-1, readonly=False)
Whether to format parameter names, or display the variable names instead. Example use: TkParameterized.pretty_parameters=False (This causes all Parameters throughout the GUI to be displayed with variable names.)
has_unapplied_change()[source]

Return True if any one of the packed parameters’ displayed values is different from that on the object.

class paramtk.ProgressWindow(parent, sim=None, timer=None, progress_var=None, title=None, status=None, unpack_master_when_done=True)[source]

Bases: paramtk.ProgressController, Tkinter.Frame

Graphically displays progress information for a SomeTimer object.

** Currently expects a 0-100 (percent) value ***

class paramtk.ScrolledFrame(parent, **config)[source]

Bases: Tkinter.Frame

XXXX

Content to be scrolled should go in the ‘content’ frame.

class paramtk.TaggedSlider(master, variable, bounds=(0, 1), inclusive_bounds=(True, True), slider_length=100, tag_width=10, tag_extra_config={}, slider_extra_config={})[source]

Bases: Tkinter.Frame

Widget for manipulating a numeric value using either a slider or a text-entry box, keeping the two values in sync.

Generates a number of Events:

<<TagFocusOut>> - tag loses focus <<TagReturn>> - Return pressed in tag <<SliderSet>> - slider is clicked/dragged

config(**options)[source]

TaggedSlider is a compound widget. In most cases, config options should be passed to one of the component widgets (i.e. the tag or the slider). For some options, however, we need to handle them being set on the widget as a whole; further, some of these should be applied to both component widgets, but some should just be applied to one.

Options handled: * state (applied to both) * background, foreground (applied to tag only)

get()[source]

Calls the tag’s get() method.

Helps to match behavior of other Tkinter Widgets.

set_bounds(lower, upper, inclusive_bounds=None)

Set new lower and upper bounds for the slider.

If specified, inclusive_bounds should be a sequence of length 2 specifying True or False for the lower and upper bounds.

set_slider_bounds(lower, upper, inclusive_bounds=None)[source]

Set new lower and upper bounds for the slider.

If specified, inclusive_bounds should be a sequence of length 2 specifying True or False for the lower and upper bounds.

tag_set()[source]

After entering a value into the tag, this method should be called to set the slider correctly.

(Called automatically for tag’s <Return> and <FocusOut> events.)

class paramtk.TkParameterized(master, extraPO=None, self_first=True, msg_handler=None, **params)[source]

Bases: paramtk.TkParameterizedBase

Provide widgets for Parameters of itself and up to one additional Parameterized instance or class.

A subclass that defines a Parameter p can display it appropriately for manipulation by the user simply by calling pack_param(‘p’). The GUI display and the actual Parameter value are automatically synchronized (though see technical notes in TkParameterizedBase’s documentation for more details).

In general, pack_param() adds a Tkinter.Frame containing a label and a widget:

——————— The Parameter’s | | ‘representation’ | [label] [widget] |<—-frame | | ———————

In the same way, an instance of this class can be used to display the Parameters of an existing object. By passing in extraPO=x, where x is an existing Parameterized instance or class, a Parameter q of x can also be displayed in the GUI by calling pack_param(‘q’).

For representation in the GUI, Parameter values might need to be converted between their real values and strings used for display (e.g. for a ClassSelector, the options are really class objects, but the user is presented with a list of strings to choose from). Such translation is handled and documented in the TkParameterizedBase; the default behaviors can be overridden if required.

(Note that this class simply adds widget drawing to TkParameterizedBase. More detail about the shadowing of Parameters is available in the documentation for TkParameterizedBase.)

param Boolean pretty_parameters (allow_None=False, bounds=(0, 1), constant=False, default=True, instantiate=False, pickle_default_value=True, precedence=-1, readonly=False)
Whether to format parameter names, or display the variable names instead. Example use: TkParameterized.pretty_parameters=False (This causes all Parameters throughout the GUI to be displayed with variable names.)
gui_get_param(param_name)[source]

Simulate getting the parameter in the GUI.

gui_set_param(param_name, val)[source]

Simulate setting the parameter in the GUI.

hide_param(name)[source]

Hide the representation of Parameter ‘name’.

pack_param(name, parent=None, widget_options={}, on_set=None, on_modify=None, **pack_options)[source]

Create a widget for the Parameter name, configured according to widget_options, and pack()ed according to the pack_options.

Pop-up help is automatically set from the Parameter’s doc.

The widget and label (if appropriate) are enlosed in a Frame so they can be manipulated as a single unit (see the class docstring). The representation (frame,widget,label,pack_options) is returned (as well as being stored in the representations dictionary).

  • parent is an existing widget that is to be the parent

(master) of the widget created for this paramter. If no parent is specified, defaults to the originally supplied master (i.e. that set during __init__).

  • on_set is an optional function to call whenever the

Parameter’s corresponding Tkinter Variable’s trace_variable indicates that it has been set (this does not necessarily mean that the widget’s value has changed). When the widget is created, the on_set method will be called (because the creation of the widget triggers a set in Tkinter).

  • on_modify is an optional function to call whenever the

corresponding Tkinter Variable is actually changed.

widget_options specified here override anything that might have been set elsewhere (e.g. Button’s size can be overridden here if required).

Examples of use: pack_param(name) pack_param(name,side=’left’) pack_param(name,parent=frame3,on_set=some_func) pack_param(name,widget_options={‘width’:50},side=’top’,expand=’yes’,fill=’y’)

unhide_param(name, new_pack_options={})[source]

Un-hide the representation of Parameter ‘name’.

Any new pack options supplied overwrite the originally supplied ones, but the parent of the widget remains the same.

unpack_param(name)[source]

Destroy the representation of Parameter ‘name’.

(unpack and then pack a param if you want to put it in a different frame; otherwise simply use hide and unhide)

class paramtk.TkParameterizedBase(extraPO=None, self_first=True, live_update=True, **params)[source]

Bases: param.parameterized.Parameterized

A Parameterized subclass that maintains Tkinter.Variable shadows (proxies) of its Parameters. The Tkinter Variable shadows are kept in sync with the Parameter values, and vice versa.

Optionally performs the same for an additional shadowed Parameterized (extraPO). The Parameters of the extra shadowed PO are available via this object (via both the usual ‘dot’ attribute access and dedicated parameter accessors declared in this class).

The Tkinter.Variable shadows for this Parameterized and any extra shadowed one are available under their corresponding parameter names in the _tkvars dictionary.

(See note 1 for complications arising from name clashes.)

Parameters being represented by TkParameterizedBase also have a ‘translators’ dictionary, allowing mapping between string representations of the objects and the objects themselves (for use with e.g. a Tkinter.OptionMenu). More information about the translators is available from specific translator-related methods in this class.

  1. (a) There is an order of precedance for parameter lookup: this PO > shadowed PO.

    Therefore, if you create a Parameter for this PO with the same name as one of the shadowed PO’s Parameters, only the Parameter on this PO will be shadowed.

    Example: ‘name’ is a common attribute. As a Parameterized, this object has a ‘name’ Parameter. Any shadowed PO will also have a ‘name’ Parameter. By default, this object’s name will be shadowed at the expense of the name of the extra shadowed PO.

    The precedence order can be reversed by setting the attribute ‘self_first’ on this object to False.

    (b) Along the same lines, an additional complication can arise relating specifically to ‘dot’ attribute lookup. For instance, a sublass of TkParameterized might also inherit from Tkinter.Frame. Frame has many of its own attributes, including - for example - ‘size’. If we shadow a Parameterized that has a ‘size’ Parameter, the Parameterized’s size Parameter will not be available as .size because (‘dot’) attribute lookup begins on the local object and is not overridden by ‘self_first’. Using the parameter accessors .get_parameter_object(‘size’) or .get_parameter_value(‘size’) (and the equivalent set versions) avoids this problem.

  2. If a shadowed PO’s Parameter value is modified elsewhere, the Tkinter Variable shadow is NOT updated until that Parameter value or shadow value is requested from this object. Thus requesting the value will always return an up-to-date result, but any GUI display of the Variable might display a stale value (until a GUI refresh takes place).

change_PO(extraPO)[source]

Shadow the Parameters of extraPO.

get_parameter_object(name, parameterized_object=None, with_source=False)[source]

Return the Parameter object (not value) specified by name, from the source_POs in this object (or the specified parameterized_object).

If with_source=True, returns also the source parameterizedobject.

get_parameter_value(name, parameterized_object=None)[source]

Return the value of the parameter specified by name.

If a parameterized_object is specified, looks for the parameter there. Otherwise, looks in the source_POs of this object.

get_source_po(name)[source]

Return the Parameterized which contains the parameter ‘name’.

set_parameter_value(name, val, parameterized_object=None)[source]

Set the value of the parameter specified by name to val.

Updates the corresponding tkvar.

class paramtk.ToolTip(wdgt, msg=None, msgFunc=None, delay=1, follow=True)[source]

Bases: Tkinter.Toplevel

Provides a ToolTip widget for Tkinter. To apply a ToolTip to any Tkinter widget, simply pass the widget to the ToolTip constructor

hide(event=None)[source]

Hides the ToolTip. Usually this is caused by leaving the widget

Arguments:
event: The event that called this function
move(event)[source]

Processes motion within the widget.

Arguments:
event: The event that called this function
show()[source]

Displays the ToolTip if the time delay has been long enough

spawn(event=None)[source]

Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget

Arguments:
event: The event that called this funciton
class paramtk.Translator(param, initial_value=None)[source]

Bases: object

Abstract class that

Translators handle translation between objects and their string representations in the GUI.

last_string2object_failed is a flag that can be set to indicate that the last string-to-object translation failed. (TkParameterized checks this attribute for indicating errors to the user.)
paramtk.askyesno(title=None, message=None, **options)[source]

Ask a question; return true if the answer is yes

paramtk.edit_parameters(parameterized, with_apply=True, **params)[source]

Edit the Parameters of a supplied parameterized instance or class.

Specify with_apply=False for a ParametersFrame (which immediately updates the object - no need to press the Apply button).

Extra params are passed to the ParametersFrame constructor.

paramtk.initialize()[source]

Add extension Tcl/Tk code to the Tk instance at Tkinter._default_root (creating the Tk instance first if necessary).

paramtk.inverse(dict_)[source]

Return the inverse of dictionary dict_.

(I.e. return a dictionary with keys that are the values of dict_, and values that are the corresponding keys from dict_.)

The values of dict_ must be unique.

paramtk.is_button(widget)[source]

Simple detection of Button-like widgets that are not Checkbuttons (i.e. widgets that do not require a separate label).

paramtk.keys_sorted_by_value(d)[source]

Return the keys of dictionary d sorted by value.

paramtk.keys_sorted_by_value_unique(d, **sort_kwargs)[source]

Return the keys of d, sorted by value.

The values of d must be unique (see inverse)

paramtk.keys_sorted_by_value_unique_None_safe(d, **sort_kwargs)[source]

None is handled separately: if present, it always comes out at the end of the list. Allows callers to use any sort function without worrying that None will not match the other objects (e.g. for using an attribute present on all the other objects, such as precedence of sheets).

paramtk.lookup_by_class(dict_, class_)[source]

Look for class_ or its superclasses in the keys of dict_; on finding a match, return the value (return None if no match found).

Searches from the most immediate class to the most distant (i.e. from class_ to the final superclass of class_).