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