home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / Tkinter.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  203.0 KB  |  4,124 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Wrapper functions for Tcl/Tk.
  5.  
  6. Tkinter provides classes which allow the display, positioning and
  7. control of widgets. Toplevel widgets are Tk and Toplevel. Other
  8. widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
  9. Checkbutton, Scale, Listbox, Scrollbar, OptionMenu. Properties of the
  10. widgets are specified with keyword arguments.  Keyword arguments have
  11. the same name as the corresponding resource under Tk.
  12.  
  13. Widgets are positioned with one of the geometry managers Place, Pack
  14. or Grid. These managers can be called with methods place, pack, grid
  15. available in every Widget.
  16.  
  17. Actions are bound to events by resources (e.g. keyword argument
  18. command) or with the method bind.
  19.  
  20. Example (Hello, World):
  21. import Tkinter
  22. from Tkconstants import *
  23. tk = Tkinter.Tk()
  24. frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
  25. frame.pack(fill=BOTH,expand=1)
  26. label = Tkinter.Label(frame, text="Hello, World")
  27. label.pack(fill=X, expand=1)
  28. button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
  29. button.pack(side=BOTTOM)
  30. tk.mainloop()
  31. '''
  32. __version__ = '$Revision: 1.160 $'
  33. import sys
  34. if sys.platform == 'win32':
  35.     import FixTk
  36.  
  37. import _tkinter
  38. tkinter = _tkinter
  39. TclError = _tkinter.TclError
  40. from types import *
  41. from Tkconstants import *
  42.  
  43. try:
  44.     import MacOS
  45.     _MacOS = MacOS
  46.     del MacOS
  47. except ImportError:
  48.     _MacOS = None
  49.  
  50. TkVersion = float(_tkinter.TK_VERSION)
  51. TclVersion = float(_tkinter.TCL_VERSION)
  52. READABLE = _tkinter.READABLE
  53. WRITABLE = _tkinter.WRITABLE
  54. EXCEPTION = _tkinter.EXCEPTION
  55.  
  56. try:
  57.     _tkinter.createfilehandler
  58. except AttributeError:
  59.     _tkinter.createfilehandler = None
  60.  
  61.  
  62. try:
  63.     _tkinter.deletefilehandler
  64. except AttributeError:
  65.     _tkinter.deletefilehandler = None
  66.  
  67.  
  68. def _flatten(tuple):
  69.     '''Internal function.'''
  70.     res = ()
  71.     for item in tuple:
  72.         if type(item) in (TupleType, ListType):
  73.             res = res + _flatten(item)
  74.         elif item is not None:
  75.             res = res + (item,)
  76.         
  77.     
  78.     return res
  79.  
  80.  
  81. try:
  82.     _flatten = _tkinter._flatten
  83. except AttributeError:
  84.     pass
  85.  
  86.  
  87. def _cnfmerge(cnfs):
  88.     '''Internal function.'''
  89.     if type(cnfs) is DictionaryType:
  90.         return cnfs
  91.     elif type(cnfs) in (NoneType, StringType):
  92.         return cnfs
  93.     else:
  94.         cnf = { }
  95.         for c in _flatten(cnfs):
  96.             
  97.             try:
  98.                 cnf.update(c)
  99.             except (AttributeError, TypeError):
  100.                 msg = None
  101.                 print '_cnfmerge: fallback due to:', msg
  102.                 for k, v in c.items():
  103.                     cnf[k] = v
  104.                 
  105.  
  106.         
  107.         return cnf
  108.  
  109.  
  110. try:
  111.     _cnfmerge = _tkinter._cnfmerge
  112. except AttributeError:
  113.     pass
  114.  
  115.  
  116. class Event:
  117.     '''Container for the properties of an event.
  118.  
  119.     Instances of this type are generated if one of the following events occurs:
  120.  
  121.     KeyPress, KeyRelease - for keyboard events
  122.     ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
  123.     Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
  124.     Colormap, Gravity, Reparent, Property, Destroy, Activate,
  125.     Deactivate - for window events.
  126.  
  127.     If a callback function for one of these events is registered
  128.     using bind, bind_all, bind_class, or tag_bind, the callback is
  129.     called with an Event as first argument. It will have the
  130.     following attributes (in braces are the event types for which
  131.     the attribute is valid):
  132.  
  133.         serial - serial number of event
  134.     num - mouse button pressed (ButtonPress, ButtonRelease)
  135.     focus - whether the window has the focus (Enter, Leave)
  136.     height - height of the exposed window (Configure, Expose)
  137.     width - width of the exposed window (Configure, Expose)
  138.     keycode - keycode of the pressed key (KeyPress, KeyRelease)
  139.     state - state of the event as a number (ButtonPress, ButtonRelease,
  140.                             Enter, KeyPress, KeyRelease,
  141.                             Leave, Motion)
  142.     state - state as a string (Visibility)
  143.     time - when the event occurred
  144.     x - x-position of the mouse
  145.     y - y-position of the mouse
  146.     x_root - x-position of the mouse on the screen
  147.              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  148.     y_root - y-position of the mouse on the screen
  149.              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  150.     char - pressed character (KeyPress, KeyRelease)
  151.     send_event - see X/Windows documentation
  152.     keysym - keysym of the the event as a string (KeyPress, KeyRelease)
  153.     keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
  154.     type - type of the event as a number
  155.     widget - widget in which the event occurred
  156.     delta - delta of wheel movement (MouseWheel)
  157.     '''
  158.     pass
  159.  
  160. _support_default_root = 1
  161. _default_root = None
  162.  
  163. def NoDefaultRoot():
  164.     '''Inhibit setting of default root window.
  165.  
  166.     Call this function to inhibit that the first instance of
  167.     Tk is used for windows without an explicit parent window.
  168.     '''
  169.     global _support_default_root, _default_root, _default_root
  170.     _support_default_root = 0
  171.     _default_root = None
  172.     del _default_root
  173.  
  174.  
  175. def _tkerror(err):
  176.     '''Internal function.'''
  177.     pass
  178.  
  179.  
  180. def _exit(code = '0'):
  181.     '''Internal function. Calling it will throw the exception SystemExit.'''
  182.     raise SystemExit, code
  183.  
  184. _varnum = 0
  185.  
  186. class Variable:
  187.     '''Internal class. Base class to define value holders for e.g. buttons.'''
  188.     _default = ''
  189.     
  190.     def __init__(self, master = None):
  191.         '''Construct a variable with an optional MASTER as master widget.
  192.         The variable is named PY_VAR_number in Tcl.
  193.         '''
  194.         global _varnum
  195.         if not master:
  196.             master = _default_root
  197.         
  198.         self._master = master
  199.         self._tk = master.tk
  200.         self._name = 'PY_VAR' + `_varnum`
  201.         _varnum = _varnum + 1
  202.         self.set(self._default)
  203.  
  204.     
  205.     def __del__(self):
  206.         '''Unset the variable in Tcl.'''
  207.         self._tk.globalunsetvar(self._name)
  208.  
  209.     
  210.     def __str__(self):
  211.         '''Return the name of the variable in Tcl.'''
  212.         return self._name
  213.  
  214.     
  215.     def set(self, value):
  216.         '''Set the variable to VALUE.'''
  217.         return self._tk.globalsetvar(self._name, value)
  218.  
  219.     
  220.     def trace_variable(self, mode, callback):
  221.         '''Define a trace callback for the variable.
  222.  
  223.         MODE is one of "r", "w", "u" for read, write, undefine.
  224.         CALLBACK must be a function which is called when
  225.         the variable is read, written or undefined.
  226.  
  227.         Return the name of the callback.
  228.         '''
  229.         cbname = self._master._register(callback)
  230.         self._tk.call('trace', 'variable', self._name, mode, cbname)
  231.         return cbname
  232.  
  233.     trace = trace_variable
  234.     
  235.     def trace_vdelete(self, mode, cbname):
  236.         '''Delete the trace callback for a variable.
  237.  
  238.         MODE is one of "r", "w", "u" for read, write, undefine.
  239.         CBNAME is the name of the callback returned from trace_variable or trace.
  240.         '''
  241.         self._tk.call('trace', 'vdelete', self._name, mode, cbname)
  242.         self._master.deletecommand(cbname)
  243.  
  244.     
  245.     def trace_vinfo(self):
  246.         '''Return all trace callback information.'''
  247.         return map(self._tk.split, self._tk.splitlist(self._tk.call('trace', 'vinfo', self._name)))
  248.  
  249.  
  250.  
  251. class StringVar(Variable):
  252.     '''Value holder for strings variables.'''
  253.     _default = ''
  254.     
  255.     def __init__(self, master = None):
  256.         '''Construct a string variable.
  257.  
  258.         MASTER can be given as master widget.'''
  259.         Variable.__init__(self, master)
  260.  
  261.     
  262.     def get(self):
  263.         '''Return value of variable as string.'''
  264.         return self._tk.globalgetvar(self._name)
  265.  
  266.  
  267.  
  268. class IntVar(Variable):
  269.     '''Value holder for integer variables.'''
  270.     _default = 0
  271.     
  272.     def __init__(self, master = None):
  273.         '''Construct an integer variable.
  274.  
  275.         MASTER can be given as master widget.'''
  276.         Variable.__init__(self, master)
  277.  
  278.     
  279.     def get(self):
  280.         '''Return the value of the variable as an integer.'''
  281.         return getint(self._tk.globalgetvar(self._name))
  282.  
  283.  
  284.  
  285. class DoubleVar(Variable):
  286.     '''Value holder for float variables.'''
  287.     _default = 0.0
  288.     
  289.     def __init__(self, master = None):
  290.         '''Construct a float variable.
  291.  
  292.         MASTER can be given as a master widget.'''
  293.         Variable.__init__(self, master)
  294.  
  295.     
  296.     def get(self):
  297.         '''Return the value of the variable as a float.'''
  298.         return getdouble(self._tk.globalgetvar(self._name))
  299.  
  300.  
  301.  
  302. class BooleanVar(Variable):
  303.     '''Value holder for boolean variables.'''
  304.     _default = 'false'
  305.     
  306.     def __init__(self, master = None):
  307.         '''Construct a boolean variable.
  308.  
  309.         MASTER can be given as a master widget.'''
  310.         Variable.__init__(self, master)
  311.  
  312.     
  313.     def get(self):
  314.         '''Return the value of the variable as 0 or 1.'''
  315.         return self._tk.getboolean(self._tk.globalgetvar(self._name))
  316.  
  317.  
  318.  
  319. def mainloop(n = 0):
  320.     '''Run the main loop of Tcl.'''
  321.     _default_root.tk.mainloop(n)
  322.  
  323. getint = int
  324. getdouble = float
  325.  
  326. def getboolean(s):
  327.     '''Convert true and false to integer values 1 and 0.'''
  328.     return _default_root.tk.getboolean(s)
  329.  
  330.  
  331. class Misc:
  332.     '''Internal class.
  333.  
  334.     Base class which defines methods common for interior widgets.'''
  335.     _tclCommands = None
  336.     
  337.     def destroy(self):
  338.         '''Internal function.
  339.  
  340.         Delete all Tcl commands created for
  341.         this widget in the Tcl interpreter.'''
  342.         if self._tclCommands is not None:
  343.             for name in self._tclCommands:
  344.                 self.tk.deletecommand(name)
  345.             
  346.             self._tclCommands = None
  347.         
  348.  
  349.     
  350.     def deletecommand(self, name):
  351.         '''Internal function.
  352.  
  353.         Delete the Tcl command provided in NAME.'''
  354.         self.tk.deletecommand(name)
  355.         
  356.         try:
  357.             self._tclCommands.remove(name)
  358.         except ValueError:
  359.             pass
  360.  
  361.  
  362.     
  363.     def tk_strictMotif(self, boolean = None):
  364.         '''Set Tcl internal variable, whether the look and feel
  365.         should adhere to Motif.
  366.  
  367.         A parameter of 1 means adhere to Motif (e.g. no color
  368.         change if mouse passes over slider).
  369.         Returns the set value.'''
  370.         return self.tk.getboolean(self.tk.call('set', 'tk_strictMotif', boolean))
  371.  
  372.     
  373.     def tk_bisque(self):
  374.         '''Change the color scheme to light brown as used in Tk 3.6 and before.'''
  375.         self.tk.call('tk_bisque')
  376.  
  377.     
  378.     def tk_setPalette(self, *args, **kw):
  379.         '''Set a new color scheme for all widget elements.
  380.  
  381.         A single color as argument will cause that all colors of Tk
  382.         widget elements are derived from this.
  383.         Alternatively several keyword parameters and its associated
  384.         colors can be given. The following keywords are valid:
  385.         activeBackground, foreground, selectColor,
  386.         activeForeground, highlightBackground, selectBackground,
  387.         background, highlightColor, selectForeground,
  388.         disabledForeground, insertBackground, troughColor.'''
  389.         self.tk.call(('tk_setPalette',) + _flatten(args) + _flatten(kw.items()))
  390.  
  391.     
  392.     def tk_menuBar(self, *args):
  393.         '''Do not use. Needed in Tk 3.6 and earlier.'''
  394.         pass
  395.  
  396.     
  397.     def wait_variable(self, name = 'PY_VAR'):
  398.         '''Wait until the variable is modified.
  399.  
  400.         A parameter of type IntVar, StringVar, DoubleVar or
  401.         BooleanVar must be given.'''
  402.         self.tk.call('tkwait', 'variable', name)
  403.  
  404.     waitvar = wait_variable
  405.     
  406.     def wait_window(self, window = None):
  407.         '''Wait until a WIDGET is destroyed.
  408.  
  409.         If no parameter is given self is used.'''
  410.         if window is None:
  411.             window = self
  412.         
  413.         self.tk.call('tkwait', 'window', window._w)
  414.  
  415.     
  416.     def wait_visibility(self, window = None):
  417.         '''Wait until the visibility of a WIDGET changes
  418.         (e.g. it appears).
  419.  
  420.         If no parameter is given self is used.'''
  421.         if window is None:
  422.             window = self
  423.         
  424.         self.tk.call('tkwait', 'visibility', window._w)
  425.  
  426.     
  427.     def setvar(self, name = 'PY_VAR', value = '1'):
  428.         '''Set Tcl variable NAME to VALUE.'''
  429.         self.tk.setvar(name, value)
  430.  
  431.     
  432.     def getvar(self, name = 'PY_VAR'):
  433.         '''Return value of Tcl variable NAME.'''
  434.         return self.tk.getvar(name)
  435.  
  436.     getint = int
  437.     getdouble = float
  438.     
  439.     def getboolean(self, s):
  440.         '''Return 0 or 1 for Tcl boolean values true and false given as parameter.'''
  441.         return self.tk.getboolean(s)
  442.  
  443.     
  444.     def focus_set(self):
  445.         '''Direct input focus to this widget.
  446.  
  447.         If the application currently does not have the focus
  448.         this widget will get the focus if the application gets
  449.         the focus through the window manager.'''
  450.         self.tk.call('focus', self._w)
  451.  
  452.     focus = focus_set
  453.     
  454.     def focus_force(self):
  455.         '''Direct input focus to this widget even if the
  456.         application does not have the focus. Use with
  457.         caution!'''
  458.         self.tk.call('focus', '-force', self._w)
  459.  
  460.     
  461.     def focus_get(self):
  462.         '''Return the widget which has currently the focus in the
  463.         application.
  464.  
  465.         Use focus_displayof to allow working with several
  466.         displays. Return None if application does not have
  467.         the focus.'''
  468.         name = self.tk.call('focus')
  469.         if name == 'none' or not name:
  470.             return None
  471.         
  472.         return self._nametowidget(name)
  473.  
  474.     
  475.     def focus_displayof(self):
  476.         '''Return the widget which has currently the focus on the
  477.         display where this widget is located.
  478.  
  479.         Return None if the application does not have the focus.'''
  480.         name = self.tk.call('focus', '-displayof', self._w)
  481.         if name == 'none' or not name:
  482.             return None
  483.         
  484.         return self._nametowidget(name)
  485.  
  486.     
  487.     def focus_lastfor(self):
  488.         '''Return the widget which would have the focus if top level
  489.         for this widget gets the focus from the window manager.'''
  490.         name = self.tk.call('focus', '-lastfor', self._w)
  491.         if name == 'none' or not name:
  492.             return None
  493.         
  494.         return self._nametowidget(name)
  495.  
  496.     
  497.     def tk_focusFollowsMouse(self):
  498.         '''The widget under mouse will get automatically focus. Can not
  499.         be disabled easily.'''
  500.         self.tk.call('tk_focusFollowsMouse')
  501.  
  502.     
  503.     def tk_focusNext(self):
  504.         '''Return the next widget in the focus order which follows
  505.         widget which has currently the focus.
  506.  
  507.         The focus order first goes to the next child, then to
  508.         the children of the child recursively and then to the
  509.         next sibling which is higher in the stacking order.  A
  510.         widget is omitted if it has the takefocus resource set
  511.         to 0.'''
  512.         name = self.tk.call('tk_focusNext', self._w)
  513.         if not name:
  514.             return None
  515.         
  516.         return self._nametowidget(name)
  517.  
  518.     
  519.     def tk_focusPrev(self):
  520.         '''Return previous widget in the focus order. See tk_focusNext for details.'''
  521.         name = self.tk.call('tk_focusPrev', self._w)
  522.         if not name:
  523.             return None
  524.         
  525.         return self._nametowidget(name)
  526.  
  527.     
  528.     def after(self, ms, func = None, *args):
  529.         '''Call function once after given time.
  530.  
  531.         MS specifies the time in milliseconds. FUNC gives the
  532.         function which shall be called. Additional parameters
  533.         are given as parameters to the function call.  Return
  534.         identifier to cancel scheduling with after_cancel.'''
  535.         if not func:
  536.             self.tk.call('after', ms)
  537.         else:
  538.             tmp = []
  539.             
  540.             def callit(func = func, args = args, self = self, tmp = tmp):
  541.                 
  542.                 try:
  543.                     apply(func, args)
  544.                 finally:
  545.                     
  546.                     try:
  547.                         self.deletecommand(tmp[0])
  548.                     except TclError:
  549.                         pass
  550.  
  551.  
  552.  
  553.             name = self._register(callit)
  554.             tmp.append(name)
  555.             return self.tk.call('after', ms, name)
  556.  
  557.     
  558.     def after_idle(self, func, *args):
  559.         '''Call FUNC once if the Tcl main loop has no event to
  560.         process.
  561.  
  562.         Return an identifier to cancel the scheduling with
  563.         after_cancel.'''
  564.         return apply(self.after, ('idle', func) + args)
  565.  
  566.     
  567.     def after_cancel(self, id):
  568.         '''Cancel scheduling of function identified with ID.
  569.  
  570.         Identifier returned by after or after_idle must be
  571.         given as first parameter.'''
  572.         self.tk.call('after', 'cancel', id)
  573.  
  574.     
  575.     def bell(self, displayof = 0):
  576.         """Ring a display's bell."""
  577.         self.tk.call(('bell',) + self._displayof(displayof))
  578.  
  579.     
  580.     def clipboard_clear(self, **kw):
  581.         '''Clear the data in the Tk clipboard.
  582.  
  583.         A widget specified for the optional displayof keyword
  584.         argument specifies the target display.'''
  585.         if not kw.has_key('displayof'):
  586.             kw['displayof'] = self._w
  587.         
  588.         self.tk.call(('clipboard', 'clear') + self._options(kw))
  589.  
  590.     
  591.     def clipboard_append(self, string, **kw):
  592.         '''Append STRING to the Tk clipboard.
  593.  
  594.         A widget specified at the optional displayof keyword
  595.         argument specifies the target display. The clipboard
  596.         can be retrieved with selection_get.'''
  597.         if not kw.has_key('displayof'):
  598.             kw['displayof'] = self._w
  599.         
  600.         self.tk.call(('clipboard', 'append') + self._options(kw) + ('--', string))
  601.  
  602.     
  603.     def grab_current(self):
  604.         '''Return widget which has currently the grab in this application
  605.         or None.'''
  606.         name = self.tk.call('grab', 'current', self._w)
  607.         if not name:
  608.             return None
  609.         
  610.         return self._nametowidget(name)
  611.  
  612.     
  613.     def grab_release(self):
  614.         '''Release grab for this widget if currently set.'''
  615.         self.tk.call('grab', 'release', self._w)
  616.  
  617.     
  618.     def grab_set(self):
  619.         '''Set grab for this widget.
  620.  
  621.         A grab directs all events to this and descendant
  622.         widgets in the application.'''
  623.         self.tk.call('grab', 'set', self._w)
  624.  
  625.     
  626.     def grab_set_global(self):
  627.         '''Set global grab for this widget.
  628.  
  629.         A global grab directs all events to this and
  630.         descendant widgets on the display. Use with caution -
  631.         other applications do not get events anymore.'''
  632.         self.tk.call('grab', 'set', '-global', self._w)
  633.  
  634.     
  635.     def grab_status(self):
  636.         '''Return None, "local" or "global" if this widget has
  637.         no, a local or a global grab.'''
  638.         status = self.tk.call('grab', 'status', self._w)
  639.         if status == 'none':
  640.             status = None
  641.         
  642.         return status
  643.  
  644.     
  645.     def lower(self, belowThis = None):
  646.         '''Lower this widget in the stacking order.'''
  647.         self.tk.call('lower', self._w, belowThis)
  648.  
  649.     
  650.     def option_add(self, pattern, value, priority = None):
  651.         '''Set a VALUE (second parameter) for an option
  652.         PATTERN (first parameter).
  653.  
  654.         An optional third parameter gives the numeric priority
  655.         (defaults to 80).'''
  656.         self.tk.call('option', 'add', pattern, value, priority)
  657.  
  658.     
  659.     def option_clear(self):
  660.         '''Clear the option database.
  661.  
  662.         It will be reloaded if option_add is called.'''
  663.         self.tk.call('option', 'clear')
  664.  
  665.     
  666.     def option_get(self, name, className):
  667.         '''Return the value for an option NAME for this widget
  668.         with CLASSNAME.
  669.  
  670.         Values with higher priority override lower values.'''
  671.         return self.tk.call('option', 'get', self._w, name, className)
  672.  
  673.     
  674.     def option_readfile(self, fileName, priority = None):
  675.         '''Read file FILENAME into the option database.
  676.  
  677.         An optional second parameter gives the numeric
  678.         priority.'''
  679.         self.tk.call('option', 'readfile', fileName, priority)
  680.  
  681.     
  682.     def selection_clear(self, **kw):
  683.         '''Clear the current X selection.'''
  684.         if not kw.has_key('displayof'):
  685.             kw['displayof'] = self._w
  686.         
  687.         self.tk.call(('selection', 'clear') + self._options(kw))
  688.  
  689.     
  690.     def selection_get(self, **kw):
  691.         '''Return the contents of the current X selection.
  692.  
  693.         A keyword parameter selection specifies the name of
  694.         the selection and defaults to PRIMARY.  A keyword
  695.         parameter displayof specifies a widget on the display
  696.         to use.'''
  697.         if not kw.has_key('displayof'):
  698.             kw['displayof'] = self._w
  699.         
  700.         return self.tk.call(('selection', 'get') + self._options(kw))
  701.  
  702.     
  703.     def selection_handle(self, command, **kw):
  704.         '''Specify a function COMMAND to call if the X
  705.         selection owned by this widget is queried by another
  706.         application.
  707.  
  708.         This function must return the contents of the
  709.         selection. The function will be called with the
  710.         arguments OFFSET and LENGTH which allows the chunking
  711.         of very long selections. The following keyword
  712.         parameters can be provided:
  713.         selection - name of the selection (default PRIMARY),
  714.         type - type of the selection (e.g. STRING, FILE_NAME).'''
  715.         name = self._register(command)
  716.         self.tk.call(('selection', 'handle') + self._options(kw) + (self._w, name))
  717.  
  718.     
  719.     def selection_own(self, **kw):
  720.         '''Become owner of X selection.
  721.  
  722.         A keyword parameter selection specifies the name of
  723.         the selection (default PRIMARY).'''
  724.         self.tk.call(('selection', 'own') + self._options(kw) + (self._w,))
  725.  
  726.     
  727.     def selection_own_get(self, **kw):
  728.         '''Return owner of X selection.
  729.  
  730.         The following keyword parameter can
  731.         be provided:
  732.         selection - name of the selection (default PRIMARY),
  733.         type - type of the selection (e.g. STRING, FILE_NAME).'''
  734.         if not kw.has_key('displayof'):
  735.             kw['displayof'] = self._w
  736.         
  737.         name = self.tk.call(('selection', 'own') + self._options(kw))
  738.         if not name:
  739.             return None
  740.         
  741.         return self._nametowidget(name)
  742.  
  743.     
  744.     def send(self, interp, cmd, *args):
  745.         '''Send Tcl command CMD to different interpreter INTERP to be executed.'''
  746.         return self.tk.call(('send', interp, cmd) + args)
  747.  
  748.     
  749.     def lower(self, belowThis = None):
  750.         '''Lower this widget in the stacking order.'''
  751.         self.tk.call('lower', self._w, belowThis)
  752.  
  753.     
  754.     def tkraise(self, aboveThis = None):
  755.         '''Raise this widget in the stacking order.'''
  756.         self.tk.call('raise', self._w, aboveThis)
  757.  
  758.     lift = tkraise
  759.     
  760.     def colormodel(self, value = None):
  761.         '''Useless. Not implemented in Tk.'''
  762.         return self.tk.call('tk', 'colormodel', self._w, value)
  763.  
  764.     
  765.     def winfo_atom(self, name, displayof = 0):
  766.         '''Return integer which represents atom NAME.'''
  767.         args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  768.         return getint(self.tk.call(args))
  769.  
  770.     
  771.     def winfo_atomname(self, id, displayof = 0):
  772.         '''Return name of atom with identifier ID.'''
  773.         args = ('winfo', 'atomname') + self._displayof(displayof) + (id,)
  774.         return self.tk.call(args)
  775.  
  776.     
  777.     def winfo_cells(self):
  778.         '''Return number of cells in the colormap for this widget.'''
  779.         return getint(self.tk.call('winfo', 'cells', self._w))
  780.  
  781.     
  782.     def winfo_children(self):
  783.         '''Return a list of all widgets which are children of this widget.'''
  784.         return map(self._nametowidget, self.tk.splitlist(self.tk.call('winfo', 'children', self._w)))
  785.  
  786.     
  787.     def winfo_class(self):
  788.         '''Return window class name of this widget.'''
  789.         return self.tk.call('winfo', 'class', self._w)
  790.  
  791.     
  792.     def winfo_colormapfull(self):
  793.         '''Return true if at the last color request the colormap was full.'''
  794.         return self.tk.getboolean(self.tk.call('winfo', 'colormapfull', self._w))
  795.  
  796.     
  797.     def winfo_containing(self, rootX, rootY, displayof = 0):
  798.         '''Return the widget which is at the root coordinates ROOTX, ROOTY.'''
  799.         args = ('winfo', 'containing') + self._displayof(displayof) + (rootX, rootY)
  800.         name = self.tk.call(args)
  801.         if not name:
  802.             return None
  803.         
  804.         return self._nametowidget(name)
  805.  
  806.     
  807.     def winfo_depth(self):
  808.         '''Return the number of bits per pixel.'''
  809.         return getint(self.tk.call('winfo', 'depth', self._w))
  810.  
  811.     
  812.     def winfo_exists(self):
  813.         '''Return true if this widget exists.'''
  814.         return getint(self.tk.call('winfo', 'exists', self._w))
  815.  
  816.     
  817.     def winfo_fpixels(self, number):
  818.         '''Return the number of pixels for the given distance NUMBER
  819.         (e.g. "3c") as float.'''
  820.         return getdouble(self.tk.call('winfo', 'fpixels', self._w, number))
  821.  
  822.     
  823.     def winfo_geometry(self):
  824.         '''Return geometry string for this widget in the form "widthxheight+X+Y".'''
  825.         return self.tk.call('winfo', 'geometry', self._w)
  826.  
  827.     
  828.     def winfo_height(self):
  829.         '''Return height of this widget.'''
  830.         return getint(self.tk.call('winfo', 'height', self._w))
  831.  
  832.     
  833.     def winfo_id(self):
  834.         '''Return identifier ID for this widget.'''
  835.         return self.tk.getint(self.tk.call('winfo', 'id', self._w))
  836.  
  837.     
  838.     def winfo_interps(self, displayof = 0):
  839.         '''Return the name of all Tcl interpreters for this display.'''
  840.         args = ('winfo', 'interps') + self._displayof(displayof)
  841.         return self.tk.splitlist(self.tk.call(args))
  842.  
  843.     
  844.     def winfo_ismapped(self):
  845.         '''Return true if this widget is mapped.'''
  846.         return getint(self.tk.call('winfo', 'ismapped', self._w))
  847.  
  848.     
  849.     def winfo_manager(self):
  850.         '''Return the window mananger name for this widget.'''
  851.         return self.tk.call('winfo', 'manager', self._w)
  852.  
  853.     
  854.     def winfo_name(self):
  855.         '''Return the name of this widget.'''
  856.         return self.tk.call('winfo', 'name', self._w)
  857.  
  858.     
  859.     def winfo_parent(self):
  860.         '''Return the name of the parent of this widget.'''
  861.         return self.tk.call('winfo', 'parent', self._w)
  862.  
  863.     
  864.     def winfo_pathname(self, id, displayof = 0):
  865.         '''Return the pathname of the widget given by ID.'''
  866.         args = ('winfo', 'pathname') + self._displayof(displayof) + (id,)
  867.         return self.tk.call(args)
  868.  
  869.     
  870.     def winfo_pixels(self, number):
  871.         '''Rounded integer value of winfo_fpixels.'''
  872.         return getint(self.tk.call('winfo', 'pixels', self._w, number))
  873.  
  874.     
  875.     def winfo_pointerx(self):
  876.         '''Return the x coordinate of the pointer on the root window.'''
  877.         return getint(self.tk.call('winfo', 'pointerx', self._w))
  878.  
  879.     
  880.     def winfo_pointerxy(self):
  881.         '''Return a tuple of x and y coordinates of the pointer on the root window.'''
  882.         return self._getints(self.tk.call('winfo', 'pointerxy', self._w))
  883.  
  884.     
  885.     def winfo_pointery(self):
  886.         '''Return the y coordinate of the pointer on the root window.'''
  887.         return getint(self.tk.call('winfo', 'pointery', self._w))
  888.  
  889.     
  890.     def winfo_reqheight(self):
  891.         '''Return requested height of this widget.'''
  892.         return getint(self.tk.call('winfo', 'reqheight', self._w))
  893.  
  894.     
  895.     def winfo_reqwidth(self):
  896.         '''Return requested width of this widget.'''
  897.         return getint(self.tk.call('winfo', 'reqwidth', self._w))
  898.  
  899.     
  900.     def winfo_rgb(self, color):
  901.         '''Return tuple of decimal values for red, green, blue for
  902.         COLOR in this widget.'''
  903.         return self._getints(self.tk.call('winfo', 'rgb', self._w, color))
  904.  
  905.     
  906.     def winfo_rootx(self):
  907.         '''Return x coordinate of upper left corner of this widget on the
  908.         root window.'''
  909.         return getint(self.tk.call('winfo', 'rootx', self._w))
  910.  
  911.     
  912.     def winfo_rooty(self):
  913.         '''Return y coordinate of upper left corner of this widget on the
  914.         root window.'''
  915.         return getint(self.tk.call('winfo', 'rooty', self._w))
  916.  
  917.     
  918.     def winfo_screen(self):
  919.         '''Return the screen name of this widget.'''
  920.         return self.tk.call('winfo', 'screen', self._w)
  921.  
  922.     
  923.     def winfo_screencells(self):
  924.         '''Return the number of the cells in the colormap of the screen
  925.         of this widget.'''
  926.         return getint(self.tk.call('winfo', 'screencells', self._w))
  927.  
  928.     
  929.     def winfo_screendepth(self):
  930.         '''Return the number of bits per pixel of the root window of the
  931.         screen of this widget.'''
  932.         return getint(self.tk.call('winfo', 'screendepth', self._w))
  933.  
  934.     
  935.     def winfo_screenheight(self):
  936.         '''Return the number of pixels of the height of the screen of this widget
  937.         in pixel.'''
  938.         return getint(self.tk.call('winfo', 'screenheight', self._w))
  939.  
  940.     
  941.     def winfo_screenmmheight(self):
  942.         '''Return the number of pixels of the height of the screen of
  943.         this widget in mm.'''
  944.         return getint(self.tk.call('winfo', 'screenmmheight', self._w))
  945.  
  946.     
  947.     def winfo_screenmmwidth(self):
  948.         '''Return the number of pixels of the width of the screen of
  949.         this widget in mm.'''
  950.         return getint(self.tk.call('winfo', 'screenmmwidth', self._w))
  951.  
  952.     
  953.     def winfo_screenvisual(self):
  954.         '''Return one of the strings directcolor, grayscale, pseudocolor,
  955.         staticcolor, staticgray, or truecolor for the default
  956.         colormodel of this screen.'''
  957.         return self.tk.call('winfo', 'screenvisual', self._w)
  958.  
  959.     
  960.     def winfo_screenwidth(self):
  961.         '''Return the number of pixels of the width of the screen of
  962.         this widget in pixel.'''
  963.         return getint(self.tk.call('winfo', 'screenwidth', self._w))
  964.  
  965.     
  966.     def winfo_server(self):
  967.         '''Return information of the X-Server of the screen of this widget in
  968.         the form "XmajorRminor vendor vendorVersion".'''
  969.         return self.tk.call('winfo', 'server', self._w)
  970.  
  971.     
  972.     def winfo_toplevel(self):
  973.         '''Return the toplevel widget of this widget.'''
  974.         return self._nametowidget(self.tk.call('winfo', 'toplevel', self._w))
  975.  
  976.     
  977.     def winfo_viewable(self):
  978.         '''Return true if the widget and all its higher ancestors are mapped.'''
  979.         return getint(self.tk.call('winfo', 'viewable', self._w))
  980.  
  981.     
  982.     def winfo_visual(self):
  983.         '''Return one of the strings directcolor, grayscale, pseudocolor,
  984.         staticcolor, staticgray, or truecolor for the
  985.         colormodel of this widget.'''
  986.         return self.tk.call('winfo', 'visual', self._w)
  987.  
  988.     
  989.     def winfo_visualid(self):
  990.         '''Return the X identifier for the visual for this widget.'''
  991.         return self.tk.call('winfo', 'visualid', self._w)
  992.  
  993.     
  994.     def winfo_visualsavailable(self, includeids = 0):
  995.         '''Return a list of all visuals available for the screen
  996.         of this widget.
  997.  
  998.         Each item in the list consists of a visual name (see winfo_visual), a
  999.         depth and if INCLUDEIDS=1 is given also the X identifier.'''
  1000.         if not includeids and 'includeids':
  1001.             pass
  1002.         data = self.tk.split(self.tk.call('winfo', 'visualsavailable', self._w, None))
  1003.         if type(data) is StringType:
  1004.             data = [
  1005.                 self.tk.split(data)]
  1006.         
  1007.         return map(self._Misc__winfo_parseitem, data)
  1008.  
  1009.     
  1010.     def __winfo_parseitem(self, t):
  1011.         '''Internal function.'''
  1012.         return t[:1] + tuple(map(self._Misc__winfo_getint, t[1:]))
  1013.  
  1014.     
  1015.     def __winfo_getint(self, x):
  1016.         '''Internal function.'''
  1017.         return int(x, 0)
  1018.  
  1019.     
  1020.     def winfo_vrootheight(self):
  1021.         '''Return the height of the virtual root window associated with this
  1022.         widget in pixels. If there is no virtual root window return the
  1023.         height of the screen.'''
  1024.         return getint(self.tk.call('winfo', 'vrootheight', self._w))
  1025.  
  1026.     
  1027.     def winfo_vrootwidth(self):
  1028.         '''Return the width of the virtual root window associated with this
  1029.         widget in pixel. If there is no virtual root window return the
  1030.         width of the screen.'''
  1031.         return getint(self.tk.call('winfo', 'vrootwidth', self._w))
  1032.  
  1033.     
  1034.     def winfo_vrootx(self):
  1035.         '''Return the x offset of the virtual root relative to the root
  1036.         window of the screen of this widget.'''
  1037.         return getint(self.tk.call('winfo', 'vrootx', self._w))
  1038.  
  1039.     
  1040.     def winfo_vrooty(self):
  1041.         '''Return the y offset of the virtual root relative to the root
  1042.         window of the screen of this widget.'''
  1043.         return getint(self.tk.call('winfo', 'vrooty', self._w))
  1044.  
  1045.     
  1046.     def winfo_width(self):
  1047.         '''Return the width of this widget.'''
  1048.         return getint(self.tk.call('winfo', 'width', self._w))
  1049.  
  1050.     
  1051.     def winfo_x(self):
  1052.         '''Return the x coordinate of the upper left corner of this widget
  1053.         in the parent.'''
  1054.         return getint(self.tk.call('winfo', 'x', self._w))
  1055.  
  1056.     
  1057.     def winfo_y(self):
  1058.         '''Return the y coordinate of the upper left corner of this widget
  1059.         in the parent.'''
  1060.         return getint(self.tk.call('winfo', 'y', self._w))
  1061.  
  1062.     
  1063.     def update(self):
  1064.         '''Enter event loop until all pending events have been processed by Tcl.'''
  1065.         self.tk.call('update')
  1066.  
  1067.     
  1068.     def update_idletasks(self):
  1069.         '''Enter event loop until all idle callbacks have been called. This
  1070.         will update the display of windows but not process events caused by
  1071.         the user.'''
  1072.         self.tk.call('update', 'idletasks')
  1073.  
  1074.     
  1075.     def bindtags(self, tagList = None):
  1076.         '''Set or get the list of bindtags for this widget.
  1077.  
  1078.         With no argument return the list of all bindtags associated with
  1079.         this widget. With a list of strings as argument the bindtags are
  1080.         set to this list. The bindtags determine in which order events are
  1081.         processed (see bind).'''
  1082.         if tagList is None:
  1083.             return self.tk.splitlist(self.tk.call('bindtags', self._w))
  1084.         else:
  1085.             self.tk.call('bindtags', self._w, tagList)
  1086.  
  1087.     
  1088.     def _bind(self, what, sequence, func, add, needcleanup = 1):
  1089.         '''Internal function.'''
  1090.         if type(func) is StringType:
  1091.             self.tk.call(what + (sequence, func))
  1092.         elif func:
  1093.             funcid = self._register(func, self._substitute, needcleanup)
  1094.             if not add and '+':
  1095.                 pass
  1096.             cmd = '%sif {"[%s %s]" == "break"} break\n' % ('', funcid, self._subst_format_str)
  1097.             self.tk.call(what + (sequence, cmd))
  1098.             return funcid
  1099.         elif sequence:
  1100.             return self.tk.call(what + (sequence,))
  1101.         else:
  1102.             return self.tk.splitlist(self.tk.call(what))
  1103.  
  1104.     
  1105.     def bind(self, sequence = None, func = None, add = None):
  1106.         '''Bind to this widget at event SEQUENCE a call to function FUNC.
  1107.  
  1108.         SEQUENCE is a string of concatenated event
  1109.         patterns. An event pattern is of the form
  1110.         <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
  1111.         of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
  1112.         Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
  1113.         B3, Alt, Button4, B4, Double, Button5, B5 Triple,
  1114.         Mod1, M1. TYPE is one of Activate, Enter, Map,
  1115.         ButtonPress, Button, Expose, Motion, ButtonRelease
  1116.         FocusIn, MouseWheel, Circulate, FocusOut, Property,
  1117.         Colormap, Gravity Reparent, Configure, KeyPress, Key,
  1118.         Unmap, Deactivate, KeyRelease Visibility, Destroy,
  1119.         Leave and DETAIL is the button number for ButtonPress,
  1120.         ButtonRelease and DETAIL is the Keysym for KeyPress and
  1121.         KeyRelease. Examples are
  1122.         <Control-Button-1> for pressing Control and mouse button 1 or
  1123.         <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
  1124.         An event pattern can also be a virtual event of the form
  1125.         <<AString>> where AString can be arbitrary. This
  1126.         event can be generated by event_generate.
  1127.         If events are concatenated they must appear shortly
  1128.         after each other.
  1129.  
  1130.         FUNC will be called if the event sequence occurs with an
  1131.         instance of Event as argument. If the return value of FUNC is
  1132.         "break" no further bound function is invoked.
  1133.  
  1134.         An additional boolean parameter ADD specifies whether FUNC will
  1135.         be called additionally to the other bound function or whether
  1136.         it will replace the previous function.
  1137.  
  1138.         Bind will return an identifier to allow deletion of the bound function with
  1139.         unbind without memory leak.
  1140.  
  1141.         If FUNC or SEQUENCE is omitted the bound function or list
  1142.         of bound events are returned.'''
  1143.         return self._bind(('bind', self._w), sequence, func, add)
  1144.  
  1145.     
  1146.     def unbind(self, sequence, funcid = None):
  1147.         '''Unbind for this widget for event SEQUENCE  the
  1148.         function identified with FUNCID.'''
  1149.         self.tk.call('bind', self._w, sequence, '')
  1150.         if funcid:
  1151.             self.deletecommand(funcid)
  1152.         
  1153.  
  1154.     
  1155.     def bind_all(self, sequence = None, func = None, add = None):
  1156.         '''Bind to all widgets at an event SEQUENCE a call to function FUNC.
  1157.         An additional boolean parameter ADD specifies whether FUNC will
  1158.         be called additionally to the other bound function or whether
  1159.         it will replace the previous function. See bind for the return value.'''
  1160.         return self._bind(('bind', 'all'), sequence, func, add, 0)
  1161.  
  1162.     
  1163.     def unbind_all(self, sequence):
  1164.         '''Unbind for all widgets for event SEQUENCE all functions.'''
  1165.         self.tk.call('bind', 'all', sequence, '')
  1166.  
  1167.     
  1168.     def bind_class(self, className, sequence = None, func = None, add = None):
  1169.         '''Bind to widgets with bindtag CLASSNAME at event
  1170.         SEQUENCE a call of function FUNC. An additional
  1171.         boolean parameter ADD specifies whether FUNC will be
  1172.         called additionally to the other bound function or
  1173.         whether it will replace the previous function. See bind for
  1174.         the return value.'''
  1175.         return self._bind(('bind', className), sequence, func, add, 0)
  1176.  
  1177.     
  1178.     def unbind_class(self, className, sequence):
  1179.         '''Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
  1180.         all functions.'''
  1181.         self.tk.call('bind', className, sequence, '')
  1182.  
  1183.     
  1184.     def mainloop(self, n = 0):
  1185.         '''Call the mainloop of Tk.'''
  1186.         self.tk.mainloop(n)
  1187.  
  1188.     
  1189.     def quit(self):
  1190.         '''Quit the Tcl interpreter. All widgets will be destroyed.'''
  1191.         self.tk.quit()
  1192.  
  1193.     
  1194.     def _getints(self, string):
  1195.         '''Internal function.'''
  1196.         if string:
  1197.             return tuple(map(getint, self.tk.splitlist(string)))
  1198.         
  1199.  
  1200.     
  1201.     def _getdoubles(self, string):
  1202.         '''Internal function.'''
  1203.         if string:
  1204.             return tuple(map(getdouble, self.tk.splitlist(string)))
  1205.         
  1206.  
  1207.     
  1208.     def _getboolean(self, string):
  1209.         '''Internal function.'''
  1210.         if string:
  1211.             return self.tk.getboolean(string)
  1212.         
  1213.  
  1214.     
  1215.     def _displayof(self, displayof):
  1216.         '''Internal function.'''
  1217.         if displayof:
  1218.             return ('-displayof', displayof)
  1219.         
  1220.         if displayof is None:
  1221.             return ('-displayof', self._w)
  1222.         
  1223.         return ()
  1224.  
  1225.     
  1226.     def _options(self, cnf, kw = None):
  1227.         '''Internal function.'''
  1228.         if kw:
  1229.             cnf = _cnfmerge((cnf, kw))
  1230.         else:
  1231.             cnf = _cnfmerge(cnf)
  1232.         res = ()
  1233.         for k, v in cnf.items():
  1234.             if v is not None:
  1235.                 if k[-1] == '_':
  1236.                     k = k[:-1]
  1237.                 
  1238.                 if callable(v):
  1239.                     v = self._register(v)
  1240.                 
  1241.                 res = res + ('-' + k, v)
  1242.             
  1243.         
  1244.         return res
  1245.  
  1246.     
  1247.     def nametowidget(self, name):
  1248.         '''Return the Tkinter instance of a widget identified by
  1249.         its Tcl name NAME.'''
  1250.         w = self
  1251.         if name[0] == '.':
  1252.             w = w._root()
  1253.             name = name[1:]
  1254.         
  1255.         while name:
  1256.             i = name.find('.')
  1257.             if i >= 0:
  1258.                 (name, tail) = (name[:i], name[i + 1:])
  1259.             else:
  1260.                 tail = ''
  1261.             w = w.children[name]
  1262.             name = tail
  1263.         return w
  1264.  
  1265.     _nametowidget = nametowidget
  1266.     
  1267.     def _register(self, func, subst = None, needcleanup = 1):
  1268.         '''Return a newly created Tcl function. If this
  1269.         function is called, the Python function FUNC will
  1270.         be executed. An optional function SUBST can
  1271.         be given which will be executed before FUNC.'''
  1272.         f = CallWrapper(func, subst, self).__call__
  1273.         name = `id(f)`
  1274.         
  1275.         try:
  1276.             func = func.im_func
  1277.         except AttributeError:
  1278.             pass
  1279.  
  1280.         
  1281.         try:
  1282.             name = name + func.__name__
  1283.         except AttributeError:
  1284.             pass
  1285.  
  1286.         self.tk.createcommand(name, f)
  1287.         if needcleanup:
  1288.             if self._tclCommands is None:
  1289.                 self._tclCommands = []
  1290.             
  1291.             self._tclCommands.append(name)
  1292.         
  1293.         return name
  1294.  
  1295.     register = _register
  1296.     
  1297.     def _root(self):
  1298.         '''Internal function.'''
  1299.         w = self
  1300.         while w.master:
  1301.             w = w.master
  1302.         return w
  1303.  
  1304.     _subst_format = ('%#', '%b', '%f', '%h', '%k', '%s', '%t', '%w', '%x', '%y', '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
  1305.     _subst_format_str = ' '.join(_subst_format)
  1306.     
  1307.     def _substitute(self, *args):
  1308.         '''Internal function.'''
  1309.         if len(args) != len(self._subst_format):
  1310.             return args
  1311.         
  1312.         getboolean = self.tk.getboolean
  1313.         getint = int
  1314.         (nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D) = args
  1315.         e = Event()
  1316.         e.serial = getint(nsign)
  1317.         e.num = getint(b)
  1318.         
  1319.         try:
  1320.             e.focus = getboolean(f)
  1321.         except TclError:
  1322.             pass
  1323.  
  1324.         e.height = getint(h)
  1325.         e.keycode = getint(k)
  1326.         
  1327.         try:
  1328.             e.state = getint(s)
  1329.         except ValueError:
  1330.             e.state = s
  1331.  
  1332.         e.time = getint(t)
  1333.         e.width = getint(w)
  1334.         e.x = getint(x)
  1335.         e.y = getint(y)
  1336.         e.char = A
  1337.         
  1338.         try:
  1339.             e.send_event = getboolean(E)
  1340.         except TclError:
  1341.             pass
  1342.  
  1343.         e.keysym = K
  1344.         e.keysym_num = getint(N)
  1345.         e.type = T
  1346.         
  1347.         try:
  1348.             e.widget = self._nametowidget(W)
  1349.         except KeyError:
  1350.             e.widget = W
  1351.  
  1352.         e.x_root = getint(X)
  1353.         e.y_root = getint(Y)
  1354.         
  1355.         try:
  1356.             e.delta = getint(D)
  1357.         except ValueError:
  1358.             e.delta = 0
  1359.  
  1360.         return (e,)
  1361.  
  1362.     
  1363.     def _report_exception(self):
  1364.         '''Internal function.'''
  1365.         import sys
  1366.         (exc, val, tb) = (sys.exc_type, sys.exc_value, sys.exc_traceback)
  1367.         root = self._root()
  1368.         root.report_callback_exception(exc, val, tb)
  1369.  
  1370.     
  1371.     def configure(self, cnf = None, **kw):
  1372.         '''Configure resources of a widget.
  1373.  
  1374.         The values for resources are specified as keyword
  1375.         arguments. To get an overview about
  1376.         the allowed keyword arguments call the method keys.
  1377.         '''
  1378.         if kw:
  1379.             cnf = _cnfmerge((cnf, kw))
  1380.         elif cnf:
  1381.             cnf = _cnfmerge(cnf)
  1382.         
  1383.         if cnf is None:
  1384.             cnf = { }
  1385.             for x in self.tk.split(self.tk.call(self._w, 'configure')):
  1386.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1387.             
  1388.             return cnf
  1389.         
  1390.         if type(cnf) is StringType:
  1391.             x = self.tk.split(self.tk.call(self._w, 'configure', '-' + cnf))
  1392.             return (x[0][1:],) + x[1:]
  1393.         
  1394.         self.tk.call((self._w, 'configure') + self._options(cnf))
  1395.  
  1396.     config = configure
  1397.     
  1398.     def cget(self, key):
  1399.         '''Return the resource value for a KEY given as string.'''
  1400.         return self.tk.call(self._w, 'cget', '-' + key)
  1401.  
  1402.     __getitem__ = cget
  1403.     
  1404.     def __setitem__(self, key, value):
  1405.         self.configure({
  1406.             key: value })
  1407.  
  1408.     
  1409.     def keys(self):
  1410.         '''Return a list of all resource names of this widget.'''
  1411.         return map((lambda x: x[0][1:]), self.tk.split(self.tk.call(self._w, 'configure')))
  1412.  
  1413.     
  1414.     def __str__(self):
  1415.         '''Return the window path name of this widget.'''
  1416.         return self._w
  1417.  
  1418.     _noarg_ = [
  1419.         '_noarg_']
  1420.     
  1421.     def pack_propagate(self, flag = _noarg_):
  1422.         '''Set or get the status for propagation of geometry information.
  1423.  
  1424.         A boolean argument specifies whether the geometry information
  1425.         of the slaves will determine the size of this widget. If no argument
  1426.         is given the current setting will be returned.
  1427.         '''
  1428.         if flag is Misc._noarg_:
  1429.             return self._getboolean(self.tk.call('pack', 'propagate', self._w))
  1430.         else:
  1431.             self.tk.call('pack', 'propagate', self._w, flag)
  1432.  
  1433.     propagate = pack_propagate
  1434.     
  1435.     def pack_slaves(self):
  1436.         '''Return a list of all slaves of this widget
  1437.         in its packing order.'''
  1438.         return map(self._nametowidget, self.tk.splitlist(self.tk.call('pack', 'slaves', self._w)))
  1439.  
  1440.     slaves = pack_slaves
  1441.     
  1442.     def place_slaves(self):
  1443.         '''Return a list of all slaves of this widget
  1444.         in its packing order.'''
  1445.         return map(self._nametowidget, self.tk.splitlist(self.tk.call('place', 'slaves', self._w)))
  1446.  
  1447.     
  1448.     def grid_bbox(self, column = None, row = None, col2 = None, row2 = None):
  1449.         '''Return a tuple of integer coordinates for the bounding
  1450.         box of this widget controlled by the geometry manager grid.
  1451.  
  1452.         If COLUMN, ROW is given the bounding box applies from
  1453.         the cell with row and column 0 to the specified
  1454.         cell. If COL2 and ROW2 are given the bounding box
  1455.         starts at that cell.
  1456.  
  1457.         The returned integers specify the offset of the upper left
  1458.         corner in the master widget and the width and height.
  1459.         '''
  1460.         args = ('grid', 'bbox', self._w)
  1461.         if column is not None and row is not None:
  1462.             args = args + (column, row)
  1463.         
  1464.         if col2 is not None and row2 is not None:
  1465.             args = args + (col2, row2)
  1466.         
  1467.         if not self._getints(apply(self.tk.call, args)):
  1468.             pass
  1469.         return None
  1470.  
  1471.     bbox = grid_bbox
  1472.     
  1473.     def _grid_configure(self, command, index, cnf, kw):
  1474.         '''Internal function.'''
  1475.         if type(cnf) is StringType and not kw:
  1476.             if cnf[-1:] == '_':
  1477.                 cnf = cnf[:-1]
  1478.             
  1479.             if cnf[:1] != '-':
  1480.                 cnf = '-' + cnf
  1481.             
  1482.             options = (cnf,)
  1483.         else:
  1484.             options = self._options(cnf, kw)
  1485.         if not options:
  1486.             res = self.tk.call('grid', command, self._w, index)
  1487.             words = self.tk.splitlist(res)
  1488.             dict = { }
  1489.             for i in range(0, len(words), 2):
  1490.                 key = words[i][1:]
  1491.                 value = words[i + 1]
  1492.                 if not value:
  1493.                     value = None
  1494.                 elif '.' in value:
  1495.                     value = getdouble(value)
  1496.                 else:
  1497.                     value = getint(value)
  1498.                 dict[key] = value
  1499.             
  1500.             return dict
  1501.         
  1502.         res = self.tk.call(('grid', command, self._w, index) + options)
  1503.         if len(options) == 1:
  1504.             if not res:
  1505.                 return None
  1506.             
  1507.             if '.' in res:
  1508.                 return getdouble(res)
  1509.             
  1510.             return getint(res)
  1511.         
  1512.  
  1513.     
  1514.     def grid_columnconfigure(self, index, cnf = { }, **kw):
  1515.         '''Configure column INDEX of a grid.
  1516.  
  1517.         Valid resources are minsize (minimum size of the column),
  1518.         weight (how much does additional space propagate to this column)
  1519.         and pad (how much space to let additionally).'''
  1520.         return self._grid_configure('columnconfigure', index, cnf, kw)
  1521.  
  1522.     columnconfigure = grid_columnconfigure
  1523.     
  1524.     def grid_location(self, x, y):
  1525.         '''Return a tuple of column and row which identify the cell
  1526.         at which the pixel at position X and Y inside the master
  1527.         widget is located.'''
  1528.         if not self._getints(self.tk.call('grid', 'location', self._w, x, y)):
  1529.             pass
  1530.         return None
  1531.  
  1532.     
  1533.     def grid_propagate(self, flag = _noarg_):
  1534.         '''Set or get the status for propagation of geometry information.
  1535.  
  1536.         A boolean argument specifies whether the geometry information
  1537.         of the slaves will determine the size of this widget. If no argument
  1538.         is given, the current setting will be returned.
  1539.         '''
  1540.         if flag is Misc._noarg_:
  1541.             return self._getboolean(self.tk.call('grid', 'propagate', self._w))
  1542.         else:
  1543.             self.tk.call('grid', 'propagate', self._w, flag)
  1544.  
  1545.     
  1546.     def grid_rowconfigure(self, index, cnf = { }, **kw):
  1547.         '''Configure row INDEX of a grid.
  1548.  
  1549.         Valid resources are minsize (minimum size of the row),
  1550.         weight (how much does additional space propagate to this row)
  1551.         and pad (how much space to let additionally).'''
  1552.         return self._grid_configure('rowconfigure', index, cnf, kw)
  1553.  
  1554.     rowconfigure = grid_rowconfigure
  1555.     
  1556.     def grid_size(self):
  1557.         '''Return a tuple of the number of column and rows in the grid.'''
  1558.         if not self._getints(self.tk.call('grid', 'size', self._w)):
  1559.             pass
  1560.         return None
  1561.  
  1562.     size = grid_size
  1563.     
  1564.     def grid_slaves(self, row = None, column = None):
  1565.         '''Return a list of all slaves of this widget
  1566.         in its packing order.'''
  1567.         args = ()
  1568.         if row is not None:
  1569.             args = args + ('-row', row)
  1570.         
  1571.         if column is not None:
  1572.             args = args + ('-column', column)
  1573.         
  1574.         return map(self._nametowidget, self.tk.splitlist(self.tk.call(('grid', 'slaves', self._w) + args)))
  1575.  
  1576.     
  1577.     def event_add(self, virtual, *sequences):
  1578.         '''Bind a virtual event VIRTUAL (of the form <<Name>>)
  1579.         to an event SEQUENCE such that the virtual event is triggered
  1580.         whenever SEQUENCE occurs.'''
  1581.         args = ('event', 'add', virtual) + sequences
  1582.         self.tk.call(args)
  1583.  
  1584.     
  1585.     def event_delete(self, virtual, *sequences):
  1586.         '''Unbind a virtual event VIRTUAL from SEQUENCE.'''
  1587.         args = ('event', 'delete', virtual) + sequences
  1588.         self.tk.call(args)
  1589.  
  1590.     
  1591.     def event_generate(self, sequence, **kw):
  1592.         '''Generate an event SEQUENCE. Additional
  1593.         keyword arguments specify parameter of the event
  1594.         (e.g. x, y, rootx, rooty).'''
  1595.         args = ('event', 'generate', self._w, sequence)
  1596.         for k, v in kw.items():
  1597.             args = args + ('-%s' % k, str(v))
  1598.         
  1599.         self.tk.call(args)
  1600.  
  1601.     
  1602.     def event_info(self, virtual = None):
  1603.         '''Return a list of all virtual events or the information
  1604.         about the SEQUENCE bound to the virtual event VIRTUAL.'''
  1605.         return self.tk.splitlist(self.tk.call('event', 'info', virtual))
  1606.  
  1607.     
  1608.     def image_names(self):
  1609.         '''Return a list of all existing image names.'''
  1610.         return self.tk.call('image', 'names')
  1611.  
  1612.     
  1613.     def image_types(self):
  1614.         '''Return a list of all available image types (e.g. phote bitmap).'''
  1615.         return self.tk.call('image', 'types')
  1616.  
  1617.  
  1618.  
  1619. class CallWrapper:
  1620.     '''Internal class. Stores function to call when some user
  1621.     defined Tcl function is called e.g. after an event occurred.'''
  1622.     
  1623.     def __init__(self, func, subst, widget):
  1624.         '''Store FUNC, SUBST and WIDGET as members.'''
  1625.         self.func = func
  1626.         self.subst = subst
  1627.         self.widget = widget
  1628.  
  1629.     
  1630.     def __call__(self, *args):
  1631.         '''Apply first function SUBST to arguments, than FUNC.'''
  1632.         
  1633.         try:
  1634.             if self.subst:
  1635.                 args = apply(self.subst, args)
  1636.             
  1637.             return apply(self.func, args)
  1638.         except SystemExit:
  1639.             msg = None
  1640.             raise SystemExit, msg
  1641.         except:
  1642.             self.widget._report_exception()
  1643.  
  1644.  
  1645.  
  1646.  
  1647. class Wm:
  1648.     '''Provides functions for the communication with the window manager.'''
  1649.     
  1650.     def wm_aspect(self, minNumer = None, minDenom = None, maxNumer = None, maxDenom = None):
  1651.         '''Instruct the window manager to set the aspect ratio (width/height)
  1652.         of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
  1653.         of the actual values if no argument is given.'''
  1654.         return self._getints(self.tk.call('wm', 'aspect', self._w, minNumer, minDenom, maxNumer, maxDenom))
  1655.  
  1656.     aspect = wm_aspect
  1657.     
  1658.     def wm_client(self, name = None):
  1659.         '''Store NAME in WM_CLIENT_MACHINE property of this widget. Return
  1660.         current value.'''
  1661.         return self.tk.call('wm', 'client', self._w, name)
  1662.  
  1663.     client = wm_client
  1664.     
  1665.     def wm_colormapwindows(self, *wlist):
  1666.         '''Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
  1667.         of this widget. This list contains windows whose colormaps differ from their
  1668.         parents. Return current list of widgets if WLIST is empty.'''
  1669.         if len(wlist) > 1:
  1670.             wlist = (wlist,)
  1671.         
  1672.         args = ('wm', 'colormapwindows', self._w) + wlist
  1673.         return map(self._nametowidget, self.tk.call(args))
  1674.  
  1675.     colormapwindows = wm_colormapwindows
  1676.     
  1677.     def wm_command(self, value = None):
  1678.         '''Store VALUE in WM_COMMAND property. It is the command
  1679.         which shall be used to invoke the application. Return current
  1680.         command if VALUE is None.'''
  1681.         return self.tk.call('wm', 'command', self._w, value)
  1682.  
  1683.     command = wm_command
  1684.     
  1685.     def wm_deiconify(self):
  1686.         '''Deiconify this widget. If it was never mapped it will not be mapped.
  1687.         On Windows it will raise this widget and give it the focus.'''
  1688.         return self.tk.call('wm', 'deiconify', self._w)
  1689.  
  1690.     deiconify = wm_deiconify
  1691.     
  1692.     def wm_focusmodel(self, model = None):
  1693.         '''Set focus model to MODEL. "active" means that this widget will claim
  1694.         the focus itself, "passive" means that the window manager shall give
  1695.         the focus. Return current focus model if MODEL is None.'''
  1696.         return self.tk.call('wm', 'focusmodel', self._w, model)
  1697.  
  1698.     focusmodel = wm_focusmodel
  1699.     
  1700.     def wm_frame(self):
  1701.         '''Return identifier for decorative frame of this widget if present.'''
  1702.         return self.tk.call('wm', 'frame', self._w)
  1703.  
  1704.     frame = wm_frame
  1705.     
  1706.     def wm_geometry(self, newGeometry = None):
  1707.         '''Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
  1708.         current value if None is given.'''
  1709.         return self.tk.call('wm', 'geometry', self._w, newGeometry)
  1710.  
  1711.     geometry = wm_geometry
  1712.     
  1713.     def wm_grid(self, baseWidth = None, baseHeight = None, widthInc = None, heightInc = None):
  1714.         '''Instruct the window manager that this widget shall only be
  1715.         resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
  1716.         height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
  1717.         number of grid units requested in Tk_GeometryRequest.'''
  1718.         return self._getints(self.tk.call('wm', 'grid', self._w, baseWidth, baseHeight, widthInc, heightInc))
  1719.  
  1720.     grid = wm_grid
  1721.     
  1722.     def wm_group(self, pathName = None):
  1723.         '''Set the group leader widgets for related widgets to PATHNAME. Return
  1724.         the group leader of this widget if None is given.'''
  1725.         return self.tk.call('wm', 'group', self._w, pathName)
  1726.  
  1727.     group = wm_group
  1728.     
  1729.     def wm_iconbitmap(self, bitmap = None):
  1730.         '''Set bitmap for the iconified widget to BITMAP. Return
  1731.         the bitmap if None is given.'''
  1732.         return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  1733.  
  1734.     iconbitmap = wm_iconbitmap
  1735.     
  1736.     def wm_iconify(self):
  1737.         '''Display widget as icon.'''
  1738.         return self.tk.call('wm', 'iconify', self._w)
  1739.  
  1740.     iconify = wm_iconify
  1741.     
  1742.     def wm_iconmask(self, bitmap = None):
  1743.         '''Set mask for the icon bitmap of this widget. Return the
  1744.         mask if None is given.'''
  1745.         return self.tk.call('wm', 'iconmask', self._w, bitmap)
  1746.  
  1747.     iconmask = wm_iconmask
  1748.     
  1749.     def wm_iconname(self, newName = None):
  1750.         '''Set the name of the icon for this widget. Return the name if
  1751.         None is given.'''
  1752.         return self.tk.call('wm', 'iconname', self._w, newName)
  1753.  
  1754.     iconname = wm_iconname
  1755.     
  1756.     def wm_iconposition(self, x = None, y = None):
  1757.         '''Set the position of the icon of this widget to X and Y. Return
  1758.         a tuple of the current values of X and X if None is given.'''
  1759.         return self._getints(self.tk.call('wm', 'iconposition', self._w, x, y))
  1760.  
  1761.     iconposition = wm_iconposition
  1762.     
  1763.     def wm_iconwindow(self, pathName = None):
  1764.         '''Set widget PATHNAME to be displayed instead of icon. Return the current
  1765.         value if None is given.'''
  1766.         return self.tk.call('wm', 'iconwindow', self._w, pathName)
  1767.  
  1768.     iconwindow = wm_iconwindow
  1769.     
  1770.     def wm_maxsize(self, width = None, height = None):
  1771.         '''Set max WIDTH and HEIGHT for this widget. If the window is gridded
  1772.         the values are given in grid units. Return the current values if None
  1773.         is given.'''
  1774.         return self._getints(self.tk.call('wm', 'maxsize', self._w, width, height))
  1775.  
  1776.     maxsize = wm_maxsize
  1777.     
  1778.     def wm_minsize(self, width = None, height = None):
  1779.         '''Set min WIDTH and HEIGHT for this widget. If the window is gridded
  1780.         the values are given in grid units. Return the current values if None
  1781.         is given.'''
  1782.         return self._getints(self.tk.call('wm', 'minsize', self._w, width, height))
  1783.  
  1784.     minsize = wm_minsize
  1785.     
  1786.     def wm_overrideredirect(self, boolean = None):
  1787.         '''Instruct the window manager to ignore this widget
  1788.         if BOOLEAN is given with 1. Return the current value if None
  1789.         is given.'''
  1790.         return self._getboolean(self.tk.call('wm', 'overrideredirect', self._w, boolean))
  1791.  
  1792.     overrideredirect = wm_overrideredirect
  1793.     
  1794.     def wm_positionfrom(self, who = None):
  1795.         '''Instruct the window manager that the position of this widget shall
  1796.         be defined by the user if WHO is "user", and by its own policy if WHO is
  1797.         "program".'''
  1798.         return self.tk.call('wm', 'positionfrom', self._w, who)
  1799.  
  1800.     positionfrom = wm_positionfrom
  1801.     
  1802.     def wm_protocol(self, name = None, func = None):
  1803.         '''Bind function FUNC to command NAME for this widget.
  1804.         Return the function bound to NAME if None is given. NAME could be
  1805.         e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW".'''
  1806.         if callable(func):
  1807.             command = self._register(func)
  1808.         else:
  1809.             command = func
  1810.         return self.tk.call('wm', 'protocol', self._w, name, command)
  1811.  
  1812.     protocol = wm_protocol
  1813.     
  1814.     def wm_resizable(self, width = None, height = None):
  1815.         '''Instruct the window manager whether this width can be resized
  1816.         in WIDTH or HEIGHT. Both values are boolean values.'''
  1817.         return self.tk.call('wm', 'resizable', self._w, width, height)
  1818.  
  1819.     resizable = wm_resizable
  1820.     
  1821.     def wm_sizefrom(self, who = None):
  1822.         '''Instruct the window manager that the size of this widget shall
  1823.         be defined by the user if WHO is "user", and by its own policy if WHO is
  1824.         "program".'''
  1825.         return self.tk.call('wm', 'sizefrom', self._w, who)
  1826.  
  1827.     sizefrom = wm_sizefrom
  1828.     
  1829.     def wm_state(self, newstate = None):
  1830.         '''Query or set the state of this widget as one of normal, icon,
  1831.         iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only).'''
  1832.         return self.tk.call('wm', 'state', self._w, newstate)
  1833.  
  1834.     state = wm_state
  1835.     
  1836.     def wm_title(self, string = None):
  1837.         '''Set the title of this widget.'''
  1838.         return self.tk.call('wm', 'title', self._w, string)
  1839.  
  1840.     title = wm_title
  1841.     
  1842.     def wm_transient(self, master = None):
  1843.         '''Instruct the window manager that this widget is transient
  1844.         with regard to widget MASTER.'''
  1845.         return self.tk.call('wm', 'transient', self._w, master)
  1846.  
  1847.     transient = wm_transient
  1848.     
  1849.     def wm_withdraw(self):
  1850.         '''Withdraw this widget from the screen such that it is unmapped
  1851.         and forgotten by the window manager. Re-draw it with wm_deiconify.'''
  1852.         return self.tk.call('wm', 'withdraw', self._w)
  1853.  
  1854.     withdraw = wm_withdraw
  1855.  
  1856.  
  1857. class Tk(Misc, Wm):
  1858.     '''Toplevel widget of Tk which represents mostly the main window
  1859.     of an appliation. It has an associated Tcl interpreter.'''
  1860.     _w = '.'
  1861.     
  1862.     def __init__(self, screenName = None, baseName = None, className = 'Tk'):
  1863.         '''Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
  1864.         be created. BASENAME will be used for the identification of the profile file (see
  1865.         readprofile).
  1866.         It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
  1867.         is the name of the widget class.'''
  1868.         global _default_root
  1869.         self.master = None
  1870.         self.children = { }
  1871.         if baseName is None:
  1872.             import sys
  1873.             import os
  1874.             baseName = os.path.basename(sys.argv[0])
  1875.             (baseName, ext) = os.path.splitext(baseName)
  1876.             if ext not in ('.py', '.pyc', '.pyo'):
  1877.                 baseName = baseName + ext
  1878.             
  1879.         
  1880.         self.tk = _tkinter.create(screenName, baseName, className)
  1881.         if _MacOS and hasattr(_MacOS, 'SchedParams'):
  1882.             _MacOS.SchedParams(1, 0)
  1883.             self.update()
  1884.         
  1885.         tk_version = self.tk.getvar('tk_version')
  1886.         if tk_version != _tkinter.TK_VERSION:
  1887.             raise RuntimeError, "tk.h version (%s) doesn't match libtk.a version (%s)" % (_tkinter.TK_VERSION, tk_version)
  1888.         
  1889.         tcl_version = self.tk.getvar('tcl_version')
  1890.         if tcl_version != _tkinter.TCL_VERSION:
  1891.             raise RuntimeError, "tcl.h version (%s) doesn't match libtcl.a version (%s)" % (_tkinter.TCL_VERSION, tcl_version)
  1892.         
  1893.         if TkVersion < 4.0:
  1894.             raise RuntimeError, 'Tk 4.0 or higher is required; found Tk %s' % str(TkVersion)
  1895.         
  1896.         self.tk.createcommand('tkerror', _tkerror)
  1897.         self.tk.createcommand('exit', _exit)
  1898.         self.readprofile(baseName, className)
  1899.         if _support_default_root and not _default_root:
  1900.             _default_root = self
  1901.         
  1902.         self.protocol('WM_DELETE_WINDOW', self.destroy)
  1903.  
  1904.     
  1905.     def destroy(self):
  1906.         '''Destroy this and all descendants widgets. This will
  1907.         end the application of this Tcl interpreter.'''
  1908.         global _default_root
  1909.         for c in self.children.values():
  1910.             c.destroy()
  1911.         
  1912.         self.tk.call('destroy', self._w)
  1913.         Misc.destroy(self)
  1914.         if _support_default_root and _default_root is self:
  1915.             _default_root = None
  1916.         
  1917.  
  1918.     
  1919.     def readprofile(self, baseName, className):
  1920.         '''Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
  1921.         the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
  1922.         such a file exists in the home directory.'''
  1923.         import os
  1924.         if os.environ.has_key('HOME'):
  1925.             home = os.environ['HOME']
  1926.         else:
  1927.             home = os.curdir
  1928.         class_tcl = os.path.join(home, '.%s.tcl' % className)
  1929.         class_py = os.path.join(home, '.%s.py' % className)
  1930.         base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  1931.         base_py = os.path.join(home, '.%s.py' % baseName)
  1932.         dir = {
  1933.             'self': self }
  1934.         exec 'from Tkinter import *' in dir
  1935.         if os.path.isfile(class_tcl):
  1936.             self.tk.call('source', class_tcl)
  1937.         
  1938.         if os.path.isfile(class_py):
  1939.             execfile(class_py, dir)
  1940.         
  1941.         if os.path.isfile(base_tcl):
  1942.             self.tk.call('source', base_tcl)
  1943.         
  1944.         if os.path.isfile(base_py):
  1945.             execfile(base_py, dir)
  1946.         
  1947.  
  1948.     
  1949.     def report_callback_exception(self, exc, val, tb):
  1950.         '''Internal function. It reports exception on sys.stderr.'''
  1951.         import traceback
  1952.         import sys
  1953.         sys.stderr.write('Exception in Tkinter callback\n')
  1954.         sys.last_type = exc
  1955.         sys.last_value = val
  1956.         sys.last_traceback = tb
  1957.         traceback.print_exception(exc, val, tb)
  1958.  
  1959.  
  1960.  
  1961. class Pack:
  1962.     '''Geometry manager Pack.
  1963.  
  1964.     Base class to use the methods pack_* in every widget.'''
  1965.     
  1966.     def pack_configure(self, cnf = { }, **kw):
  1967.         '''Pack a widget in the parent widget. Use as options:
  1968.         after=widget - pack it after you have packed widget
  1969.         anchor=NSEW (or subset) - position widget according to
  1970.                                   given direction
  1971.                 before=widget - pack it before you will pack widget
  1972.         expand=1 or 0 - expand widget if parent size grows
  1973.         fill=NONE or X or Y or BOTH - fill widget if widget grows
  1974.         in=master - use master to contain this widget
  1975.         ipadx=amount - add internal padding in x direction
  1976.         ipady=amount - add internal padding in y direction
  1977.         padx=amount - add padding in x direction
  1978.         pady=amount - add padding in y direction
  1979.         side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
  1980.         '''
  1981.         self.tk.call(('pack', 'configure', self._w) + self._options(cnf, kw))
  1982.  
  1983.     pack = configure = config = pack_configure
  1984.     
  1985.     def pack_forget(self):
  1986.         '''Unmap this widget and do not use it for the packing order.'''
  1987.         self.tk.call('pack', 'forget', self._w)
  1988.  
  1989.     forget = pack_forget
  1990.     
  1991.     def pack_info(self):
  1992.         '''Return information about the packing options
  1993.         for this widget.'''
  1994.         words = self.tk.splitlist(self.tk.call('pack', 'info', self._w))
  1995.         dict = { }
  1996.         for i in range(0, len(words), 2):
  1997.             key = words[i][1:]
  1998.             value = words[i + 1]
  1999.             if value[:1] == '.':
  2000.                 value = self._nametowidget(value)
  2001.             
  2002.             dict[key] = value
  2003.         
  2004.         return dict
  2005.  
  2006.     info = pack_info
  2007.     propagate = pack_propagate = Misc.pack_propagate
  2008.     slaves = pack_slaves = Misc.pack_slaves
  2009.  
  2010.  
  2011. class Place:
  2012.     '''Geometry manager Place.
  2013.  
  2014.     Base class to use the methods place_* in every widget.'''
  2015.     
  2016.     def place_configure(self, cnf = { }, **kw):
  2017.         '''Place a widget in the parent widget. Use as options:
  2018.         in=master - master relative to which the widget is placed.
  2019.         x=amount - locate anchor of this widget at position x of master
  2020.         y=amount - locate anchor of this widget at position y of master
  2021.         relx=amount - locate anchor of this widget between 0.0 and 1.0
  2022.                       relative to width of master (1.0 is right edge)
  2023.             rely=amount - locate anchor of this widget between 0.0 and 1.0
  2024.                       relative to height of master (1.0 is bottom edge)
  2025.             anchor=NSEW (or subset) - position anchor according to given direction
  2026.         width=amount - width of this widget in pixel
  2027.         height=amount - height of this widget in pixel
  2028.         relwidth=amount - width of this widget between 0.0 and 1.0
  2029.                           relative to width of master (1.0 is the same width
  2030.                   as the master)
  2031.             relheight=amount - height of this widget between 0.0 and 1.0
  2032.                            relative to height of master (1.0 is the same
  2033.                    height as the master)
  2034.             bordermode="inside" or "outside" - whether to take border width of master widget
  2035.                                                into account
  2036.             '''
  2037.         for k in [
  2038.             'in_']:
  2039.             if kw.has_key(k):
  2040.                 kw[k[:-1]] = kw[k]
  2041.                 del kw[k]
  2042.             
  2043.         
  2044.         self.tk.call(('place', 'configure', self._w) + self._options(cnf, kw))
  2045.  
  2046.     place = configure = config = place_configure
  2047.     
  2048.     def place_forget(self):
  2049.         '''Unmap this widget.'''
  2050.         self.tk.call('place', 'forget', self._w)
  2051.  
  2052.     forget = place_forget
  2053.     
  2054.     def place_info(self):
  2055.         '''Return information about the placing options
  2056.         for this widget.'''
  2057.         words = self.tk.splitlist(self.tk.call('place', 'info', self._w))
  2058.         dict = { }
  2059.         for i in range(0, len(words), 2):
  2060.             key = words[i][1:]
  2061.             value = words[i + 1]
  2062.             if value[:1] == '.':
  2063.                 value = self._nametowidget(value)
  2064.             
  2065.             dict[key] = value
  2066.         
  2067.         return dict
  2068.  
  2069.     info = place_info
  2070.     slaves = place_slaves = Misc.place_slaves
  2071.  
  2072.  
  2073. class Grid:
  2074.     '''Geometry manager Grid.
  2075.  
  2076.     Base class to use the methods grid_* in every widget.'''
  2077.     
  2078.     def grid_configure(self, cnf = { }, **kw):
  2079.         '''Position a widget in the parent widget in a grid. Use as options:
  2080.         column=number - use cell identified with given column (starting with 0)
  2081.         columnspan=number - this widget will span several columns
  2082.         in=master - use master to contain this widget
  2083.         ipadx=amount - add internal padding in x direction
  2084.         ipady=amount - add internal padding in y direction
  2085.         padx=amount - add padding in x direction
  2086.         pady=amount - add padding in y direction
  2087.         row=number - use cell identified with given row (starting with 0)
  2088.         rowspan=number - this widget will span several rows
  2089.         sticky=NSEW - if cell is larger on which sides will this
  2090.                       widget stick to the cell boundary
  2091.         '''
  2092.         self.tk.call(('grid', 'configure', self._w) + self._options(cnf, kw))
  2093.  
  2094.     grid = configure = config = grid_configure
  2095.     bbox = grid_bbox = Misc.grid_bbox
  2096.     columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  2097.     
  2098.     def grid_forget(self):
  2099.         '''Unmap this widget.'''
  2100.         self.tk.call('grid', 'forget', self._w)
  2101.  
  2102.     forget = grid_forget
  2103.     
  2104.     def grid_remove(self):
  2105.         '''Unmap this widget but remember the grid options.'''
  2106.         self.tk.call('grid', 'remove', self._w)
  2107.  
  2108.     
  2109.     def grid_info(self):
  2110.         '''Return information about the options
  2111.         for positioning this widget in a grid.'''
  2112.         words = self.tk.splitlist(self.tk.call('grid', 'info', self._w))
  2113.         dict = { }
  2114.         for i in range(0, len(words), 2):
  2115.             key = words[i][1:]
  2116.             value = words[i + 1]
  2117.             if value[:1] == '.':
  2118.                 value = self._nametowidget(value)
  2119.             
  2120.             dict[key] = value
  2121.         
  2122.         return dict
  2123.  
  2124.     info = grid_info
  2125.     location = grid_location = Misc.grid_location
  2126.     propagate = grid_propagate = Misc.grid_propagate
  2127.     rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  2128.     size = grid_size = Misc.grid_size
  2129.     slaves = grid_slaves = Misc.grid_slaves
  2130.  
  2131.  
  2132. class BaseWidget(Misc):
  2133.     '''Internal class.'''
  2134.     
  2135.     def _setup(self, master, cnf):
  2136.         '''Internal function. Sets up information about children.'''
  2137.         global _default_root
  2138.         if _support_default_root:
  2139.             if not master:
  2140.                 if not _default_root:
  2141.                     _default_root = Tk()
  2142.                 
  2143.                 master = _default_root
  2144.             
  2145.         
  2146.         self.master = master
  2147.         self.tk = master.tk
  2148.         name = None
  2149.         if cnf.has_key('name'):
  2150.             name = cnf['name']
  2151.             del cnf['name']
  2152.         
  2153.         if not name:
  2154.             name = `id(self)`
  2155.         
  2156.         self._name = name
  2157.         if master._w == '.':
  2158.             self._w = '.' + name
  2159.         else:
  2160.             self._w = master._w + '.' + name
  2161.         self.children = { }
  2162.         if self.master.children.has_key(self._name):
  2163.             self.master.children[self._name].destroy()
  2164.         
  2165.         self.master.children[self._name] = self
  2166.  
  2167.     
  2168.     def __init__(self, master, widgetName, cnf = { }, kw = { }, extra = ()):
  2169.         '''Construct a widget with the parent widget MASTER, a name WIDGETNAME
  2170.         and appropriate options.'''
  2171.         if kw:
  2172.             cnf = _cnfmerge((cnf, kw))
  2173.         
  2174.         self.widgetName = widgetName
  2175.         BaseWidget._setup(self, master, cnf)
  2176.         classes = []
  2177.         for k in cnf.keys():
  2178.             if type(k) is ClassType:
  2179.                 classes.append((k, cnf[k]))
  2180.                 del cnf[k]
  2181.             
  2182.         
  2183.         self.tk.call((widgetName, self._w) + extra + self._options(cnf))
  2184.         for k, v in classes:
  2185.             k.configure(self, v)
  2186.         
  2187.  
  2188.     
  2189.     def destroy(self):
  2190.         '''Destroy this and all descendants widgets.'''
  2191.         for c in self.children.values():
  2192.             c.destroy()
  2193.         
  2194.         if self.master.children.has_key(self._name):
  2195.             del self.master.children[self._name]
  2196.         
  2197.         self.tk.call('destroy', self._w)
  2198.         Misc.destroy(self)
  2199.  
  2200.     
  2201.     def _do(self, name, args = ()):
  2202.         return self.tk.call((self._w, name) + args)
  2203.  
  2204.  
  2205.  
  2206. class Widget(BaseWidget, Pack, Place, Grid):
  2207.     '''Internal class.
  2208.  
  2209.     Base class for a widget which can be positioned with the geometry managers
  2210.     Pack, Place or Grid.'''
  2211.     pass
  2212.  
  2213.  
  2214. class Toplevel(BaseWidget, Wm):
  2215.     '''Toplevel widget, e.g. for dialogs.'''
  2216.     
  2217.     def __init__(self, master = None, cnf = { }, **kw):
  2218.         '''Construct a toplevel widget with the parent MASTER.
  2219.  
  2220.         Valid resource names: background, bd, bg, borderwidth, class,
  2221.         colormap, container, cursor, height, highlightbackground,
  2222.         highlightcolor, highlightthickness, menu, relief, screen, takefocus,
  2223.         use, visual, width.'''
  2224.         if kw:
  2225.             cnf = _cnfmerge((cnf, kw))
  2226.         
  2227.         extra = ()
  2228.         for wmkey in [
  2229.             'screen',
  2230.             'class_',
  2231.             'class',
  2232.             'visual',
  2233.             'colormap']:
  2234.             if cnf.has_key(wmkey):
  2235.                 val = cnf[wmkey]
  2236.                 if wmkey[-1] == '_':
  2237.                     opt = '-' + wmkey[:-1]
  2238.                 else:
  2239.                     opt = '-' + wmkey
  2240.                 extra = extra + (opt, val)
  2241.                 del cnf[wmkey]
  2242.             
  2243.         
  2244.         BaseWidget.__init__(self, master, 'toplevel', cnf, { }, extra)
  2245.         root = self._root()
  2246.         self.iconname(root.iconname())
  2247.         self.title(root.title())
  2248.         self.protocol('WM_DELETE_WINDOW', self.destroy)
  2249.  
  2250.  
  2251.  
  2252. class Button(Widget):
  2253.     '''Button widget.'''
  2254.     
  2255.     def __init__(self, master = None, cnf = { }, **kw):
  2256.         '''Construct a button widget with the parent MASTER.
  2257.  
  2258.         Valid resource names: activebackground, activeforeground, anchor,
  2259.         background, bd, bg, bitmap, borderwidth, command, cursor, default,
  2260.         disabledforeground, fg, font, foreground, height,
  2261.         highlightbackground, highlightcolor, highlightthickness, image,
  2262.         justify, padx, pady, relief, state, takefocus, text, textvariable,
  2263.         underline, width, wraplength.'''
  2264.         Widget.__init__(self, master, 'button', cnf, kw)
  2265.  
  2266.     
  2267.     def tkButtonEnter(self, *dummy):
  2268.         self.tk.call('tkButtonEnter', self._w)
  2269.  
  2270.     
  2271.     def tkButtonLeave(self, *dummy):
  2272.         self.tk.call('tkButtonLeave', self._w)
  2273.  
  2274.     
  2275.     def tkButtonDown(self, *dummy):
  2276.         self.tk.call('tkButtonDown', self._w)
  2277.  
  2278.     
  2279.     def tkButtonUp(self, *dummy):
  2280.         self.tk.call('tkButtonUp', self._w)
  2281.  
  2282.     
  2283.     def tkButtonInvoke(self, *dummy):
  2284.         self.tk.call('tkButtonInvoke', self._w)
  2285.  
  2286.     
  2287.     def flash(self):
  2288.         self.tk.call(self._w, 'flash')
  2289.  
  2290.     
  2291.     def invoke(self):
  2292.         return self.tk.call(self._w, 'invoke')
  2293.  
  2294.  
  2295.  
  2296. def AtEnd():
  2297.     return 'end'
  2298.  
  2299.  
  2300. def AtInsert(*args):
  2301.     s = 'insert'
  2302.     for a in args:
  2303.         if a:
  2304.             s = s + ' ' + a
  2305.         
  2306.     
  2307.     return s
  2308.  
  2309.  
  2310. def AtSelFirst():
  2311.     return 'sel.first'
  2312.  
  2313.  
  2314. def AtSelLast():
  2315.     return 'sel.last'
  2316.  
  2317.  
  2318. def At(x, y = None):
  2319.     if y is None:
  2320.         return '@' + `x`
  2321.     else:
  2322.         return '@' + `x` + ',' + `y`
  2323.  
  2324.  
  2325. class Canvas(Widget):
  2326.     '''Canvas widget to display graphical elements like lines or text.'''
  2327.     
  2328.     def __init__(self, master = None, cnf = { }, **kw):
  2329.         '''Construct a canvas widget with the parent MASTER.
  2330.  
  2331.         Valid resource names: background, bd, bg, borderwidth, closeenough,
  2332.         confine, cursor, height, highlightbackground, highlightcolor,
  2333.         highlightthickness, insertbackground, insertborderwidth,
  2334.         insertofftime, insertontime, insertwidth, offset, relief,
  2335.         scrollregion, selectbackground, selectborderwidth, selectforeground,
  2336.         state, takefocus, width, xscrollcommand, xscrollincrement,
  2337.         yscrollcommand, yscrollincrement.'''
  2338.         Widget.__init__(self, master, 'canvas', cnf, kw)
  2339.  
  2340.     
  2341.     def addtag(self, *args):
  2342.         '''Internal function.'''
  2343.         self.tk.call((self._w, 'addtag') + args)
  2344.  
  2345.     
  2346.     def addtag_above(self, newtag, tagOrId):
  2347.         '''Add tag NEWTAG to all items above TAGORID.'''
  2348.         self.addtag(newtag, 'above', tagOrId)
  2349.  
  2350.     
  2351.     def addtag_all(self, newtag):
  2352.         '''Add tag NEWTAG to all items.'''
  2353.         self.addtag(newtag, 'all')
  2354.  
  2355.     
  2356.     def addtag_below(self, newtag, tagOrId):
  2357.         '''Add tag NEWTAG to all items below TAGORID.'''
  2358.         self.addtag(newtag, 'below', tagOrId)
  2359.  
  2360.     
  2361.     def addtag_closest(self, newtag, x, y, halo = None, start = None):
  2362.         '''Add tag NEWTAG to item which is closest to pixel at X, Y.
  2363.         If several match take the top-most.
  2364.         All items closer than HALO are considered overlapping (all are
  2365.         closests). If START is specified the next below this tag is taken.'''
  2366.         self.addtag(newtag, 'closest', x, y, halo, start)
  2367.  
  2368.     
  2369.     def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  2370.         '''Add tag NEWTAG to all items in the rectangle defined
  2371.         by X1,Y1,X2,Y2.'''
  2372.         self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  2373.  
  2374.     
  2375.     def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  2376.         '''Add tag NEWTAG to all items which overlap the rectangle
  2377.         defined by X1,Y1,X2,Y2.'''
  2378.         self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  2379.  
  2380.     
  2381.     def addtag_withtag(self, newtag, tagOrId):
  2382.         '''Add tag NEWTAG to all items with TAGORID.'''
  2383.         self.addtag(newtag, 'withtag', tagOrId)
  2384.  
  2385.     
  2386.     def bbox(self, *args):
  2387.         '''Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2388.         which encloses all items with tags specified as arguments.'''
  2389.         if not self._getints(self.tk.call((self._w, 'bbox') + args)):
  2390.             pass
  2391.         return None
  2392.  
  2393.     
  2394.     def tag_unbind(self, tagOrId, sequence, funcid = None):
  2395.         '''Unbind for all items with TAGORID for event SEQUENCE  the
  2396.         function identified with FUNCID.'''
  2397.         self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  2398.         if funcid:
  2399.             self.deletecommand(funcid)
  2400.         
  2401.  
  2402.     
  2403.     def tag_bind(self, tagOrId, sequence = None, func = None, add = None):
  2404.         '''Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
  2405.  
  2406.         An additional boolean parameter ADD specifies whether FUNC will be
  2407.         called additionally to the other bound function or whether it will
  2408.         replace the previous function. See bind for the return value.'''
  2409.         return self._bind((self._w, 'bind', tagOrId), sequence, func, add)
  2410.  
  2411.     
  2412.     def canvasx(self, screenx, gridspacing = None):
  2413.         '''Return the canvas x coordinate of pixel position SCREENX rounded
  2414.         to nearest multiple of GRIDSPACING units.'''
  2415.         return getdouble(self.tk.call(self._w, 'canvasx', screenx, gridspacing))
  2416.  
  2417.     
  2418.     def canvasy(self, screeny, gridspacing = None):
  2419.         '''Return the canvas y coordinate of pixel position SCREENY rounded
  2420.         to nearest multiple of GRIDSPACING units.'''
  2421.         return getdouble(self.tk.call(self._w, 'canvasy', screeny, gridspacing))
  2422.  
  2423.     
  2424.     def coords(self, *args):
  2425.         '''Return a list of coordinates for the item given in ARGS.'''
  2426.         return map(getdouble, self.tk.splitlist(self.tk.call((self._w, 'coords') + args)))
  2427.  
  2428.     
  2429.     def _create(self, itemType, args, kw):
  2430.         '''Internal function.'''
  2431.         args = _flatten(args)
  2432.         cnf = args[-1]
  2433.         if type(cnf) in (DictionaryType, TupleType):
  2434.             args = args[:-1]
  2435.         else:
  2436.             cnf = { }
  2437.         return getint(apply(self.tk.call, (self._w, 'create', itemType) + args + self._options(cnf, kw)))
  2438.  
  2439.     
  2440.     def create_arc(self, *args, **kw):
  2441.         '''Create arc shaped region with coordinates x1,y1,x2,y2.'''
  2442.         return self._create('arc', args, kw)
  2443.  
  2444.     
  2445.     def create_bitmap(self, *args, **kw):
  2446.         '''Create bitmap with coordinates x1,y1.'''
  2447.         return self._create('bitmap', args, kw)
  2448.  
  2449.     
  2450.     def create_image(self, *args, **kw):
  2451.         '''Create image item with coordinates x1,y1.'''
  2452.         return self._create('image', args, kw)
  2453.  
  2454.     
  2455.     def create_line(self, *args, **kw):
  2456.         '''Create line with coordinates x1,y1,...,xn,yn.'''
  2457.         return self._create('line', args, kw)
  2458.  
  2459.     
  2460.     def create_oval(self, *args, **kw):
  2461.         '''Create oval with coordinates x1,y1,x2,y2.'''
  2462.         return self._create('oval', args, kw)
  2463.  
  2464.     
  2465.     def create_polygon(self, *args, **kw):
  2466.         '''Create polygon with coordinates x1,y1,...,xn,yn.'''
  2467.         return self._create('polygon', args, kw)
  2468.  
  2469.     
  2470.     def create_rectangle(self, *args, **kw):
  2471.         '''Create rectangle with coordinates x1,y1,x2,y2.'''
  2472.         return self._create('rectangle', args, kw)
  2473.  
  2474.     
  2475.     def create_text(self, *args, **kw):
  2476.         '''Create text with coordinates x1,y1.'''
  2477.         return self._create('text', args, kw)
  2478.  
  2479.     
  2480.     def create_window(self, *args, **kw):
  2481.         '''Create window with coordinates x1,y1,x2,y2.'''
  2482.         return self._create('window', args, kw)
  2483.  
  2484.     
  2485.     def dchars(self, *args):
  2486.         '''Delete characters of text items identified by tag or id in ARGS (possibly
  2487.         several times) from FIRST to LAST character (including).'''
  2488.         self.tk.call((self._w, 'dchars') + args)
  2489.  
  2490.     
  2491.     def delete(self, *args):
  2492.         '''Delete items identified by all tag or ids contained in ARGS.'''
  2493.         self.tk.call((self._w, 'delete') + args)
  2494.  
  2495.     
  2496.     def dtag(self, *args):
  2497.         '''Delete tag or id given as last arguments in ARGS from items
  2498.         identified by first argument in ARGS.'''
  2499.         self.tk.call((self._w, 'dtag') + args)
  2500.  
  2501.     
  2502.     def find(self, *args):
  2503.         '''Internal function.'''
  2504.         if not self._getints(self.tk.call((self._w, 'find') + args)):
  2505.             pass
  2506.         return ()
  2507.  
  2508.     
  2509.     def find_above(self, tagOrId):
  2510.         '''Return items above TAGORID.'''
  2511.         return self.find('above', tagOrId)
  2512.  
  2513.     
  2514.     def find_all(self):
  2515.         '''Return all items.'''
  2516.         return self.find('all')
  2517.  
  2518.     
  2519.     def find_below(self, tagOrId):
  2520.         '''Return all items below TAGORID.'''
  2521.         return self.find('below', tagOrId)
  2522.  
  2523.     
  2524.     def find_closest(self, x, y, halo = None, start = None):
  2525.         '''Return item which is closest to pixel at X, Y.
  2526.         If several match take the top-most.
  2527.         All items closer than HALO are considered overlapping (all are
  2528.         closests). If START is specified the next below this tag is taken.'''
  2529.         return self.find('closest', x, y, halo, start)
  2530.  
  2531.     
  2532.     def find_enclosed(self, x1, y1, x2, y2):
  2533.         '''Return all items in rectangle defined
  2534.         by X1,Y1,X2,Y2.'''
  2535.         return self.find('enclosed', x1, y1, x2, y2)
  2536.  
  2537.     
  2538.     def find_overlapping(self, x1, y1, x2, y2):
  2539.         '''Return all items which overlap the rectangle
  2540.         defined by X1,Y1,X2,Y2.'''
  2541.         return self.find('overlapping', x1, y1, x2, y2)
  2542.  
  2543.     
  2544.     def find_withtag(self, tagOrId):
  2545.         '''Return all items with TAGORID.'''
  2546.         return self.find('withtag', tagOrId)
  2547.  
  2548.     
  2549.     def focus(self, *args):
  2550.         '''Set focus to the first item specified in ARGS.'''
  2551.         return self.tk.call((self._w, 'focus') + args)
  2552.  
  2553.     
  2554.     def gettags(self, *args):
  2555.         '''Return tags associated with the first item specified in ARGS.'''
  2556.         return self.tk.splitlist(self.tk.call((self._w, 'gettags') + args))
  2557.  
  2558.     
  2559.     def icursor(self, *args):
  2560.         '''Set cursor at position POS in the item identified by TAGORID.
  2561.         In ARGS TAGORID must be first.'''
  2562.         self.tk.call((self._w, 'icursor') + args)
  2563.  
  2564.     
  2565.     def index(self, *args):
  2566.         '''Return position of cursor as integer in item specified in ARGS.'''
  2567.         return getint(self.tk.call((self._w, 'index') + args))
  2568.  
  2569.     
  2570.     def insert(self, *args):
  2571.         '''Insert TEXT in item TAGORID at position POS. ARGS must
  2572.         be TAGORID POS TEXT.'''
  2573.         self.tk.call((self._w, 'insert') + args)
  2574.  
  2575.     
  2576.     def itemcget(self, tagOrId, option):
  2577.         '''Return the resource value for an OPTION for item TAGORID.'''
  2578.         return self.tk.call((self._w, 'itemcget') + (tagOrId, '-' + option))
  2579.  
  2580.     
  2581.     def itemconfigure(self, tagOrId, cnf = None, **kw):
  2582.         '''Configure resources of an item TAGORID.
  2583.  
  2584.         The values for resources are specified as keyword
  2585.         arguments. To get an overview about
  2586.         the allowed keyword arguments call the method without arguments.
  2587.         '''
  2588.         if cnf is None and not kw:
  2589.             cnf = { }
  2590.             for x in self.tk.split(self.tk.call(self._w, 'itemconfigure', tagOrId)):
  2591.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  2592.             
  2593.             return cnf
  2594.         
  2595.         if type(cnf) == StringType and not kw:
  2596.             x = self.tk.split(self.tk.call(self._w, 'itemconfigure', tagOrId, '-' + cnf))
  2597.             return (x[0][1:],) + x[1:]
  2598.         
  2599.         self.tk.call((self._w, 'itemconfigure', tagOrId) + self._options(cnf, kw))
  2600.  
  2601.     itemconfig = itemconfigure
  2602.     
  2603.     def tag_lower(self, *args):
  2604.         '''Lower an item TAGORID given in ARGS
  2605.         (optional below another item).'''
  2606.         self.tk.call((self._w, 'lower') + args)
  2607.  
  2608.     lower = tag_lower
  2609.     
  2610.     def move(self, *args):
  2611.         '''Move an item TAGORID given in ARGS.'''
  2612.         self.tk.call((self._w, 'move') + args)
  2613.  
  2614.     
  2615.     def postscript(self, cnf = { }, **kw):
  2616.         '''Print the contents of the canvas to a postscript
  2617.         file. Valid options: colormap, colormode, file, fontmap,
  2618.         height, pageanchor, pageheight, pagewidth, pagex, pagey,
  2619.         rotate, witdh, x, y.'''
  2620.         return self.tk.call((self._w, 'postscript') + self._options(cnf, kw))
  2621.  
  2622.     
  2623.     def tag_raise(self, *args):
  2624.         '''Raise an item TAGORID given in ARGS
  2625.         (optional above another item).'''
  2626.         self.tk.call((self._w, 'raise') + args)
  2627.  
  2628.     lift = tkraise = tag_raise
  2629.     
  2630.     def scale(self, *args):
  2631.         '''Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.'''
  2632.         self.tk.call((self._w, 'scale') + args)
  2633.  
  2634.     
  2635.     def scan_mark(self, x, y):
  2636.         '''Remember the current X, Y coordinates.'''
  2637.         self.tk.call(self._w, 'scan', 'mark', x, y)
  2638.  
  2639.     
  2640.     def scan_dragto(self, x, y):
  2641.         '''Adjust the view of the canvas to 10 times the
  2642.         difference between X and Y and the coordinates given in
  2643.         scan_mark.'''
  2644.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  2645.  
  2646.     
  2647.     def select_adjust(self, tagOrId, index):
  2648.         '''Adjust the end of the selection near the cursor of an item TAGORID to index.'''
  2649.         self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  2650.  
  2651.     
  2652.     def select_clear(self):
  2653.         '''Clear the selection if it is in this widget.'''
  2654.         self.tk.call(self._w, 'select', 'clear')
  2655.  
  2656.     
  2657.     def select_from(self, tagOrId, index):
  2658.         '''Set the fixed end of a selection in item TAGORID to INDEX.'''
  2659.         self.tk.call(self._w, 'select', 'from', tagOrId, index)
  2660.  
  2661.     
  2662.     def select_item(self):
  2663.         '''Return the item which has the selection.'''
  2664.         self.tk.call(self._w, 'select', 'item')
  2665.  
  2666.     
  2667.     def select_to(self, tagOrId, index):
  2668.         '''Set the variable end of a selection in item TAGORID to INDEX.'''
  2669.         self.tk.call(self._w, 'select', 'to', tagOrId, index)
  2670.  
  2671.     
  2672.     def type(self, tagOrId):
  2673.         '''Return the type of the item TAGORID.'''
  2674.         if not self.tk.call(self._w, 'type', tagOrId):
  2675.             pass
  2676.         return None
  2677.  
  2678.     
  2679.     def xview(self, *args):
  2680.         '''Query and change horizontal position of the view.'''
  2681.         if not args:
  2682.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  2683.         
  2684.         self.tk.call((self._w, 'xview') + args)
  2685.  
  2686.     
  2687.     def xview_moveto(self, fraction):
  2688.         '''Adjusts the view in the window so that FRACTION of the
  2689.         total width of the canvas is off-screen to the left.'''
  2690.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2691.  
  2692.     
  2693.     def xview_scroll(self, number, what):
  2694.         '''Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).'''
  2695.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2696.  
  2697.     
  2698.     def yview(self, *args):
  2699.         '''Query and change vertical position of the view.'''
  2700.         if not args:
  2701.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  2702.         
  2703.         self.tk.call((self._w, 'yview') + args)
  2704.  
  2705.     
  2706.     def yview_moveto(self, fraction):
  2707.         '''Adjusts the view in the window so that FRACTION of the
  2708.         total height of the canvas is off-screen to the top.'''
  2709.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  2710.  
  2711.     
  2712.     def yview_scroll(self, number, what):
  2713.         '''Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).'''
  2714.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  2715.  
  2716.  
  2717.  
  2718. class Checkbutton(Widget):
  2719.     '''Checkbutton widget which is either in on- or off-state.'''
  2720.     
  2721.     def __init__(self, master = None, cnf = { }, **kw):
  2722.         '''Construct a checkbutton widget with the parent MASTER.
  2723.  
  2724.         Valid resource names: activebackground, activeforeground, anchor,
  2725.         background, bd, bg, bitmap, borderwidth, command, cursor,
  2726.         disabledforeground, fg, font, foreground, height,
  2727.         highlightbackground, highlightcolor, highlightthickness, image,
  2728.         indicatoron, justify, offvalue, onvalue, padx, pady, relief,
  2729.         selectcolor, selectimage, state, takefocus, text, textvariable,
  2730.         underline, variable, width, wraplength.'''
  2731.         Widget.__init__(self, master, 'checkbutton', cnf, kw)
  2732.  
  2733.     
  2734.     def deselect(self):
  2735.         '''Put the button in off-state.'''
  2736.         self.tk.call(self._w, 'deselect')
  2737.  
  2738.     
  2739.     def flash(self):
  2740.         '''Flash the button.'''
  2741.         self.tk.call(self._w, 'flash')
  2742.  
  2743.     
  2744.     def invoke(self):
  2745.         '''Toggle the button and invoke a command if given as resource.'''
  2746.         return self.tk.call(self._w, 'invoke')
  2747.  
  2748.     
  2749.     def select(self):
  2750.         '''Put the button in on-state.'''
  2751.         self.tk.call(self._w, 'select')
  2752.  
  2753.     
  2754.     def toggle(self):
  2755.         '''Toggle the button.'''
  2756.         self.tk.call(self._w, 'toggle')
  2757.  
  2758.  
  2759.  
  2760. class Entry(Widget):
  2761.     '''Entry widget which allows to display simple text.'''
  2762.     
  2763.     def __init__(self, master = None, cnf = { }, **kw):
  2764.         '''Construct an entry widget with the parent MASTER.
  2765.  
  2766.         Valid resource names: background, bd, bg, borderwidth, cursor,
  2767.         exportselection, fg, font, foreground, highlightbackground,
  2768.         highlightcolor, highlightthickness, insertbackground,
  2769.         insertborderwidth, insertofftime, insertontime, insertwidth,
  2770.         invalidcommand, invcmd, justify, relief, selectbackground,
  2771.         selectborderwidth, selectforeground, show, state, takefocus,
  2772.         textvariable, validate, validatecommand, vcmd, width,
  2773.         xscrollcommand.'''
  2774.         Widget.__init__(self, master, 'entry', cnf, kw)
  2775.  
  2776.     
  2777.     def delete(self, first, last = None):
  2778.         '''Delete text from FIRST to LAST (not included).'''
  2779.         self.tk.call(self._w, 'delete', first, last)
  2780.  
  2781.     
  2782.     def get(self):
  2783.         '''Return the text.'''
  2784.         return self.tk.call(self._w, 'get')
  2785.  
  2786.     
  2787.     def icursor(self, index):
  2788.         '''Insert cursor at INDEX.'''
  2789.         self.tk.call(self._w, 'icursor', index)
  2790.  
  2791.     
  2792.     def index(self, index):
  2793.         '''Return position of cursor.'''
  2794.         return getint(self.tk.call(self._w, 'index', index))
  2795.  
  2796.     
  2797.     def insert(self, index, string):
  2798.         '''Insert STRING at INDEX.'''
  2799.         self.tk.call(self._w, 'insert', index, string)
  2800.  
  2801.     
  2802.     def scan_mark(self, x):
  2803.         '''Remember the current X, Y coordinates.'''
  2804.         self.tk.call(self._w, 'scan', 'mark', x)
  2805.  
  2806.     
  2807.     def scan_dragto(self, x):
  2808.         '''Adjust the view of the canvas to 10 times the
  2809.         difference between X and Y and the coordinates given in
  2810.         scan_mark.'''
  2811.         self.tk.call(self._w, 'scan', 'dragto', x)
  2812.  
  2813.     
  2814.     def selection_adjust(self, index):
  2815.         '''Adjust the end of the selection near the cursor to INDEX.'''
  2816.         self.tk.call(self._w, 'selection', 'adjust', index)
  2817.  
  2818.     select_adjust = selection_adjust
  2819.     
  2820.     def selection_clear(self):
  2821.         '''Clear the selection if it is in this widget.'''
  2822.         self.tk.call(self._w, 'selection', 'clear')
  2823.  
  2824.     select_clear = selection_clear
  2825.     
  2826.     def selection_from(self, index):
  2827.         '''Set the fixed end of a selection to INDEX.'''
  2828.         self.tk.call(self._w, 'selection', 'from', index)
  2829.  
  2830.     select_from = selection_from
  2831.     
  2832.     def selection_present(self):
  2833.         '''Return whether the widget has the selection.'''
  2834.         return self.tk.getboolean(self.tk.call(self._w, 'selection', 'present'))
  2835.  
  2836.     select_present = selection_present
  2837.     
  2838.     def selection_range(self, start, end):
  2839.         '''Set the selection from START to END (not included).'''
  2840.         self.tk.call(self._w, 'selection', 'range', start, end)
  2841.  
  2842.     select_range = selection_range
  2843.     
  2844.     def selection_to(self, index):
  2845.         '''Set the variable end of a selection to INDEX.'''
  2846.         self.tk.call(self._w, 'selection', 'to', index)
  2847.  
  2848.     select_to = selection_to
  2849.     
  2850.     def xview(self, index):
  2851.         '''Query and change horizontal position of the view.'''
  2852.         self.tk.call(self._w, 'xview', index)
  2853.  
  2854.     
  2855.     def xview_moveto(self, fraction):
  2856.         '''Adjust the view in the window so that FRACTION of the
  2857.         total width of the entry is off-screen to the left.'''
  2858.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  2859.  
  2860.     
  2861.     def xview_scroll(self, number, what):
  2862.         '''Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).'''
  2863.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  2864.  
  2865.  
  2866.  
  2867. class Frame(Widget):
  2868.     '''Frame widget which may contain other widgets and can have a 3D border.'''
  2869.     
  2870.     def __init__(self, master = None, cnf = { }, **kw):
  2871.         '''Construct a frame widget with the parent MASTER.
  2872.  
  2873.         Valid resource names: background, bd, bg, borderwidth, class,
  2874.         colormap, container, cursor, height, highlightbackground,
  2875.         highlightcolor, highlightthickness, relief, takefocus, visual, width.'''
  2876.         cnf = _cnfmerge((cnf, kw))
  2877.         extra = ()
  2878.         if cnf.has_key('class_'):
  2879.             extra = ('-class', cnf['class_'])
  2880.             del cnf['class_']
  2881.         elif cnf.has_key('class'):
  2882.             extra = ('-class', cnf['class'])
  2883.             del cnf['class']
  2884.         
  2885.         Widget.__init__(self, master, 'frame', cnf, { }, extra)
  2886.  
  2887.  
  2888.  
  2889. class Label(Widget):
  2890.     '''Label widget which can display text and bitmaps.'''
  2891.     
  2892.     def __init__(self, master = None, cnf = { }, **kw):
  2893.         '''Construct a label widget with the parent MASTER.
  2894.  
  2895.         Valid resource names: anchor, background, bd, bg, bitmap,
  2896.         borderwidth, cursor, fg, font, foreground, height,
  2897.         highlightbackground, highlightcolor, highlightthickness, image,
  2898.         justify, padx, pady, relief, takefocus, text, textvariable,
  2899.         underline, width, wraplength.'''
  2900.         Widget.__init__(self, master, 'label', cnf, kw)
  2901.  
  2902.  
  2903.  
  2904. class Listbox(Widget):
  2905.     '''Listbox widget which can display a list of strings.'''
  2906.     
  2907.     def __init__(self, master = None, cnf = { }, **kw):
  2908.         '''Construct a listbox widget with the parent MASTER.
  2909.  
  2910.         Valid resource names: background, bd, bg, borderwidth, cursor,
  2911.         exportselection, fg, font, foreground, height, highlightbackground,
  2912.         highlightcolor, highlightthickness, relief, selectbackground,
  2913.         selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
  2914.         width, xscrollcommand, yscrollcommand, listvariable.'''
  2915.         Widget.__init__(self, master, 'listbox', cnf, kw)
  2916.  
  2917.     
  2918.     def activate(self, index):
  2919.         '''Activate item identified by INDEX.'''
  2920.         self.tk.call(self._w, 'activate', index)
  2921.  
  2922.     
  2923.     def bbox(self, *args):
  2924.         '''Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2925.         which encloses the item identified by index in ARGS.'''
  2926.         if not self._getints(self.tk.call((self._w, 'bbox') + args)):
  2927.             pass
  2928.         return None
  2929.  
  2930.     
  2931.     def curselection(self):
  2932.         '''Return list of indices of currently selected item.'''
  2933.         return self.tk.splitlist(self.tk.call(self._w, 'curselection'))
  2934.  
  2935.     
  2936.     def delete(self, first, last = None):
  2937.         '''Delete items from FIRST to LAST (not included).'''
  2938.         self.tk.call(self._w, 'delete', first, last)
  2939.  
  2940.     
  2941.     def get(self, first, last = None):
  2942.         '''Get list of items from FIRST to LAST (not included).'''
  2943.         if last:
  2944.             return self.tk.splitlist(self.tk.call(self._w, 'get', first, last))
  2945.         else:
  2946.             return self.tk.call(self._w, 'get', first)
  2947.  
  2948.     
  2949.     def index(self, index):
  2950.         '''Return index of item identified with INDEX.'''
  2951.         i = self.tk.call(self._w, 'index', index)
  2952.         if i == 'none':
  2953.             return None
  2954.         
  2955.         return getint(i)
  2956.  
  2957.     
  2958.     def insert(self, index, *elements):
  2959.         '''Insert ELEMENTS at INDEX.'''
  2960.         self.tk.call((self._w, 'insert', index) + elements)
  2961.  
  2962.     
  2963.     def nearest(self, y):
  2964.         '''Get index of item which is nearest to y coordinate Y.'''
  2965.         return getint(self.tk.call(self._w, 'nearest', y))
  2966.  
  2967.     
  2968.     def scan_mark(self, x, y):
  2969.         '''Remember the current X, Y coordinates.'''
  2970.         self.tk.call(self._w, 'scan', 'mark', x, y)
  2971.  
  2972.     
  2973.     def scan_dragto(self, x, y):
  2974.         '''Adjust the view of the listbox to 10 times the
  2975.         difference between X and Y and the coordinates given in
  2976.         scan_mark.'''
  2977.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  2978.  
  2979.     
  2980.     def see(self, index):
  2981.         '''Scroll such that INDEX is visible.'''
  2982.         self.tk.call(self._w, 'see', index)
  2983.  
  2984.     
  2985.     def selection_anchor(self, index):
  2986.         '''Set the fixed end oft the selection to INDEX.'''
  2987.         self.tk.call(self._w, 'selection', 'anchor', index)
  2988.  
  2989.     select_anchor = selection_anchor
  2990.     
  2991.     def selection_clear(self, first, last = None):
  2992.         '''Clear the selection from FIRST to LAST (not included).'''
  2993.         self.tk.call(self._w, 'selection', 'clear', first, last)
  2994.  
  2995.     select_clear = selection_clear
  2996.     
  2997.     def selection_includes(self, index):
  2998.         '''Return 1 if INDEX is part of the selection.'''
  2999.         return self.tk.getboolean(self.tk.call(self._w, 'selection', 'includes', index))
  3000.  
  3001.     select_includes = selection_includes
  3002.     
  3003.     def selection_set(self, first, last = None):
  3004.         '''Set the selection from FIRST to LAST (not included) without
  3005.         changing the currently selected elements.'''
  3006.         self.tk.call(self._w, 'selection', 'set', first, last)
  3007.  
  3008.     select_set = selection_set
  3009.     
  3010.     def size(self):
  3011.         '''Return the number of elements in the listbox.'''
  3012.         return getint(self.tk.call(self._w, 'size'))
  3013.  
  3014.     
  3015.     def xview(self, *what):
  3016.         '''Query and change horizontal position of the view.'''
  3017.         if not what:
  3018.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  3019.         
  3020.         self.tk.call((self._w, 'xview') + what)
  3021.  
  3022.     
  3023.     def xview_moveto(self, fraction):
  3024.         '''Adjust the view in the window so that FRACTION of the
  3025.         total width of the entry is off-screen to the left.'''
  3026.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  3027.  
  3028.     
  3029.     def xview_scroll(self, number, what):
  3030.         '''Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).'''
  3031.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  3032.  
  3033.     
  3034.     def yview(self, *what):
  3035.         '''Query and change vertical position of the view.'''
  3036.         if not what:
  3037.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  3038.         
  3039.         self.tk.call((self._w, 'yview') + what)
  3040.  
  3041.     
  3042.     def yview_moveto(self, fraction):
  3043.         '''Adjust the view in the window so that FRACTION of the
  3044.         total width of the entry is off-screen to the top.'''
  3045.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  3046.  
  3047.     
  3048.     def yview_scroll(self, number, what):
  3049.         '''Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).'''
  3050.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  3051.  
  3052.     
  3053.     def itemcget(self, index, option):
  3054.         '''Return the resource value for an ITEM and an OPTION.'''
  3055.         return self.tk.call((self._w, 'itemcget') + (index, '-' + option))
  3056.  
  3057.     
  3058.     def itemconfigure(self, index, cnf = None, **kw):
  3059.         '''Configure resources of an ITEM.
  3060.  
  3061.         The values for resources are specified as keyword arguments.
  3062.         To get an overview about the allowed keyword arguments
  3063.         call the method without arguments.
  3064.         Valid resource names: background, bg, foreground, fg,
  3065.         selectbackground, selectforeground.'''
  3066.         if cnf is None and not kw:
  3067.             cnf = { }
  3068.             for x in self.tk.split(self.tk.call(self._w, 'itemconfigure', index)):
  3069.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  3070.             
  3071.             return cnf
  3072.         
  3073.         if type(cnf) == StringType and not kw:
  3074.             x = self.tk.split(self.tk.call(self._w, 'itemconfigure', index, '-' + cnf))
  3075.             return (x[0][1:],) + x[1:]
  3076.         
  3077.         self.tk.call((self._w, 'itemconfigure', index) + self._options(cnf, kw))
  3078.  
  3079.     itemconfig = itemconfigure
  3080.  
  3081.  
  3082. class Menu(Widget):
  3083.     '''Menu widget which allows to display menu bars, pull-down menus and pop-up menus.'''
  3084.     
  3085.     def __init__(self, master = None, cnf = { }, **kw):
  3086.         '''Construct menu widget with the parent MASTER.
  3087.  
  3088.         Valid resource names: activebackground, activeborderwidth,
  3089.         activeforeground, background, bd, bg, borderwidth, cursor,
  3090.         disabledforeground, fg, font, foreground, postcommand, relief,
  3091.         selectcolor, takefocus, tearoff, tearoffcommand, title, type.'''
  3092.         Widget.__init__(self, master, 'menu', cnf, kw)
  3093.  
  3094.     
  3095.     def tk_bindForTraversal(self):
  3096.         pass
  3097.  
  3098.     
  3099.     def tk_mbPost(self):
  3100.         self.tk.call('tk_mbPost', self._w)
  3101.  
  3102.     
  3103.     def tk_mbUnpost(self):
  3104.         self.tk.call('tk_mbUnpost')
  3105.  
  3106.     
  3107.     def tk_traverseToMenu(self, char):
  3108.         self.tk.call('tk_traverseToMenu', self._w, char)
  3109.  
  3110.     
  3111.     def tk_traverseWithinMenu(self, char):
  3112.         self.tk.call('tk_traverseWithinMenu', self._w, char)
  3113.  
  3114.     
  3115.     def tk_getMenuButtons(self):
  3116.         return self.tk.call('tk_getMenuButtons', self._w)
  3117.  
  3118.     
  3119.     def tk_nextMenu(self, count):
  3120.         self.tk.call('tk_nextMenu', count)
  3121.  
  3122.     
  3123.     def tk_nextMenuEntry(self, count):
  3124.         self.tk.call('tk_nextMenuEntry', count)
  3125.  
  3126.     
  3127.     def tk_invokeMenu(self):
  3128.         self.tk.call('tk_invokeMenu', self._w)
  3129.  
  3130.     
  3131.     def tk_firstMenu(self):
  3132.         self.tk.call('tk_firstMenu', self._w)
  3133.  
  3134.     
  3135.     def tk_mbButtonDown(self):
  3136.         self.tk.call('tk_mbButtonDown', self._w)
  3137.  
  3138.     
  3139.     def tk_popup(self, x, y, entry = ''):
  3140.         '''Post the menu at position X,Y with entry ENTRY.'''
  3141.         self.tk.call('tk_popup', self._w, x, y, entry)
  3142.  
  3143.     
  3144.     def activate(self, index):
  3145.         '''Activate entry at INDEX.'''
  3146.         self.tk.call(self._w, 'activate', index)
  3147.  
  3148.     
  3149.     def add(self, itemType, cnf = { }, **kw):
  3150.         '''Internal function.'''
  3151.         self.tk.call((self._w, 'add', itemType) + self._options(cnf, kw))
  3152.  
  3153.     
  3154.     def add_cascade(self, cnf = { }, **kw):
  3155.         '''Add hierarchical menu item.'''
  3156.         if not cnf:
  3157.             pass
  3158.         self.add('cascade', kw)
  3159.  
  3160.     
  3161.     def add_checkbutton(self, cnf = { }, **kw):
  3162.         '''Add checkbutton menu item.'''
  3163.         if not cnf:
  3164.             pass
  3165.         self.add('checkbutton', kw)
  3166.  
  3167.     
  3168.     def add_command(self, cnf = { }, **kw):
  3169.         '''Add command menu item.'''
  3170.         if not cnf:
  3171.             pass
  3172.         self.add('command', kw)
  3173.  
  3174.     
  3175.     def add_radiobutton(self, cnf = { }, **kw):
  3176.         '''Addd radio menu item.'''
  3177.         if not cnf:
  3178.             pass
  3179.         self.add('radiobutton', kw)
  3180.  
  3181.     
  3182.     def add_separator(self, cnf = { }, **kw):
  3183.         '''Add separator.'''
  3184.         if not cnf:
  3185.             pass
  3186.         self.add('separator', kw)
  3187.  
  3188.     
  3189.     def insert(self, index, itemType, cnf = { }, **kw):
  3190.         '''Internal function.'''
  3191.         self.tk.call((self._w, 'insert', index, itemType) + self._options(cnf, kw))
  3192.  
  3193.     
  3194.     def insert_cascade(self, index, cnf = { }, **kw):
  3195.         '''Add hierarchical menu item at INDEX.'''
  3196.         if not cnf:
  3197.             pass
  3198.         self.insert(index, 'cascade', kw)
  3199.  
  3200.     
  3201.     def insert_checkbutton(self, index, cnf = { }, **kw):
  3202.         '''Add checkbutton menu item at INDEX.'''
  3203.         if not cnf:
  3204.             pass
  3205.         self.insert(index, 'checkbutton', kw)
  3206.  
  3207.     
  3208.     def insert_command(self, index, cnf = { }, **kw):
  3209.         '''Add command menu item at INDEX.'''
  3210.         if not cnf:
  3211.             pass
  3212.         self.insert(index, 'command', kw)
  3213.  
  3214.     
  3215.     def insert_radiobutton(self, index, cnf = { }, **kw):
  3216.         '''Addd radio menu item at INDEX.'''
  3217.         if not cnf:
  3218.             pass
  3219.         self.insert(index, 'radiobutton', kw)
  3220.  
  3221.     
  3222.     def insert_separator(self, index, cnf = { }, **kw):
  3223.         '''Add separator at INDEX.'''
  3224.         if not cnf:
  3225.             pass
  3226.         self.insert(index, 'separator', kw)
  3227.  
  3228.     
  3229.     def delete(self, index1, index2 = None):
  3230.         '''Delete menu items between INDEX1 and INDEX2 (not included).'''
  3231.         self.tk.call(self._w, 'delete', index1, index2)
  3232.  
  3233.     
  3234.     def entrycget(self, index, option):
  3235.         '''Return the resource value of an menu item for OPTION at INDEX.'''
  3236.         return self.tk.call(self._w, 'entrycget', index, '-' + option)
  3237.  
  3238.     
  3239.     def entryconfigure(self, index, cnf = None, **kw):
  3240.         '''Configure a menu item at INDEX.'''
  3241.         if cnf is None and not kw:
  3242.             cnf = { }
  3243.             for x in self.tk.split(self.tk.call((self._w, 'entryconfigure', index))):
  3244.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  3245.             
  3246.             return cnf
  3247.         
  3248.         if type(cnf) == StringType and not kw:
  3249.             x = self.tk.split(self.tk.call((self._w, 'entryconfigure', index, '-' + cnf)))
  3250.             return (x[0][1:],) + x[1:]
  3251.         
  3252.         self.tk.call((self._w, 'entryconfigure', index) + self._options(cnf, kw))
  3253.  
  3254.     entryconfig = entryconfigure
  3255.     
  3256.     def index(self, index):
  3257.         '''Return the index of a menu item identified by INDEX.'''
  3258.         i = self.tk.call(self._w, 'index', index)
  3259.         if i == 'none':
  3260.             return None
  3261.         
  3262.         return getint(i)
  3263.  
  3264.     
  3265.     def invoke(self, index):
  3266.         '''Invoke a menu item identified by INDEX and execute
  3267.         the associated command.'''
  3268.         return self.tk.call(self._w, 'invoke', index)
  3269.  
  3270.     
  3271.     def post(self, x, y):
  3272.         '''Display a menu at position X,Y.'''
  3273.         self.tk.call(self._w, 'post', x, y)
  3274.  
  3275.     
  3276.     def type(self, index):
  3277.         '''Return the type of the menu item at INDEX.'''
  3278.         return self.tk.call(self._w, 'type', index)
  3279.  
  3280.     
  3281.     def unpost(self):
  3282.         '''Unmap a menu.'''
  3283.         self.tk.call(self._w, 'unpost')
  3284.  
  3285.     
  3286.     def yposition(self, index):
  3287.         '''Return the y-position of the topmost pixel of the menu item at INDEX.'''
  3288.         return getint(self.tk.call(self._w, 'yposition', index))
  3289.  
  3290.  
  3291.  
  3292. class Menubutton(Widget):
  3293.     '''Menubutton widget, obsolete since Tk8.0.'''
  3294.     
  3295.     def __init__(self, master = None, cnf = { }, **kw):
  3296.         Widget.__init__(self, master, 'menubutton', cnf, kw)
  3297.  
  3298.  
  3299.  
  3300. class Message(Widget):
  3301.     '''Message widget to display multiline text. Obsolete since Label does it too.'''
  3302.     
  3303.     def __init__(self, master = None, cnf = { }, **kw):
  3304.         Widget.__init__(self, master, 'message', cnf, kw)
  3305.  
  3306.  
  3307.  
  3308. class Radiobutton(Widget):
  3309.     '''Radiobutton widget which shows only one of several buttons in on-state.'''
  3310.     
  3311.     def __init__(self, master = None, cnf = { }, **kw):
  3312.         '''Construct a radiobutton widget with the parent MASTER.
  3313.  
  3314.         Valid resource names: activebackground, activeforeground, anchor,
  3315.         background, bd, bg, bitmap, borderwidth, command, cursor,
  3316.         disabledforeground, fg, font, foreground, height,
  3317.         highlightbackground, highlightcolor, highlightthickness, image,
  3318.         indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
  3319.         state, takefocus, text, textvariable, underline, value, variable,
  3320.         width, wraplength.'''
  3321.         Widget.__init__(self, master, 'radiobutton', cnf, kw)
  3322.  
  3323.     
  3324.     def deselect(self):
  3325.         '''Put the button in off-state.'''
  3326.         self.tk.call(self._w, 'deselect')
  3327.  
  3328.     
  3329.     def flash(self):
  3330.         '''Flash the button.'''
  3331.         self.tk.call(self._w, 'flash')
  3332.  
  3333.     
  3334.     def invoke(self):
  3335.         '''Toggle the button and invoke a command if given as resource.'''
  3336.         return self.tk.call(self._w, 'invoke')
  3337.  
  3338.     
  3339.     def select(self):
  3340.         '''Put the button in on-state.'''
  3341.         self.tk.call(self._w, 'select')
  3342.  
  3343.  
  3344.  
  3345. class Scale(Widget):
  3346.     '''Scale widget which can display a numerical scale.'''
  3347.     
  3348.     def __init__(self, master = None, cnf = { }, **kw):
  3349.         '''Construct a scale widget with the parent MASTER.
  3350.  
  3351.         Valid resource names: activebackground, background, bigincrement, bd,
  3352.         bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
  3353.         highlightbackground, highlightcolor, highlightthickness, label,
  3354.         length, orient, relief, repeatdelay, repeatinterval, resolution,
  3355.         showvalue, sliderlength, sliderrelief, state, takefocus,
  3356.         tickinterval, to, troughcolor, variable, width.'''
  3357.         Widget.__init__(self, master, 'scale', cnf, kw)
  3358.  
  3359.     
  3360.     def get(self):
  3361.         '''Get the current value as integer or float.'''
  3362.         value = self.tk.call(self._w, 'get')
  3363.         
  3364.         try:
  3365.             return getint(value)
  3366.         except ValueError:
  3367.             return getdouble(value)
  3368.  
  3369.  
  3370.     
  3371.     def set(self, value):
  3372.         '''Set the value to VALUE.'''
  3373.         self.tk.call(self._w, 'set', value)
  3374.  
  3375.     
  3376.     def coords(self, value = None):
  3377.         '''Return a tuple (X,Y) of the point along the centerline of the
  3378.         trough that corresponds to VALUE or the current value if None is
  3379.         given.'''
  3380.         return self._getints(self.tk.call(self._w, 'coords', value))
  3381.  
  3382.     
  3383.     def identify(self, x, y):
  3384.         '''Return where the point X,Y lies. Valid return values are "slider",
  3385.         "though1" and "though2".'''
  3386.         return self.tk.call(self._w, 'identify', x, y)
  3387.  
  3388.  
  3389.  
  3390. class Scrollbar(Widget):
  3391.     '''Scrollbar widget which displays a slider at a certain position.'''
  3392.     
  3393.     def __init__(self, master = None, cnf = { }, **kw):
  3394.         '''Construct a scrollbar widget with the parent MASTER.
  3395.  
  3396.         Valid resource names: activebackground, activerelief,
  3397.         background, bd, bg, borderwidth, command, cursor,
  3398.         elementborderwidth, highlightbackground,
  3399.         highlightcolor, highlightthickness, jump, orient,
  3400.         relief, repeatdelay, repeatinterval, takefocus,
  3401.         troughcolor, width.'''
  3402.         Widget.__init__(self, master, 'scrollbar', cnf, kw)
  3403.  
  3404.     
  3405.     def activate(self, index):
  3406.         '''Display the element at INDEX with activebackground and activerelief.
  3407.         INDEX can be "arrow1","slider" or "arrow2".'''
  3408.         self.tk.call(self._w, 'activate', index)
  3409.  
  3410.     
  3411.     def delta(self, deltax, deltay):
  3412.         '''Return the fractional change of the scrollbar setting if it
  3413.         would be moved by DELTAX or DELTAY pixels.'''
  3414.         return getdouble(self.tk.call(self._w, 'delta', deltax, deltay))
  3415.  
  3416.     
  3417.     def fraction(self, x, y):
  3418.         '''Return the fractional value which corresponds to a slider
  3419.         position of X,Y.'''
  3420.         return getdouble(self.tk.call(self._w, 'fraction', x, y))
  3421.  
  3422.     
  3423.     def identify(self, x, y):
  3424.         '''Return the element under position X,Y as one of
  3425.         "arrow1","slider","arrow2" or "".'''
  3426.         return self.tk.call(self._w, 'identify', x, y)
  3427.  
  3428.     
  3429.     def get(self):
  3430.         '''Return the current fractional values (upper and lower end)
  3431.         of the slider position.'''
  3432.         return self._getdoubles(self.tk.call(self._w, 'get'))
  3433.  
  3434.     
  3435.     def set(self, *args):
  3436.         '''Set the fractional values of the slider position (upper and
  3437.         lower ends as value between 0 and 1).'''
  3438.         self.tk.call((self._w, 'set') + args)
  3439.  
  3440.  
  3441.  
  3442. class Text(Widget):
  3443.     '''Text widget which can display text in various forms.'''
  3444.     
  3445.     def __init__(self, master = None, cnf = { }, **kw):
  3446.         '''Construct a text widget with the parent MASTER.
  3447.  
  3448.         Valid resource names: background, bd, bg, borderwidth, cursor,
  3449.         exportselection, fg, font, foreground, height,
  3450.         highlightbackground, highlightcolor, highlightthickness,
  3451.         insertbackground, insertborderwidth, insertofftime,
  3452.         insertontime, insertwidth, padx, pady, relief,
  3453.         selectbackground, selectborderwidth, selectforeground,
  3454.         setgrid, spacing1, spacing2, spacing3, state, tabs, takefocus,
  3455.         width, wrap, xscrollcommand, yscrollcommand.'''
  3456.         Widget.__init__(self, master, 'text', cnf, kw)
  3457.  
  3458.     
  3459.     def bbox(self, *args):
  3460.         '''Return a tuple of (x,y,width,height) which gives the bounding
  3461.         box of the visible part of the character at the index in ARGS.'''
  3462.         if not self._getints(self.tk.call((self._w, 'bbox') + args)):
  3463.             pass
  3464.         return None
  3465.  
  3466.     
  3467.     def tk_textSelectTo(self, index):
  3468.         self.tk.call('tk_textSelectTo', self._w, index)
  3469.  
  3470.     
  3471.     def tk_textBackspace(self):
  3472.         self.tk.call('tk_textBackspace', self._w)
  3473.  
  3474.     
  3475.     def tk_textIndexCloser(self, a, b, c):
  3476.         self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  3477.  
  3478.     
  3479.     def tk_textResetAnchor(self, index):
  3480.         self.tk.call('tk_textResetAnchor', self._w, index)
  3481.  
  3482.     
  3483.     def compare(self, index1, op, index2):
  3484.         '''Return whether between index INDEX1 and index INDEX2 the
  3485.         relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.'''
  3486.         return self.tk.getboolean(self.tk.call(self._w, 'compare', index1, op, index2))
  3487.  
  3488.     
  3489.     def debug(self, boolean = None):
  3490.         '''Turn on the internal consistency checks of the B-Tree inside the text
  3491.         widget according to BOOLEAN.'''
  3492.         return self.tk.getboolean(self.tk.call(self._w, 'debug', boolean))
  3493.  
  3494.     
  3495.     def delete(self, index1, index2 = None):
  3496.         '''Delete the characters between INDEX1 and INDEX2 (not included).'''
  3497.         self.tk.call(self._w, 'delete', index1, index2)
  3498.  
  3499.     
  3500.     def dlineinfo(self, index):
  3501.         '''Return tuple (x,y,width,height,baseline) giving the bounding box
  3502.         and baseline position of the visible part of the line containing
  3503.         the character at INDEX.'''
  3504.         return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  3505.  
  3506.     
  3507.     def get(self, index1, index2 = None):
  3508.         '''Return the text from INDEX1 to INDEX2 (not included).'''
  3509.         return self.tk.call(self._w, 'get', index1, index2)
  3510.  
  3511.     
  3512.     def image_cget(self, index, option):
  3513.         '''Return the value of OPTION of an embedded image at INDEX.'''
  3514.         if option[:1] != '-':
  3515.             option = '-' + option
  3516.         
  3517.         if option[-1:] == '_':
  3518.             option = option[:-1]
  3519.         
  3520.         return self.tk.call(self._w, 'image', 'cget', index, option)
  3521.  
  3522.     
  3523.     def image_configure(self, index, cnf = { }, **kw):
  3524.         '''Configure an embedded image at INDEX.'''
  3525.         if not cnf and not kw:
  3526.             cnf = { }
  3527.             for x in self.tk.split(self.tk.call(self._w, 'image', 'configure', index)):
  3528.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  3529.             
  3530.             return cnf
  3531.         
  3532.         apply(self.tk.call, (self._w, 'image', 'configure', index) + self._options(cnf, kw))
  3533.  
  3534.     
  3535.     def image_create(self, index, cnf = { }, **kw):
  3536.         '''Create an embedded image at INDEX.'''
  3537.         return apply(self.tk.call, (self._w, 'image', 'create', index) + self._options(cnf, kw))
  3538.  
  3539.     
  3540.     def image_names(self):
  3541.         '''Return all names of embedded images in this widget.'''
  3542.         return self.tk.call(self._w, 'image', 'names')
  3543.  
  3544.     
  3545.     def index(self, index):
  3546.         '''Return the index in the form line.char for INDEX.'''
  3547.         return self.tk.call(self._w, 'index', index)
  3548.  
  3549.     
  3550.     def insert(self, index, chars, *args):
  3551.         '''Insert CHARS before the characters at INDEX. An additional
  3552.         tag can be given in ARGS. Additional CHARS and tags can follow in ARGS.'''
  3553.         self.tk.call((self._w, 'insert', index, chars) + args)
  3554.  
  3555.     
  3556.     def mark_gravity(self, markName, direction = None):
  3557.         '''Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
  3558.         Return the current value if None is given for DIRECTION.'''
  3559.         return self.tk.call((self._w, 'mark', 'gravity', markName, direction))
  3560.  
  3561.     
  3562.     def mark_names(self):
  3563.         '''Return all mark names.'''
  3564.         return self.tk.splitlist(self.tk.call(self._w, 'mark', 'names'))
  3565.  
  3566.     
  3567.     def mark_set(self, markName, index):
  3568.         '''Set mark MARKNAME before the character at INDEX.'''
  3569.         self.tk.call(self._w, 'mark', 'set', markName, index)
  3570.  
  3571.     
  3572.     def mark_unset(self, *markNames):
  3573.         '''Delete all marks in MARKNAMES.'''
  3574.         self.tk.call((self._w, 'mark', 'unset') + markNames)
  3575.  
  3576.     
  3577.     def mark_next(self, index):
  3578.         '''Return the name of the next mark after INDEX.'''
  3579.         if not self.tk.call(self._w, 'mark', 'next', index):
  3580.             pass
  3581.         return None
  3582.  
  3583.     
  3584.     def mark_previous(self, index):
  3585.         '''Return the name of the previous mark before INDEX.'''
  3586.         if not self.tk.call(self._w, 'mark', 'previous', index):
  3587.             pass
  3588.         return None
  3589.  
  3590.     
  3591.     def scan_mark(self, x, y):
  3592.         '''Remember the current X, Y coordinates.'''
  3593.         self.tk.call(self._w, 'scan', 'mark', x, y)
  3594.  
  3595.     
  3596.     def scan_dragto(self, x, y):
  3597.         '''Adjust the view of the text to 10 times the
  3598.         difference between X and Y and the coordinates given in
  3599.         scan_mark.'''
  3600.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  3601.  
  3602.     
  3603.     def search(self, pattern, index, stopindex = None, forwards = None, backwards = None, exact = None, regexp = None, nocase = None, count = None):
  3604.         '''Search PATTERN beginning from INDEX until STOPINDEX.
  3605.         Return the index of the first character of a match or an empty string.'''
  3606.         args = [
  3607.             self._w,
  3608.             'search']
  3609.         if forwards:
  3610.             args.append('-forwards')
  3611.         
  3612.         if backwards:
  3613.             args.append('-backwards')
  3614.         
  3615.         if exact:
  3616.             args.append('-exact')
  3617.         
  3618.         if regexp:
  3619.             args.append('-regexp')
  3620.         
  3621.         if nocase:
  3622.             args.append('-nocase')
  3623.         
  3624.         if count:
  3625.             args.append('-count')
  3626.             args.append(count)
  3627.         
  3628.         if pattern[0] == '-':
  3629.             args.append('--')
  3630.         
  3631.         args.append(pattern)
  3632.         args.append(index)
  3633.         if stopindex:
  3634.             args.append(stopindex)
  3635.         
  3636.         return self.tk.call(tuple(args))
  3637.  
  3638.     
  3639.     def see(self, index):
  3640.         '''Scroll such that the character at INDEX is visible.'''
  3641.         self.tk.call(self._w, 'see', index)
  3642.  
  3643.     
  3644.     def tag_add(self, tagName, index1, *args):
  3645.         '''Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
  3646.         Additional pairs of indices may follow in ARGS.'''
  3647.         self.tk.call((self._w, 'tag', 'add', tagName, index1) + args)
  3648.  
  3649.     
  3650.     def tag_unbind(self, tagName, sequence, funcid = None):
  3651.         '''Unbind for all characters with TAGNAME for event SEQUENCE  the
  3652.         function identified with FUNCID.'''
  3653.         self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  3654.         if funcid:
  3655.             self.deletecommand(funcid)
  3656.         
  3657.  
  3658.     
  3659.     def tag_bind(self, tagName, sequence, func, add = None):
  3660.         '''Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
  3661.  
  3662.         An additional boolean parameter ADD specifies whether FUNC will be
  3663.         called additionally to the other bound function or whether it will
  3664.         replace the previous function. See bind for the return value.'''
  3665.         return self._bind((self._w, 'tag', 'bind', tagName), sequence, func, add)
  3666.  
  3667.     
  3668.     def tag_cget(self, tagName, option):
  3669.         '''Return the value of OPTION for tag TAGNAME.'''
  3670.         if option[:1] != '-':
  3671.             option = '-' + option
  3672.         
  3673.         if option[-1:] == '_':
  3674.             option = option[:-1]
  3675.         
  3676.         return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  3677.  
  3678.     
  3679.     def tag_configure(self, tagName, cnf = { }, **kw):
  3680.         '''Configure a tag TAGNAME.'''
  3681.         if type(cnf) == StringType:
  3682.             x = self.tk.split(self.tk.call(self._w, 'tag', 'configure', tagName, '-' + cnf))
  3683.             return (x[0][1:],) + x[1:]
  3684.         
  3685.         self.tk.call((self._w, 'tag', 'configure', tagName) + self._options(cnf, kw))
  3686.  
  3687.     tag_config = tag_configure
  3688.     
  3689.     def tag_delete(self, *tagNames):
  3690.         '''Delete all tags in TAGNAMES.'''
  3691.         self.tk.call((self._w, 'tag', 'delete') + tagNames)
  3692.  
  3693.     
  3694.     def tag_lower(self, tagName, belowThis = None):
  3695.         '''Change the priority of tag TAGNAME such that it is lower
  3696.         than the priority of BELOWTHIS.'''
  3697.         self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  3698.  
  3699.     
  3700.     def tag_names(self, index = None):
  3701.         '''Return a list of all tag names.'''
  3702.         return self.tk.splitlist(self.tk.call(self._w, 'tag', 'names', index))
  3703.  
  3704.     
  3705.     def tag_nextrange(self, tagName, index1, index2 = None):
  3706.         '''Return a list of start and end index for the first sequence of
  3707.         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3708.         The text is searched forward from INDEX1.'''
  3709.         return self.tk.splitlist(self.tk.call(self._w, 'tag', 'nextrange', tagName, index1, index2))
  3710.  
  3711.     
  3712.     def tag_prevrange(self, tagName, index1, index2 = None):
  3713.         '''Return a list of start and end index for the first sequence of
  3714.         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3715.         The text is searched backwards from INDEX1.'''
  3716.         return self.tk.splitlist(self.tk.call(self._w, 'tag', 'prevrange', tagName, index1, index2))
  3717.  
  3718.     
  3719.     def tag_raise(self, tagName, aboveThis = None):
  3720.         '''Change the priority of tag TAGNAME such that it is higher
  3721.         than the priority of ABOVETHIS.'''
  3722.         self.tk.call(self._w, 'tag', 'raise', tagName, aboveThis)
  3723.  
  3724.     
  3725.     def tag_ranges(self, tagName):
  3726.         '''Return a list of ranges of text which have tag TAGNAME.'''
  3727.         return self.tk.splitlist(self.tk.call(self._w, 'tag', 'ranges', tagName))
  3728.  
  3729.     
  3730.     def tag_remove(self, tagName, index1, index2 = None):
  3731.         '''Remove tag TAGNAME from all characters between INDEX1 and INDEX2.'''
  3732.         self.tk.call(self._w, 'tag', 'remove', tagName, index1, index2)
  3733.  
  3734.     
  3735.     def window_cget(self, index, option):
  3736.         '''Return the value of OPTION of an embedded window at INDEX.'''
  3737.         if option[:1] != '-':
  3738.             option = '-' + option
  3739.         
  3740.         if option[-1:] == '_':
  3741.             option = option[:-1]
  3742.         
  3743.         return self.tk.call(self._w, 'window', 'cget', index, option)
  3744.  
  3745.     
  3746.     def window_configure(self, index, cnf = { }, **kw):
  3747.         '''Configure an embedded window at INDEX.'''
  3748.         if type(cnf) == StringType:
  3749.             x = self.tk.split(self.tk.call(self._w, 'window', 'configure', index, '-' + cnf))
  3750.             return (x[0][1:],) + x[1:]
  3751.         
  3752.         self.tk.call((self._w, 'window', 'configure', index) + self._options(cnf, kw))
  3753.  
  3754.     window_config = window_configure
  3755.     
  3756.     def window_create(self, index, cnf = { }, **kw):
  3757.         '''Create a window at INDEX.'''
  3758.         self.tk.call((self._w, 'window', 'create', index) + self._options(cnf, kw))
  3759.  
  3760.     
  3761.     def window_names(self):
  3762.         '''Return all names of embedded windows in this widget.'''
  3763.         return self.tk.splitlist(self.tk.call(self._w, 'window', 'names'))
  3764.  
  3765.     
  3766.     def xview(self, *what):
  3767.         '''Query and change horizontal position of the view.'''
  3768.         if not what:
  3769.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  3770.         
  3771.         self.tk.call((self._w, 'xview') + what)
  3772.  
  3773.     
  3774.     def xview_moveto(self, fraction):
  3775.         '''Adjusts the view in the window so that FRACTION of the
  3776.         total width of the canvas is off-screen to the left.'''
  3777.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  3778.  
  3779.     
  3780.     def xview_scroll(self, number, what):
  3781.         '''Shift the x-view according to NUMBER which is measured
  3782.         in "units" or "pages" (WHAT).'''
  3783.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  3784.  
  3785.     
  3786.     def yview(self, *what):
  3787.         '''Query and change vertical position of the view.'''
  3788.         if not what:
  3789.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  3790.         
  3791.         self.tk.call((self._w, 'yview') + what)
  3792.  
  3793.     
  3794.     def yview_moveto(self, fraction):
  3795.         '''Adjusts the view in the window so that FRACTION of the
  3796.         total height of the canvas is off-screen to the top.'''
  3797.         self.tk.call(self._w, 'yview', 'moveto', fraction)
  3798.  
  3799.     
  3800.     def yview_scroll(self, number, what):
  3801.         '''Shift the y-view according to NUMBER which is measured
  3802.         in "units" or "pages" (WHAT).'''
  3803.         self.tk.call(self._w, 'yview', 'scroll', number, what)
  3804.  
  3805.     
  3806.     def yview_pickplace(self, *what):
  3807.         '''Obsolete function, use see.'''
  3808.         self.tk.call((self._w, 'yview', '-pickplace') + what)
  3809.  
  3810.  
  3811.  
  3812. class _setit:
  3813.     '''Internal class. It wraps the command in the widget OptionMenu.'''
  3814.     
  3815.     def __init__(self, var, value, callback = None):
  3816.         self._setit__value = value
  3817.         self._setit__var = var
  3818.         self._setit__callback = callback
  3819.  
  3820.     
  3821.     def __call__(self, *args):
  3822.         self._setit__var.set(self._setit__value)
  3823.         if self._setit__callback:
  3824.             apply(self._setit__callback, (self._setit__value,) + args)
  3825.         
  3826.  
  3827.  
  3828.  
  3829. class OptionMenu(Menubutton):
  3830.     '''OptionMenu which allows the user to select a value from a menu.'''
  3831.     
  3832.     def __init__(self, master, variable, value, *values, **kwargs):
  3833.         '''Construct an optionmenu widget with the parent MASTER, with
  3834.         the resource textvariable set to VARIABLE, the initially selected
  3835.         value VALUE, the other menu values VALUES and an additional
  3836.         keyword argument command.'''
  3837.         kw = {
  3838.             'borderwidth': 2,
  3839.             'textvariable': variable,
  3840.             'indicatoron': 1,
  3841.             'relief': RAISED,
  3842.             'anchor': 'c',
  3843.             'highlightthickness': 2 }
  3844.         Widget.__init__(self, master, 'menubutton', kw)
  3845.         self.widgetName = 'tk_optionMenu'
  3846.         menu = self._OptionMenu__menu = Menu(self, name = 'menu', tearoff = 0)
  3847.         self.menuname = menu._w
  3848.         callback = kwargs.get('command')
  3849.         if kwargs.has_key('command'):
  3850.             del kwargs['command']
  3851.         
  3852.         if kwargs:
  3853.             raise TclError, 'unknown option -' + kwargs.keys()[0]
  3854.         
  3855.         menu.add_command(label = value, command = _setit(variable, value, callback))
  3856.         for v in values:
  3857.             menu.add_command(label = v, command = _setit(variable, v, callback))
  3858.         
  3859.         self['menu'] = menu
  3860.  
  3861.     
  3862.     def __getitem__(self, name):
  3863.         if name == 'menu':
  3864.             return self._OptionMenu__menu
  3865.         
  3866.         return Widget.__getitem__(self, name)
  3867.  
  3868.     
  3869.     def destroy(self):
  3870.         '''Destroy this widget and the associated menu.'''
  3871.         Menubutton.destroy(self)
  3872.         self._OptionMenu__menu = None
  3873.  
  3874.  
  3875.  
  3876. class Image:
  3877.     '''Base class for images.'''
  3878.     _last_id = 0
  3879.     
  3880.     def __init__(self, imgtype, name = None, cnf = { }, master = None, **kw):
  3881.         self.name = None
  3882.         if not master:
  3883.             master = _default_root
  3884.             if not master:
  3885.                 raise RuntimeError, 'Too early to create image'
  3886.             
  3887.         
  3888.         self.tk = master.tk
  3889.         if not name:
  3890.             Image._last_id += 1
  3891.             name = 'pyimage' + `Image._last_id`
  3892.             if name[0] == '-':
  3893.                 name = '_' + name[1:]
  3894.             
  3895.         
  3896.         if kw and cnf:
  3897.             cnf = _cnfmerge((cnf, kw))
  3898.         elif kw:
  3899.             cnf = kw
  3900.         
  3901.         options = ()
  3902.         for k, v in cnf.items():
  3903.             if callable(v):
  3904.                 v = self._register(v)
  3905.             
  3906.             options = options + ('-' + k, v)
  3907.         
  3908.         self.tk.call(('image', 'create', imgtype, name) + options)
  3909.         self.name = name
  3910.  
  3911.     
  3912.     def __str__(self):
  3913.         return self.name
  3914.  
  3915.     
  3916.     def __del__(self):
  3917.         if self.name:
  3918.             
  3919.             try:
  3920.                 self.tk.call('image', 'delete', self.name)
  3921.             except TclError:
  3922.                 pass
  3923.  
  3924.         
  3925.  
  3926.     
  3927.     def __setitem__(self, key, value):
  3928.         self.tk.call(self.name, 'configure', '-' + key, value)
  3929.  
  3930.     
  3931.     def __getitem__(self, key):
  3932.         return self.tk.call(self.name, 'configure', '-' + key)
  3933.  
  3934.     
  3935.     def configure(self, **kw):
  3936.         '''Configure the image.'''
  3937.         res = ()
  3938.         for k, v in _cnfmerge(kw).items():
  3939.             if v is not None:
  3940.                 if k[-1] == '_':
  3941.                     k = k[:-1]
  3942.                 
  3943.                 if callable(v):
  3944.                     v = self._register(v)
  3945.                 
  3946.                 res = res + ('-' + k, v)
  3947.             
  3948.         
  3949.         self.tk.call((self.name, 'config') + res)
  3950.  
  3951.     config = configure
  3952.     
  3953.     def height(self):
  3954.         '''Return the height of the image.'''
  3955.         return getint(self.tk.call('image', 'height', self.name))
  3956.  
  3957.     
  3958.     def type(self):
  3959.         '''Return the type of the imgage, e.g. "photo" or "bitmap".'''
  3960.         return self.tk.call('image', 'type', self.name)
  3961.  
  3962.     
  3963.     def width(self):
  3964.         '''Return the width of the image.'''
  3965.         return getint(self.tk.call('image', 'width', self.name))
  3966.  
  3967.  
  3968.  
  3969. class PhotoImage(Image):
  3970.     '''Widget which can display colored images in GIF, PPM/PGM format.'''
  3971.     
  3972.     def __init__(self, name = None, cnf = { }, master = None, **kw):
  3973.         '''Create an image with NAME.
  3974.  
  3975.         Valid resource names: data, format, file, gamma, height, palette,
  3976.         width.'''
  3977.         apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
  3978.  
  3979.     
  3980.     def blank(self):
  3981.         '''Display a transparent image.'''
  3982.         self.tk.call(self.name, 'blank')
  3983.  
  3984.     
  3985.     def cget(self, option):
  3986.         '''Return the value of OPTION.'''
  3987.         return self.tk.call(self.name, 'cget', '-' + option)
  3988.  
  3989.     
  3990.     def __getitem__(self, key):
  3991.         return self.tk.call(self.name, 'cget', '-' + key)
  3992.  
  3993.     
  3994.     def copy(self):
  3995.         '''Return a new PhotoImage with the same image as this widget.'''
  3996.         destImage = PhotoImage()
  3997.         self.tk.call(destImage, 'copy', self.name)
  3998.         return destImage
  3999.  
  4000.     
  4001.     def zoom(self, x, y = ''):
  4002.         '''Return a new PhotoImage with the same image as this widget
  4003.         but zoom it with X and Y.'''
  4004.         destImage = PhotoImage()
  4005.         if y == '':
  4006.             y = x
  4007.         
  4008.         self.tk.call(destImage, 'copy', self.name, '-zoom', x, y)
  4009.         return destImage
  4010.  
  4011.     
  4012.     def subsample(self, x, y = ''):
  4013.         '''Return a new PhotoImage based on the same image as this widget
  4014.         but use only every Xth or Yth pixel.'''
  4015.         destImage = PhotoImage()
  4016.         if y == '':
  4017.             y = x
  4018.         
  4019.         self.tk.call(destImage, 'copy', self.name, '-subsample', x, y)
  4020.         return destImage
  4021.  
  4022.     
  4023.     def get(self, x, y):
  4024.         '''Return the color (red, green, blue) of the pixel at X,Y.'''
  4025.         return self.tk.call(self.name, 'get', x, y)
  4026.  
  4027.     
  4028.     def put(self, data, to = None):
  4029.         '''Put row formated colors to image starting from
  4030.         position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))'''
  4031.         args = (self.name, 'put', data)
  4032.         if to:
  4033.             if to[0] == '-to':
  4034.                 to = to[1:]
  4035.             
  4036.             args = args + ('-to',) + tuple(to)
  4037.         
  4038.         self.tk.call(args)
  4039.  
  4040.     
  4041.     def write(self, filename, format = None, from_coords = None):
  4042.         '''Write image to file FILENAME in FORMAT starting from
  4043.         position FROM_COORDS.'''
  4044.         args = (self.name, 'write', filename)
  4045.         if format:
  4046.             args = args + ('-format', format)
  4047.         
  4048.         if from_coords:
  4049.             args = args + ('-from',) + tuple(from_coords)
  4050.         
  4051.         self.tk.call(args)
  4052.  
  4053.  
  4054.  
  4055. class BitmapImage(Image):
  4056.     '''Widget which can display a bitmap.'''
  4057.     
  4058.     def __init__(self, name = None, cnf = { }, master = None, **kw):
  4059.         '''Create a bitmap with NAME.
  4060.  
  4061.         Valid resource names: background, data, file, foreground, maskdata, maskfile.'''
  4062.         apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
  4063.  
  4064.  
  4065.  
  4066. def image_names():
  4067.     return _default_root.tk.call('image', 'names')
  4068.  
  4069.  
  4070. def image_types():
  4071.     return _default_root.tk.call('image', 'types')
  4072.  
  4073.  
  4074. class Studbutton(Button):
  4075.     
  4076.     def __init__(self, master = None, cnf = { }, **kw):
  4077.         Widget.__init__(self, master, 'studbutton', cnf, kw)
  4078.         self.bind('<Any-Enter>', self.tkButtonEnter)
  4079.         self.bind('<Any-Leave>', self.tkButtonLeave)
  4080.         self.bind('<1>', self.tkButtonDown)
  4081.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  4082.  
  4083.  
  4084.  
  4085. class Tributton(Button):
  4086.     
  4087.     def __init__(self, master = None, cnf = { }, **kw):
  4088.         Widget.__init__(self, master, 'tributton', cnf, kw)
  4089.         self.bind('<Any-Enter>', self.tkButtonEnter)
  4090.         self.bind('<Any-Leave>', self.tkButtonLeave)
  4091.         self.bind('<1>', self.tkButtonDown)
  4092.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  4093.         self['fg'] = self['bg']
  4094.         self['activebackground'] = self['bg']
  4095.  
  4096.  
  4097.  
  4098. def _test():
  4099.     root = Tk()
  4100.     text = 'This is Tcl/Tk version %s' % TclVersion
  4101.     if TclVersion >= 8.0999999999999996:
  4102.         
  4103.         try:
  4104.             text = text + unicode('\nThis should be a cedilla: \xe7', 'iso-8859-1')
  4105.         except NameError:
  4106.             pass
  4107.  
  4108.     
  4109.     label = Label(root, text = text)
  4110.     label.pack()
  4111.     test = Button(root, text = 'Click me!', command = (lambda root = root: root.test.configure(text = '[%s]' % root.test['text'])))
  4112.     test.pack()
  4113.     root.test = test
  4114.     quit = Button(root, text = 'QUIT', command = root.destroy)
  4115.     quit.pack()
  4116.     root.iconify()
  4117.     root.update()
  4118.     root.deiconify()
  4119.     root.mainloop()
  4120.  
  4121. if __name__ == '__main__':
  4122.     _test()
  4123.  
  4124.