Advertisement
Guest User

Untitled

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