home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / lib-tk / Tkinter.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  151.8 KB  |  3,696 lines

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