Advertisement
here2share

all_Tkinter.py

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