home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2001 May / maximum-cd-2001-05.iso / Blade of Darkness / data1.cab / Program_Executable_Files / Lib / PythonLib / lib-tk / Tkinter.py < prev    next >
Encoding:
Python Source  |  2000-11-16  |  61.6 KB  |  1,856 lines

  1. # Tkinter.py -- Tk/Tcl widget wrappers
  2.  
  3. __version__ = "$Revision: 1.101 $"
  4.  
  5. import _tkinter # If this fails your Python is not configured for Tk
  6. tkinter = _tkinter # b/w compat for export
  7. TclError = _tkinter.TclError
  8. from types import *
  9. from Tkconstants import *
  10. import string; _string = string; del string
  11.  
  12. TkVersion = _string.atof(_tkinter.TK_VERSION)
  13. TclVersion = _string.atof(_tkinter.TCL_VERSION)
  14.  
  15. READABLE = _tkinter.READABLE
  16. WRITABLE = _tkinter.WRITABLE
  17. EXCEPTION = _tkinter.EXCEPTION
  18.  
  19. # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  20. try: _tkinter.createfilehandler
  21. except AttributeError: _tkinter.createfilehandler = None
  22. try: _tkinter.deletefilehandler
  23. except AttributeError: _tkinter.deletefilehandler = None
  24.     
  25.     
  26. def _flatten(tuple):
  27.     res = ()
  28.     for item in tuple:
  29.         if type(item) in (TupleType, ListType):
  30.             res = res + _flatten(item)
  31.         elif item is not None:
  32.             res = res + (item,)
  33.     return res
  34.  
  35. def _cnfmerge(cnfs):
  36.     if type(cnfs) is DictionaryType:
  37.         return cnfs
  38.     elif type(cnfs) in (NoneType, StringType):
  39.         return cnfs
  40.     else:
  41.         cnf = {}
  42.         for c in _flatten(cnfs):
  43.             try:
  44.                 cnf.update(c)
  45.             except (AttributeError, TypeError), msg:
  46.                 print "_cnfmerge: fallback due to:", msg
  47.                 for k, v in c.items():
  48.                     cnf[k] = v
  49.         return cnf
  50.  
  51. class Event:
  52.     pass
  53.  
  54. _support_default_root = 1
  55. _default_root = None
  56.  
  57. def NoDefaultRoot():
  58.     global _support_default_root
  59.     _support_default_root = 0
  60.     del _default_root
  61.  
  62. def _tkerror(err):
  63.     pass
  64.  
  65. def _exit(code='0'):
  66.     raise SystemExit, code
  67.  
  68. _varnum = 0
  69. class Variable:
  70.     _default = ""
  71.     def __init__(self, master=None):
  72.         global _varnum
  73.         if not master:
  74.             master = _default_root
  75.         self._master = master
  76.         self._tk = master.tk
  77.         self._name = 'PY_VAR' + `_varnum`
  78.         _varnum = _varnum + 1
  79.         self.set(self._default)
  80.     def __del__(self):
  81.         self._tk.globalunsetvar(self._name)
  82.     def __str__(self):
  83.         return self._name
  84.     def set(self, value):
  85.         return self._tk.globalsetvar(self._name, value)
  86.     def trace_variable(self, mode, callback):
  87.         cbname = self._master._register(callback)
  88.         self._tk.call("trace", "variable", self._name, mode, cbname)
  89.         return cbname
  90.     trace = trace_variable
  91.     def trace_vdelete(self, mode, cbname):
  92.         self._tk.call("trace", "vdelete", self._name, mode, cbname)
  93.         self._master.deletecommand(cbname)
  94.     def trace_vinfo(self):
  95.         return map(self._tk.split, self._tk.splitlist(
  96.             self._tk.call("trace", "vinfo", self._name)))
  97.  
  98. class StringVar(Variable):
  99.     _default = ""
  100.     def __init__(self, master=None):
  101.         Variable.__init__(self, master)
  102.     def get(self):
  103.         return self._tk.globalgetvar(self._name)
  104.  
  105. class IntVar(Variable):
  106.     _default = 0
  107.     def __init__(self, master=None):
  108.         Variable.__init__(self, master)
  109.     def get(self):
  110.         return self._tk.getint(self._tk.globalgetvar(self._name))
  111.  
  112. class DoubleVar(Variable):
  113.     _default = 0.0
  114.     def __init__(self, master=None):
  115.         Variable.__init__(self, master)
  116.     def get(self):
  117.         return self._tk.getdouble(self._tk.globalgetvar(self._name))
  118.  
  119. class BooleanVar(Variable):
  120.     _default = "false"
  121.     def __init__(self, master=None):
  122.         Variable.__init__(self, master)
  123.     def get(self):
  124.         return self._tk.getboolean(self._tk.globalgetvar(self._name))
  125.  
  126. def mainloop(n=0):
  127.     _default_root.tk.mainloop(n)
  128.  
  129. def getint(s):
  130.     return _default_root.tk.getint(s)
  131.  
  132. def getdouble(s):
  133.     return _default_root.tk.getdouble(s)
  134.  
  135. def getboolean(s):
  136.     return _default_root.tk.getboolean(s)
  137.  
  138. # Methods defined on both toplevel and interior widgets
  139. class Misc:
  140.     # XXX font command?
  141.     _tclCommands = None
  142.     def destroy(self):
  143.         if self._tclCommands is not None:
  144.             for name in self._tclCommands:
  145.                 #print '- Tkinter: deleted command', name
  146.                 self.tk.deletecommand(name)
  147.             self._tclCommands = None
  148.     def deletecommand(self, name):
  149.         #print '- Tkinter: deleted command', name
  150.         self.tk.deletecommand(name)
  151.         try:
  152.             self._tclCommands.remove(name)
  153.         except ValueError:
  154.             pass
  155.     def tk_strictMotif(self, boolean=None):
  156.         return self.tk.getboolean(self.tk.call(
  157.             'set', 'tk_strictMotif', boolean))
  158.     def tk_bisque(self):
  159.         self.tk.call('tk_bisque')
  160.     def tk_setPalette(self, *args, **kw):
  161.         apply(self.tk.call, ('tk_setPalette',)
  162.               + _flatten(args) + _flatten(kw.items()))
  163.     def tk_menuBar(self, *args):
  164.         pass # obsolete since Tk 4.0
  165.     def wait_variable(self, name='PY_VAR'):
  166.         self.tk.call('tkwait', 'variable', name)
  167.     waitvar = wait_variable # XXX b/w compat
  168.     def wait_window(self, window=None):
  169.         if window == None:
  170.             window = self
  171.         self.tk.call('tkwait', 'window', window._w)
  172.     def wait_visibility(self, window=None):
  173.         if window == None:
  174.             window = self
  175.         self.tk.call('tkwait', 'visibility', window._w)
  176.     def setvar(self, name='PY_VAR', value='1'):
  177.         self.tk.setvar(name, value)
  178.     def getvar(self, name='PY_VAR'):
  179.         return self.tk.getvar(name)
  180.     def getint(self, s):
  181.         return self.tk.getint(s)
  182.     def getdouble(self, s):
  183.         return self.tk.getdouble(s)
  184.     def getboolean(self, s):
  185.         return self.tk.getboolean(s)
  186.     def focus_set(self):
  187.         self.tk.call('focus', self._w)
  188.     focus = focus_set # XXX b/w compat?
  189.     def focus_force(self):
  190.         self.tk.call('focus', '-force', self._w)
  191.     def focus_get(self):
  192.         name = self.tk.call('focus')
  193.         if name == 'none' or not name: return None
  194.         return self._nametowidget(name)
  195.     def focus_displayof(self):
  196.         name = self.tk.call('focus', '-displayof', self._w)
  197.         if name == 'none' or not name: return None
  198.         return self._nametowidget(name)
  199.     def focus_lastfor(self):
  200.         name = self.tk.call('focus', '-lastfor', self._w)
  201.         if name == 'none' or not name: return None
  202.         return self._nametowidget(name)
  203.     def tk_focusFollowsMouse(self):
  204.         self.tk.call('tk_focusFollowsMouse')
  205.     def tk_focusNext(self):
  206.         name = self.tk.call('tk_focusNext', self._w)
  207.         if not name: return None
  208.         return self._nametowidget(name)
  209.     def tk_focusPrev(self):
  210.         name = self.tk.call('tk_focusPrev', self._w)
  211.         if not name: return None
  212.         return self._nametowidget(name)
  213.     def after(self, ms, func=None, *args):
  214.         if not func:
  215.             # I'd rather use time.sleep(ms*0.001)
  216.             self.tk.call('after', ms)
  217.         else:
  218.             # XXX Disgusting hack to clean up after calling func
  219.             tmp = []
  220.             def callit(func=func, args=args, self=self, tmp=tmp):
  221.                 try:
  222.                     apply(func, args)
  223.                 finally:
  224.                     self.deletecommand(tmp[0])
  225.             name = self._register(callit)
  226.             tmp.append(name)
  227.             return self.tk.call('after', ms, name)
  228.     def after_idle(self, func, *args):
  229.         return apply(self.after, ('idle', func) + args)
  230.     def after_cancel(self, id):
  231.         self.tk.call('after', 'cancel', id)
  232.     def bell(self, displayof=0):
  233.         apply(self.tk.call, ('bell',) + self._displayof(displayof))
  234.     # Clipboard handling:
  235.     def clipboard_clear(self, **kw):
  236.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  237.         apply(self.tk.call,
  238.               ('clipboard', 'clear') + self._options(kw))
  239.     def clipboard_append(self, string, **kw):
  240.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  241.         apply(self.tk.call,
  242.               ('clipboard', 'append') + self._options(kw)
  243.               + ('--', string))
  244.     # XXX grab current w/o window argument
  245.     def grab_current(self):
  246.         name = self.tk.call('grab', 'current', self._w)
  247.         if not name: return None
  248.         return self._nametowidget(name)
  249.     def grab_release(self):
  250.         self.tk.call('grab', 'release', self._w)
  251.     def grab_set(self):
  252.         self.tk.call('grab', 'set', self._w)
  253.     def grab_set_global(self):
  254.         self.tk.call('grab', 'set', '-global', self._w)
  255.     def grab_status(self):
  256.         status = self.tk.call('grab', 'status', self._w)
  257.         if status == 'none': status = None
  258.         return status
  259.     def lower(self, belowThis=None):
  260.         self.tk.call('lower', self._w, belowThis)
  261.     def option_add(self, pattern, value, priority = None):
  262.         self.tk.call('option', 'add', pattern, value, priority)
  263.     def option_clear(self):
  264.         self.tk.call('option', 'clear')
  265.     def option_get(self, name, className):
  266.         return self.tk.call('option', 'get', self._w, name, className)
  267.     def option_readfile(self, fileName, priority = None):
  268.         self.tk.call('option', 'readfile', fileName, priority)
  269.     def selection_clear(self, **kw):
  270.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  271.         apply(self.tk.call, ('selection', 'clear') + self._options(kw))
  272.     def selection_get(self, **kw):
  273.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  274.         return apply(self.tk.call,
  275.                  ('selection', 'get') + self._options(kw))
  276.     def selection_handle(self, command, **kw):
  277.         name = self._register(command)
  278.         apply(self.tk.call,
  279.               ('selection', 'handle') + self._options(kw)
  280.               + (self._w, name))
  281.     def selection_own(self, **kw):
  282.         "Become owner of X selection."
  283.         apply(self.tk.call,
  284.               ('selection', 'own') + self._options(kw) + (self._w,))
  285.     def selection_own_get(self, **kw):
  286.         "Find owner of X selection."
  287.         if not kw.has_key('displayof'): kw['displayof'] = self._w
  288.         name = apply(self.tk.call,
  289.                  ('selection', 'own') + self._options(kw))
  290.         if not name: return None
  291.         return self._nametowidget(name)
  292.     def send(self, interp, cmd, *args):
  293.         return apply(self.tk.call, ('send', interp, cmd) + args)
  294.     def lower(self, belowThis=None):
  295.         self.tk.call('lower', self._w, belowThis)
  296.     def tkraise(self, aboveThis=None):
  297.         self.tk.call('raise', self._w, aboveThis)
  298.     lift = tkraise
  299.     def colormodel(self, value=None):
  300.         return self.tk.call('tk', 'colormodel', self._w, value)
  301.     def winfo_atom(self, name, displayof=0):
  302.         args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  303.         return self.tk.getint(apply(self.tk.call, args))
  304.     def winfo_atomname(self, id, displayof=0):
  305.         args = ('winfo', 'atomname') \
  306.                + self._displayof(displayof) + (id,)
  307.         return apply(self.tk.call, args)
  308.     def winfo_cells(self):
  309.         return self.tk.getint(
  310.             self.tk.call('winfo', 'cells', self._w))
  311.     def winfo_children(self):
  312.         return map(self._nametowidget,
  313.                self.tk.splitlist(self.tk.call(
  314.                    'winfo', 'children', self._w)))
  315.     def winfo_class(self):
  316.         return self.tk.call('winfo', 'class', self._w)
  317.     def winfo_colormapfull(self):
  318.         return self.tk.getboolean(
  319.             self.tk.call('winfo', 'colormapfull', self._w))
  320.     def winfo_containing(self, rootX, rootY, displayof=0):
  321.         args = ('winfo', 'containing') \
  322.                + self._displayof(displayof) + (rootX, rootY)
  323.         name = apply(self.tk.call, args)
  324.         if not name: return None
  325.         return self._nametowidget(name)
  326.     def winfo_depth(self):
  327.         return self.tk.getint(self.tk.call('winfo', 'depth', self._w))
  328.     def winfo_exists(self):
  329.         return self.tk.getint(
  330.             self.tk.call('winfo', 'exists', self._w))
  331.     def winfo_fpixels(self, number):
  332.         return self.tk.getdouble(self.tk.call(
  333.             'winfo', 'fpixels', self._w, number))
  334.     def winfo_geometry(self):
  335.         return self.tk.call('winfo', 'geometry', self._w)
  336.     def winfo_height(self):
  337.         return self.tk.getint(
  338.             self.tk.call('winfo', 'height', self._w))
  339.     def winfo_id(self):
  340.         return self.tk.getint(
  341.             self.tk.call('winfo', 'id', self._w))
  342.     def winfo_interps(self, displayof=0):
  343.         args = ('winfo', 'interps') + self._displayof(displayof)
  344.         return self.tk.splitlist(apply(self.tk.call, args))
  345.     def winfo_ismapped(self):
  346.         return self.tk.getint(
  347.             self.tk.call('winfo', 'ismapped', self._w))
  348.     def winfo_manager(self):
  349.         return self.tk.call('winfo', 'manager', self._w)
  350.     def winfo_name(self):
  351.         return self.tk.call('winfo', 'name', self._w)
  352.     def winfo_parent(self):
  353.         return self.tk.call('winfo', 'parent', self._w)
  354.     def winfo_pathname(self, id, displayof=0):
  355.         args = ('winfo', 'pathname') \
  356.                + self._displayof(displayof) + (id,)
  357.         return apply(self.tk.call, args)
  358.     def winfo_pixels(self, number):
  359.         return self.tk.getint(
  360.             self.tk.call('winfo', 'pixels', self._w, number))
  361.     def winfo_pointerx(self):
  362.         return self.tk.getint(
  363.             self.tk.call('winfo', 'pointerx', self._w))
  364.     def winfo_pointerxy(self):
  365.         return self._getints(
  366.             self.tk.call('winfo', 'pointerxy', self._w))
  367.     def winfo_pointery(self):
  368.         return self.tk.getint(
  369.             self.tk.call('winfo', 'pointery', self._w))
  370.     def winfo_reqheight(self):
  371.         return self.tk.getint(
  372.             self.tk.call('winfo', 'reqheight', self._w))
  373.     def winfo_reqwidth(self):
  374.         return self.tk.getint(
  375.             self.tk.call('winfo', 'reqwidth', self._w))
  376.     def winfo_rgb(self, color):
  377.         return self._getints(
  378.             self.tk.call('winfo', 'rgb', self._w, color))
  379.     def winfo_rootx(self):
  380.         return self.tk.getint(
  381.             self.tk.call('winfo', 'rootx', self._w))
  382.     def winfo_rooty(self):
  383.         return self.tk.getint(
  384.             self.tk.call('winfo', 'rooty', self._w))
  385.     def winfo_screen(self):
  386.         return self.tk.call('winfo', 'screen', self._w)
  387.     def winfo_screencells(self):
  388.         return self.tk.getint(
  389.             self.tk.call('winfo', 'screencells', self._w))
  390.     def winfo_screendepth(self):
  391.         return self.tk.getint(
  392.             self.tk.call('winfo', 'screendepth', self._w))
  393.     def winfo_screenheight(self):
  394.         return self.tk.getint(
  395.             self.tk.call('winfo', 'screenheight', self._w))
  396.     def winfo_screenmmheight(self):
  397.         return self.tk.getint(
  398.             self.tk.call('winfo', 'screenmmheight', self._w))
  399.     def winfo_screenmmwidth(self):
  400.         return self.tk.getint(
  401.             self.tk.call('winfo', 'screenmmwidth', self._w))
  402.     def winfo_screenvisual(self):
  403.         return self.tk.call('winfo', 'screenvisual', self._w)
  404.     def winfo_screenwidth(self):
  405.         return self.tk.getint(
  406.             self.tk.call('winfo', 'screenwidth', self._w))
  407.     def winfo_server(self):
  408.         return self.tk.call('winfo', 'server', self._w)
  409.     def winfo_toplevel(self):
  410.         return self._nametowidget(self.tk.call(
  411.             'winfo', 'toplevel', self._w))
  412.     def winfo_viewable(self):
  413.         return self.tk.getint(
  414.             self.tk.call('winfo', 'viewable', self._w))
  415.     def winfo_visual(self):
  416.         return self.tk.call('winfo', 'visual', self._w)
  417.     def winfo_visualid(self):
  418.         return self.tk.call('winfo', 'visualid', self._w)
  419.     def winfo_visualsavailable(self, includeids=0):
  420.         data = self.tk.split(
  421.             self.tk.call('winfo', 'visualsavailable', self._w,
  422.                      includeids and 'includeids' or None))
  423.         def parseitem(x, self=self):
  424.             return x[:1] + tuple(map(self.tk.getint, x[1:]))
  425.         return map(parseitem, data)
  426.     def winfo_vrootheight(self):
  427.         return self.tk.getint(
  428.             self.tk.call('winfo', 'vrootheight', self._w))
  429.     def winfo_vrootwidth(self):
  430.         return self.tk.getint(
  431.             self.tk.call('winfo', 'vrootwidth', self._w))
  432.     def winfo_vrootx(self):
  433.         return self.tk.getint(
  434.             self.tk.call('winfo', 'vrootx', self._w))
  435.     def winfo_vrooty(self):
  436.         return self.tk.getint(
  437.             self.tk.call('winfo', 'vrooty', self._w))
  438.     def winfo_width(self):
  439.         return self.tk.getint(
  440.             self.tk.call('winfo', 'width', self._w))
  441.     def winfo_x(self):
  442.         return self.tk.getint(
  443.             self.tk.call('winfo', 'x', self._w))
  444.     def winfo_y(self):
  445.         return self.tk.getint(
  446.             self.tk.call('winfo', 'y', self._w))
  447.     def update(self):
  448.         self.tk.call('update')
  449.     def update_idletasks(self):
  450.         self.tk.call('update', 'idletasks')
  451.     def bindtags(self, tagList=None):
  452.         if tagList is None:
  453.             return self.tk.splitlist(
  454.                 self.tk.call('bindtags', self._w))
  455.         else:
  456.             self.tk.call('bindtags', self._w, tagList)
  457.     def _bind(self, what, sequence, func, add, needcleanup=1):
  458.         if func:
  459.             funcid = self._register(func, self._substitute,
  460.                         needcleanup)
  461.             cmd = ("%sset _tkinter_break [%s %s]\n"
  462.                    'if {"$_tkinter_break" == "break"} break\n') \
  463.                    % (add and '+' or '',
  464.                   funcid,
  465.                   _string.join(self._subst_format))
  466.             apply(self.tk.call, what + (sequence, cmd))
  467.             return funcid
  468.         elif func == '':
  469.             apply(self.tk.call, what + (sequence, func))
  470.         else:
  471.             return apply(self.tk.call, what + (sequence,))
  472.     def bind(self, sequence=None, func=None, add=None):
  473.         return self._bind(('bind', self._w), sequence, func, add)
  474.     def unbind(self, sequence, funcid=None):
  475.         self.tk.call('bind', self._w, sequence, '')
  476.         if funcid:
  477.             self.deletecommand(funcid)
  478.     def bind_all(self, sequence=None, func=None, add=None):
  479.         return self._bind(('bind', 'all'), sequence, func, add, 0)
  480.     def unbind_all(self, sequence):
  481.         self.tk.call('bind', 'all' , sequence, '')
  482.     def bind_class(self, className, sequence=None, func=None, add=None):
  483.         return self._bind(('bind', className), sequence, func, add, 0)
  484.     def unbind_class(self, className, sequence):
  485.         self.tk.call('bind', className , sequence, '')
  486.     def mainloop(self, n=0):
  487.         self.tk.mainloop(n)
  488.     def quit(self):
  489.         self.tk.quit()
  490.     def _getints(self, string):
  491.         if not string: return None
  492.         return tuple(map(self.tk.getint, self.tk.splitlist(string)))
  493.     def _getdoubles(self, string):
  494.         if not string: return None
  495.         return tuple(map(self.tk.getdouble, self.tk.splitlist(string)))
  496.     def _getboolean(self, string):
  497.         if string:
  498.             return self.tk.getboolean(string)
  499.     def _displayof(self, displayof):
  500.         if displayof:
  501.             return ('-displayof', displayof)
  502.         if displayof is None:
  503.             return ('-displayof', self._w)
  504.         return ()
  505.     def _options(self, cnf, kw = None):
  506.         if kw:
  507.             cnf = _cnfmerge((cnf, kw))
  508.         else:
  509.             cnf = _cnfmerge(cnf)
  510.         res = ()
  511.         for k, v in cnf.items():
  512.             if v is not None:
  513.                 if k[-1] == '_': k = k[:-1]
  514.                 if callable(v):
  515.                     v = self._register(v)
  516.                 res = res + ('-'+k, v)
  517.         return res
  518.     def nametowidget(self, name):
  519.         w = self
  520.         if name[0] == '.':
  521.             w = w._root()
  522.             name = name[1:]
  523.         find = _string.find
  524.         while name:
  525.             i = find(name, '.')
  526.             if i >= 0:
  527.                 name, tail = name[:i], name[i+1:]
  528.             else:
  529.                 tail = ''
  530.             w = w.children[name]
  531.             name = tail
  532.         return w
  533.     _nametowidget = nametowidget
  534.     def _register(self, func, subst=None, needcleanup=1):
  535.         f = CallWrapper(func, subst, self).__call__
  536.         name = `id(f)`
  537.         try:
  538.             func = func.im_func
  539.         except AttributeError:
  540.             pass
  541.         try:
  542.             name = name + func.__name__
  543.         except AttributeError:
  544.             pass
  545.         self.tk.createcommand(name, f)
  546.         if needcleanup:
  547.             if self._tclCommands is None:
  548.                 self._tclCommands = []
  549.             self._tclCommands.append(name)
  550.         #print '+ Tkinter created command', name
  551.         return name
  552.     register = _register
  553.     def _root(self):
  554.         w = self
  555.         while w.master: w = w.master
  556.         return w
  557.     _subst_format = ('%#', '%b', '%f', '%h', '%k', 
  558.              '%s', '%t', '%w', '%x', '%y',
  559.              '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y')
  560.     def _substitute(self, *args):
  561.         tk = self.tk
  562.         if len(args) != len(self._subst_format): return args
  563.         nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y = args
  564.         # Missing: (a, c, d, m, o, v, B, R)
  565.         e = Event()
  566.         e.serial = tk.getint(nsign)
  567.         e.num = tk.getint(b)
  568.         try: e.focus = tk.getboolean(f)
  569.         except TclError: pass
  570.         e.height = tk.getint(h)
  571.         e.keycode = tk.getint(k)
  572.         # For Visibility events, event state is a string and
  573.         # not an integer:
  574.         try:
  575.             e.state = tk.getint(s)
  576.         except TclError:
  577.             e.state = s
  578.         e.time = tk.getint(t)
  579.         e.width = tk.getint(w)
  580.         e.x = tk.getint(x)
  581.         e.y = tk.getint(y)
  582.         e.char = A
  583.         try: e.send_event = tk.getboolean(E)
  584.         except TclError: pass
  585.         e.keysym = K
  586.         e.keysym_num = tk.getint(N)
  587.         e.type = T
  588.         e.widget = self._nametowidget(W)
  589.         e.x_root = tk.getint(X)
  590.         e.y_root = tk.getint(Y)
  591.         return (e,)
  592.     def _report_exception(self):
  593.         import sys
  594.         exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
  595.         root = self._root()
  596.         root.report_callback_exception(exc, val, tb)
  597.     # These used to be defined in Widget:
  598.     def configure(self, cnf=None, **kw):
  599.         # XXX ought to generalize this so tag_config etc. can use it
  600.         if kw:
  601.             cnf = _cnfmerge((cnf, kw))
  602.         elif cnf:
  603.             cnf = _cnfmerge(cnf)
  604.         if cnf is None:
  605.             cnf = {}
  606.             for x in self.tk.split(
  607.                 self.tk.call(self._w, 'configure')):
  608.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  609.             return cnf
  610.         if type(cnf) is StringType:
  611.             x = self.tk.split(self.tk.call(
  612.                 self._w, 'configure', '-'+cnf))
  613.             return (x[0][1:],) + x[1:]
  614.         apply(self.tk.call, (self._w, 'configure')
  615.               + self._options(cnf))
  616.     config = configure
  617.     def cget(self, key):
  618.         return self.tk.call(self._w, 'cget', '-' + key)
  619.     __getitem__ = cget
  620.     def __setitem__(self, key, value):
  621.         self.configure({key: value})
  622.     def keys(self):
  623.         return map(lambda x: x[0][1:],
  624.                self.tk.split(self.tk.call(self._w, 'configure')))
  625.     def __str__(self):
  626.         return self._w
  627.     # Pack methods that apply to the master
  628.     _noarg_ = ['_noarg_']
  629.     def pack_propagate(self, flag=_noarg_):
  630.         if flag is Misc._noarg_:
  631.             return self._getboolean(self.tk.call(
  632.                 'pack', 'propagate', self._w))
  633.         else:
  634.             self.tk.call('pack', 'propagate', self._w, flag)
  635.     propagate = pack_propagate
  636.     def pack_slaves(self):
  637.         return map(self._nametowidget,
  638.                self.tk.splitlist(
  639.                    self.tk.call('pack', 'slaves', self._w)))
  640.     slaves = pack_slaves
  641.     # Place method that applies to the master
  642.     def place_slaves(self):
  643.         return map(self._nametowidget,
  644.                self.tk.splitlist(
  645.                    self.tk.call(
  646.                        'place', 'slaves', self._w)))
  647.     # Grid methods that apply to the master
  648.     def grid_bbox(self, column, row):
  649.         return self._getints(
  650.             self.tk.call(
  651.                 'grid', 'bbox', self._w, column, row)) or None
  652.     bbox = grid_bbox
  653.     def _grid_configure(self, command, index, cnf, kw):
  654.         if type(cnf) is StringType and not kw:
  655.             if cnf[-1:] == '_':
  656.                 cnf = cnf[:-1]
  657.             if cnf[:1] != '-':
  658.                 cnf = '-'+cnf
  659.             options = (cnf,)
  660.         else:
  661.             options = self._options(cnf, kw)
  662.         if not options:
  663.             res = self.tk.call('grid',
  664.                        command, self._w, index)
  665.             words = self.tk.splitlist(res)
  666.             dict = {}
  667.             for i in range(0, len(words), 2):
  668.                 key = words[i][1:]
  669.                 value = words[i+1]
  670.                 if not value:
  671.                     value = None
  672.                 elif '.' in value:
  673.                     value = self.tk.getdouble(value)
  674.                 else:
  675.                     value = self.tk.getint(value)
  676.                 dict[key] = value
  677.             return dict
  678.         res = apply(self.tk.call, 
  679.                   ('grid', command, self._w, index) 
  680.                   + options)
  681.         if len(options) == 1:
  682.             if not res: return None
  683.             # In Tk 7.5, -width can be a float
  684.             if '.' in res: return self.tk.getdouble(res)
  685.             return self.tk.getint(res)
  686.     def grid_columnconfigure(self, index, cnf={}, **kw):
  687.         return self._grid_configure('columnconfigure', index, cnf, kw)
  688.     columnconfigure = grid_columnconfigure
  689.     def grid_propagate(self, flag=_noarg_):
  690.         if flag is Misc._noarg_:
  691.             return self._getboolean(self.tk.call(
  692.                 'grid', 'propagate', self._w))
  693.         else:
  694.             self.tk.call('grid', 'propagate', self._w, flag)
  695.     def grid_rowconfigure(self, index, cnf={}, **kw):
  696.         return self._grid_configure('rowconfigure', index, cnf, kw)
  697.     rowconfigure = grid_rowconfigure
  698.     def grid_size(self):
  699.         return self._getints(
  700.             self.tk.call('grid', 'size', self._w)) or None
  701.     size = grid_size
  702.     def grid_slaves(self, row=None, column=None):
  703.         args = ()
  704.         if row:
  705.             args = args + ('-row', row)
  706.         if column:
  707.             args = args + ('-column', column)
  708.         return map(self._nametowidget,
  709.                self.tk.splitlist(
  710.                    apply(self.tk.call,
  711.                      ('grid', 'slaves', self._w) + args)))
  712.  
  713.     # Support for the "event" command, new in Tk 4.2.
  714.     # By Case Roole.
  715.  
  716.     def event_add(self, virtual, *sequences):
  717.         args = ('event', 'add', virtual) + sequences
  718.         apply(self.tk.call, args)
  719.  
  720.     def event_delete(self, virtual, *sequences):
  721.         args = ('event', 'delete', virtual) + sequences
  722.         apply(self.tk.call, args)
  723.  
  724.     def event_generate(self, sequence, **kw):
  725.         args = ('event', 'generate', self._w, sequence)
  726.         for k, v in kw.items():
  727.             args = args + ('-%s' % k, str(v))
  728.         apply(self.tk.call, args)
  729.  
  730.     def event_info(self, virtual=None):
  731.         return self.tk.splitlist(
  732.             self.tk.call('event', 'info', virtual))
  733.  
  734.     # Image related commands
  735.  
  736.     def image_names(self):
  737.         return self.tk.call('image', 'names')
  738.  
  739.     def image_types(self):
  740.         return self.tk.call('image', 'types')
  741.  
  742.  
  743. class CallWrapper:
  744.     def __init__(self, func, subst, widget):
  745.         self.func = func
  746.         self.subst = subst
  747.         self.widget = widget
  748.     def __call__(self, *args):
  749.         try:
  750.             if self.subst:
  751.                 args = apply(self.subst, args)
  752.             return apply(self.func, args)
  753.         except SystemExit, msg:
  754.             raise SystemExit, msg
  755.         except:
  756.             self.widget._report_exception()
  757.  
  758. class Wm:
  759.     def aspect(self, 
  760.            minNumer=None, minDenom=None, 
  761.            maxNumer=None, maxDenom=None):
  762.         return self._getints(
  763.             self.tk.call('wm', 'aspect', self._w, 
  764.                      minNumer, minDenom, 
  765.                      maxNumer, maxDenom))
  766.     def client(self, name=None):
  767.         return self.tk.call('wm', 'client', self._w, name)
  768.     def colormapwindows(self, *wlist):
  769.         args = ('wm', 'colormapwindows', self._w) + _flatten(wlist)
  770.         return map(self._nametowidget, apply(self.tk.call, args))
  771.     def command(self, value=None):
  772.         return self.tk.call('wm', 'command', self._w, value)
  773.     def deiconify(self):
  774.         return self.tk.call('wm', 'deiconify', self._w)
  775.     def focusmodel(self, model=None):
  776.         return self.tk.call('wm', 'focusmodel', self._w, model)
  777.     def frame(self):
  778.         return self.tk.call('wm', 'frame', self._w)
  779.     def geometry(self, newGeometry=None):
  780.         return self.tk.call('wm', 'geometry', self._w, newGeometry)
  781.     def grid(self,
  782.          baseWidth=None, baseHeight=None, 
  783.          widthInc=None, heightInc=None):
  784.         return self._getints(self.tk.call(
  785.             'wm', 'grid', self._w,
  786.             baseWidth, baseHeight, widthInc, heightInc))
  787.     def group(self, pathName=None):
  788.         return self.tk.call('wm', 'group', self._w, pathName)
  789.     def iconbitmap(self, bitmap=None):
  790.         return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  791.     def iconify(self):
  792.         return self.tk.call('wm', 'iconify', self._w)
  793.     def iconmask(self, bitmap=None):
  794.         return self.tk.call('wm', 'iconmask', self._w, bitmap)
  795.     def iconname(self, newName=None):
  796.         return self.tk.call('wm', 'iconname', self._w, newName)
  797.     def iconposition(self, x=None, y=None):
  798.         return self._getints(self.tk.call(
  799.             'wm', 'iconposition', self._w, x, y))
  800.     def iconwindow(self, pathName=None):
  801.         return self.tk.call('wm', 'iconwindow', self._w, pathName)
  802.     def maxsize(self, width=None, height=None):
  803.         return self._getints(self.tk.call(
  804.             'wm', 'maxsize', self._w, width, height))
  805.     def minsize(self, width=None, height=None):
  806.         return self._getints(self.tk.call(
  807.             'wm', 'minsize', self._w, width, height))
  808.     def overrideredirect(self, boolean=None):
  809.         return self._getboolean(self.tk.call(
  810.             'wm', 'overrideredirect', self._w, boolean))
  811.     def positionfrom(self, who=None):
  812.         return self.tk.call('wm', 'positionfrom', self._w, who)
  813.     def protocol(self, name=None, func=None):
  814.         if callable(func):
  815.             command = self._register(func)
  816.         else:
  817.             command = func
  818.         return self.tk.call(
  819.             'wm', 'protocol', self._w, name, command)
  820.     def resizable(self, width=None, height=None):
  821.         return self.tk.call('wm', 'resizable', self._w, width, height)
  822.     def sizefrom(self, who=None):
  823.         return self.tk.call('wm', 'sizefrom', self._w, who)
  824.     def state(self):
  825.         return self.tk.call('wm', 'state', self._w)
  826.     def title(self, string=None):
  827.         return self.tk.call('wm', 'title', self._w, string)
  828.     def transient(self, master=None):
  829.         return self.tk.call('wm', 'transient', self._w, master)
  830.     def withdraw(self):
  831.         return self.tk.call('wm', 'withdraw', self._w)
  832.  
  833. class Tk(Misc, Wm):
  834.     _w = '.'
  835.     def __init__(self, screenName=None, baseName=None, className='Tk'):
  836.         global _default_root
  837.         self.master = None
  838.         self.children = {}
  839.         if baseName is None:
  840.             import sys, os
  841.             baseName = os.path.basename(sys.argv[0])
  842.             baseName, ext = os.path.splitext(baseName)
  843.             if ext not in ('.py', 'pyc'): baseName = baseName + ext
  844.         self.tk = _tkinter.create(screenName, baseName, className)
  845.         try:
  846.             # Disable event scanning except for Command-Period
  847.             import MacOS
  848.             try:
  849.                 MacOS.SchedParams(1, 0)
  850.             except AttributeError:
  851.                 # pre-1.5, use old routine
  852.                 MacOS.EnableAppswitch(0)
  853.         except ImportError:
  854.             pass
  855.         else:
  856.             # Work around nasty MacTk bug
  857.             self.update()
  858.         # Version sanity checks
  859.         tk_version = self.tk.getvar('tk_version')
  860.         if tk_version != _tkinter.TK_VERSION:
  861.             raise RuntimeError, \
  862.             "tk.h version (%s) doesn't match libtk.a version (%s)" \
  863.             % (_tkinter.TK_VERSION, tk_version)
  864.         tcl_version = self.tk.getvar('tcl_version')
  865.         if tcl_version != _tkinter.TCL_VERSION:
  866.             raise RuntimeError, \
  867.             "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  868.             % (_tkinter.TCL_VERSION, tcl_version)
  869.         if TkVersion < 4.0:
  870.             raise RuntimeError, \
  871.             "Tk 4.0 or higher is required; found Tk %s" \
  872.             % str(TkVersion)
  873.         self.tk.createcommand('tkerror', _tkerror)
  874.         self.tk.createcommand('exit', _exit)
  875.         self.readprofile(baseName, className)
  876.         if _support_default_root and not _default_root:
  877.             _default_root = self
  878.     def destroy(self):
  879.         for c in self.children.values(): c.destroy()
  880.         self.tk.call('destroy', self._w)
  881.         Misc.destroy(self)
  882.         global _default_root
  883.         if _support_default_root and _default_root is self:
  884.             _default_root = None
  885.     def readprofile(self, baseName, className):
  886.         import os
  887.         if os.environ.has_key('HOME'): home = os.environ['HOME']
  888.         else: home = os.curdir
  889.         class_tcl = os.path.join(home, '.%s.tcl' % className)
  890.         class_py = os.path.join(home, '.%s.py' % className)
  891.         base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  892.         base_py = os.path.join(home, '.%s.py' % baseName)
  893.         dir = {'self': self}
  894.         exec 'from Tkinter import *' in dir
  895.         if os.path.isfile(class_tcl):
  896.             print 'source', `class_tcl`
  897.             self.tk.call('source', class_tcl)
  898.         if os.path.isfile(class_py):
  899.             print 'execfile', `class_py`
  900.             execfile(class_py, dir)
  901.         if os.path.isfile(base_tcl):
  902.             print 'source', `base_tcl`
  903.             self.tk.call('source', base_tcl)
  904.         if os.path.isfile(base_py):
  905.             print 'execfile', `base_py`
  906.             execfile(base_py, dir)
  907.     def report_callback_exception(self, exc, val, tb):
  908.         import traceback
  909.         print "Exception in Tkinter callback"
  910.         traceback.print_exception(exc, val, tb)
  911.  
  912. # Ideally, the classes Pack, Place and Grid disappear, the
  913. # pack/place/grid methods are defined on the Widget class, and
  914. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  915. # ...), with pack(), place() and grid() being short for
  916. # pack_configure(), place_configure() and grid_columnconfigure(), and
  917. # forget() being short for pack_forget().  As a practical matter, I'm
  918. # afraid that there is too much code out there that may be using the
  919. # Pack, Place or Grid class, so I leave them intact -- but only as
  920. # backwards compatibility features.  Also note that those methods that
  921. # take a master as argument (e.g. pack_propagate) have been moved to
  922. # the Misc class (which now incorporates all methods common between
  923. # toplevel and interior widgets).  Again, for compatibility, these are
  924. # copied into the Pack, Place or Grid class.
  925.  
  926. class Pack:
  927.     def pack_configure(self, cnf={}, **kw):
  928.         apply(self.tk.call, 
  929.               ('pack', 'configure', self._w) 
  930.               + self._options(cnf, kw))
  931.     pack = configure = config = pack_configure
  932.     def pack_forget(self):
  933.         self.tk.call('pack', 'forget', self._w)
  934.     forget = pack_forget
  935.     def pack_info(self):
  936.         words = self.tk.splitlist(
  937.             self.tk.call('pack', 'info', self._w))
  938.         dict = {}
  939.         for i in range(0, len(words), 2):
  940.             key = words[i][1:]
  941.             value = words[i+1]
  942.             if value[:1] == '.':
  943.                 value = self._nametowidget(value)
  944.             dict[key] = value
  945.         return dict
  946.     info = pack_info
  947.     propagate = pack_propagate = Misc.pack_propagate
  948.     slaves = pack_slaves = Misc.pack_slaves
  949.  
  950. class Place:
  951.     def place_configure(self, cnf={}, **kw):
  952.         for k in ['in_']:
  953.             if kw.has_key(k):
  954.                 kw[k[:-1]] = kw[k]
  955.                 del kw[k]
  956.         apply(self.tk.call, 
  957.               ('place', 'configure', self._w) 
  958.               + self._options(cnf, kw))
  959.     place = configure = config = place_configure
  960.     def place_forget(self):
  961.         self.tk.call('place', 'forget', self._w)
  962.     forget = place_forget
  963.     def place_info(self):
  964.         words = self.tk.splitlist(
  965.             self.tk.call('place', 'info', self._w))
  966.         dict = {}
  967.         for i in range(0, len(words), 2):
  968.             key = words[i][1:]
  969.             value = words[i+1]
  970.             if value[:1] == '.':
  971.                 value = self._nametowidget(value)
  972.             dict[key] = value
  973.         return dict
  974.     info = place_info
  975.     slaves = place_slaves = Misc.place_slaves
  976.  
  977. class Grid:
  978.     # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  979.     def grid_configure(self, cnf={}, **kw):
  980.         apply(self.tk.call, 
  981.               ('grid', 'configure', self._w) 
  982.               + self._options(cnf, kw))
  983.     grid = configure = config = grid_configure
  984.     bbox = grid_bbox = Misc.grid_bbox
  985.     columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  986.     def grid_forget(self):
  987.         self.tk.call('grid', 'forget', self._w)
  988.     forget = grid_forget
  989.     def grid_info(self):
  990.         words = self.tk.splitlist(
  991.             self.tk.call('grid', 'info', self._w))
  992.         dict = {}
  993.         for i in range(0, len(words), 2):
  994.             key = words[i][1:]
  995.             value = words[i+1]
  996.             if value[:1] == '.':
  997.                 value = self._nametowidget(value)
  998.             dict[key] = value
  999.         return dict
  1000.     info = grid_info
  1001.     def grid_location(self, x, y):
  1002.         return self._getints(
  1003.             self.tk.call(
  1004.                 'grid', 'location', self._w, x, y)) or None
  1005.     location = grid_location
  1006.     propagate = grid_propagate = Misc.grid_propagate
  1007.     rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  1008.     size = grid_size = Misc.grid_size
  1009.     slaves = grid_slaves = Misc.grid_slaves
  1010.  
  1011. class BaseWidget(Misc):
  1012.     def _setup(self, master, cnf):
  1013.         if _support_default_root:
  1014.             global _default_root
  1015.             if not master:
  1016.                 if not _default_root:
  1017.                     _default_root = Tk()
  1018.                 master = _default_root
  1019.             if not _default_root:
  1020.                 _default_root = master
  1021.         self.master = master
  1022.         self.tk = master.tk
  1023.         name = None
  1024.         if cnf.has_key('name'):
  1025.             name = cnf['name']
  1026.             del cnf['name']
  1027.         if not name:
  1028.             name = `id(self)`
  1029.         self._name = name
  1030.         if master._w=='.':
  1031.             self._w = '.' + name
  1032.         else:
  1033.             self._w = master._w + '.' + name
  1034.         self.children = {}
  1035.         if self.master.children.has_key(self._name):
  1036.             self.master.children[self._name].destroy()
  1037.         self.master.children[self._name] = self
  1038.     def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  1039.         if kw:
  1040.             cnf = _cnfmerge((cnf, kw))
  1041.         self.widgetName = widgetName
  1042.         BaseWidget._setup(self, master, cnf)
  1043.         classes = []
  1044.         for k in cnf.keys():
  1045.             if type(k) is ClassType:
  1046.                 classes.append((k, cnf[k]))
  1047.                 del cnf[k]
  1048.         apply(self.tk.call,
  1049.               (widgetName, self._w) + extra + self._options(cnf))
  1050.         for k, v in classes:
  1051.             k.configure(self, v)
  1052.     def destroy(self):
  1053.         for c in self.children.values(): c.destroy()
  1054.         if self.master.children.has_key(self._name):
  1055.             del self.master.children[self._name]
  1056.         self.tk.call('destroy', self._w)
  1057.         Misc.destroy(self)
  1058.     def _do(self, name, args=()):
  1059.         return apply(self.tk.call, (self._w, name) + args)
  1060.  
  1061. class Widget(BaseWidget, Pack, Place, Grid):
  1062.     pass
  1063.  
  1064. class Toplevel(BaseWidget, Wm):
  1065.     def __init__(self, master=None, cnf={}, **kw):
  1066.         if kw:
  1067.             cnf = _cnfmerge((cnf, kw))
  1068.         extra = ()
  1069.         for wmkey in ['screen', 'class_', 'class', 'visual',
  1070.                   'colormap']:
  1071.             if cnf.has_key(wmkey):
  1072.                 val = cnf[wmkey]
  1073.                 # TBD: a hack needed because some keys
  1074.                 # are not valid as keyword arguments
  1075.                 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  1076.                 else: opt = '-'+wmkey
  1077.                 extra = extra + (opt, val)
  1078.                 del cnf[wmkey]
  1079.         BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  1080.         root = self._root()
  1081.         self.iconname(root.iconname())
  1082.         self.title(root.title())
  1083.  
  1084. class Button(Widget):
  1085.     def __init__(self, master=None, cnf={}, **kw):
  1086.         Widget.__init__(self, master, 'button', cnf, kw)
  1087.     def tkButtonEnter(self, *dummy):
  1088.         self.tk.call('tkButtonEnter', self._w)
  1089.     def tkButtonLeave(self, *dummy):
  1090.         self.tk.call('tkButtonLeave', self._w)
  1091.     def tkButtonDown(self, *dummy):
  1092.         self.tk.call('tkButtonDown', self._w)
  1093.     def tkButtonUp(self, *dummy):
  1094.         self.tk.call('tkButtonUp', self._w)
  1095.     def tkButtonInvoke(self, *dummy):
  1096.         self.tk.call('tkButtonInvoke', self._w)
  1097.     def flash(self):
  1098.         self.tk.call(self._w, 'flash')
  1099.     def invoke(self):
  1100.         return self.tk.call(self._w, 'invoke')
  1101.  
  1102. # Indices:
  1103. # XXX I don't like these -- take them away
  1104. def AtEnd():
  1105.     return 'end'
  1106. def AtInsert(*args):
  1107.     s = 'insert'
  1108.     for a in args:
  1109.         if a: s = s + (' ' + a)
  1110.     return s
  1111. def AtSelFirst():
  1112.     return 'sel.first'
  1113. def AtSelLast():
  1114.     return 'sel.last'
  1115. def At(x, y=None):
  1116.     if y is None:
  1117.         return '@' + `x`        
  1118.     else:
  1119.         return '@' + `x` + ',' + `y`
  1120.  
  1121. class Canvas(Widget):
  1122.     def __init__(self, master=None, cnf={}, **kw):
  1123.         Widget.__init__(self, master, 'canvas', cnf, kw)
  1124.     def addtag(self, *args):
  1125.         self._do('addtag', args)
  1126.     def addtag_above(self, newtag, tagOrId):
  1127.         self.addtag(newtag, 'above', tagOrId)
  1128.     def addtag_all(self, newtag):
  1129.         self.addtag(newtag, 'all')
  1130.     def addtag_below(self, newtag, tagOrId):
  1131.         self.addtag(newtag, 'below', tagOrId)
  1132.     def addtag_closest(self, newtag, x, y, halo=None, start=None):
  1133.         self.addtag(newtag, 'closest', x, y, halo, start)
  1134.     def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  1135.         self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  1136.     def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  1137.         self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  1138.     def addtag_withtag(self, newtag, tagOrId):
  1139.         self.addtag(newtag, 'withtag', tagOrId)
  1140.     def bbox(self, *args):
  1141.         return self._getints(self._do('bbox', args)) or None
  1142.     def tag_unbind(self, tagOrId, sequence, funcid=None):
  1143.         self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  1144.         if funcid:
  1145.             self.deletecommand(funcid)
  1146.     def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  1147.         return self._bind((self._w, 'bind', tagOrId),
  1148.                   sequence, func, add)
  1149.     def canvasx(self, screenx, gridspacing=None):
  1150.         return self.tk.getdouble(self.tk.call(
  1151.             self._w, 'canvasx', screenx, gridspacing))
  1152.     def canvasy(self, screeny, gridspacing=None):
  1153.         return self.tk.getdouble(self.tk.call(
  1154.             self._w, 'canvasy', screeny, gridspacing))
  1155.     def coords(self, *args):
  1156.         # XXX Should use _flatten on args
  1157.         return map(self.tk.getdouble,
  1158.                            self.tk.splitlist(self._do('coords', args)))
  1159.     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  1160.         args = _flatten(args)
  1161.         cnf = args[-1]
  1162.         if type(cnf) in (DictionaryType, TupleType):
  1163.             args = args[:-1]
  1164.         else:
  1165.             cnf = {}
  1166.         return self.tk.getint(apply(
  1167.             self.tk.call,
  1168.             (self._w, 'create', itemType) 
  1169.             + args + self._options(cnf, kw)))
  1170.     def create_arc(self, *args, **kw):
  1171.         return self._create('arc', args, kw)
  1172.     def create_bitmap(self, *args, **kw):
  1173.         return self._create('bitmap', args, kw)
  1174.     def create_image(self, *args, **kw):
  1175.         return self._create('image', args, kw)
  1176.     def create_line(self, *args, **kw):
  1177.         return self._create('line', args, kw)
  1178.     def create_oval(self, *args, **kw):
  1179.         return self._create('oval', args, kw)
  1180.     def create_polygon(self, *args, **kw):
  1181.         return self._create('polygon', args, kw)
  1182.     def create_rectangle(self, *args, **kw):
  1183.         return self._create('rectangle', args, kw)
  1184.     def create_text(self, *args, **kw):
  1185.         return self._create('text', args, kw)
  1186.     def create_window(self, *args, **kw):
  1187.         return self._create('window', args, kw)
  1188.     def dchars(self, *args):
  1189.         self._do('dchars', args)
  1190.     def delete(self, *args):
  1191.         self._do('delete', args)
  1192.     def dtag(self, *args):
  1193.         self._do('dtag', args)
  1194.     def find(self, *args):
  1195.         return self._getints(self._do('find', args)) or ()
  1196.     def find_above(self, tagOrId):
  1197.         return self.find('above', tagOrId)
  1198.     def find_all(self):
  1199.         return self.find('all')
  1200.     def find_below(self, tagOrId):
  1201.         return self.find('below', tagOrId)
  1202.     def find_closest(self, x, y, halo=None, start=None):
  1203.         return self.find('closest', x, y, halo, start)
  1204.     def find_enclosed(self, x1, y1, x2, y2):
  1205.         return self.find('enclosed', x1, y1, x2, y2)
  1206.     def find_overlapping(self, x1, y1, x2, y2):
  1207.         return self.find('overlapping', x1, y1, x2, y2)
  1208.     def find_withtag(self, tagOrId):
  1209.         return self.find('withtag', tagOrId)
  1210.     def focus(self, *args):
  1211.         return self._do('focus', args)
  1212.     def gettags(self, *args):
  1213.         return self.tk.splitlist(self._do('gettags', args))
  1214.     def icursor(self, *args):
  1215.         self._do('icursor', args)
  1216.     def index(self, *args):
  1217.         return self.tk.getint(self._do('index', args))
  1218.     def insert(self, *args):
  1219.         self._do('insert', args)
  1220.     def itemcget(self, tagOrId, option):
  1221.         return self._do('itemcget', (tagOrId, '-'+option))
  1222.     def itemconfigure(self, tagOrId, cnf=None, **kw):
  1223.         if cnf is None and not kw:
  1224.             cnf = {}
  1225.             for x in self.tk.split(
  1226.                 self._do('itemconfigure', (tagOrId,))):
  1227.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1228.             return cnf
  1229.         if type(cnf) == StringType and not kw:
  1230.             x = self.tk.split(self._do('itemconfigure',
  1231.                            (tagOrId, '-'+cnf,)))
  1232.             return (x[0][1:],) + x[1:]
  1233.         self._do('itemconfigure', (tagOrId,)
  1234.              + self._options(cnf, kw))
  1235.     itemconfig = itemconfigure
  1236.     def lower(self, *args):
  1237.         self._do('lower', args)
  1238.     def move(self, *args):
  1239.         self._do('move', args)
  1240.     def postscript(self, cnf={}, **kw):
  1241.         return self._do('postscript', self._options(cnf, kw))
  1242.     def tkraise(self, *args):
  1243.         self._do('raise', args)
  1244.     lift = tkraise
  1245.     def scale(self, *args):
  1246.         self._do('scale', args)
  1247.     def scan_mark(self, x, y):
  1248.         self.tk.call(self._w, 'scan', 'mark', x, y)
  1249.     def scan_dragto(self, x, y):
  1250.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  1251.     def select_adjust(self, tagOrId, index):
  1252.         self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  1253.     def select_clear(self):
  1254.         self.tk.call(self._w, 'select', 'clear')
  1255.     def select_from(self, tagOrId, index):
  1256.         self.tk.call(self._w, 'select', 'from', tagOrId, index)
  1257.     def select_item(self):
  1258.         self.tk.call(self._w, 'select', 'item')
  1259.     def select_to(self, tagOrId, index):
  1260.         self.tk.call(self._w, 'select', 'to', tagOrId, index)
  1261.     def type(self, tagOrId):
  1262.         return self.tk.call(self._w, 'type', tagOrId) or None
  1263.     def xview(self, *args):
  1264.         if not args:
  1265.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  1266.         apply(self.tk.call, (self._w, 'xview')+args)
  1267.     def yview(self, *args):
  1268.         if not args:
  1269.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  1270.         apply(self.tk.call, (self._w, 'yview')+args)
  1271.  
  1272. class Checkbutton(Widget):
  1273.     def __init__(self, master=None, cnf={}, **kw):
  1274.         Widget.__init__(self, master, 'checkbutton', cnf, kw)
  1275.     def deselect(self):
  1276.         self.tk.call(self._w, 'deselect')
  1277.     def flash(self):
  1278.         self.tk.call(self._w, 'flash')
  1279.     def invoke(self):
  1280.         return self.tk.call(self._w, 'invoke')
  1281.     def select(self):
  1282.         self.tk.call(self._w, 'select')
  1283.     def toggle(self):
  1284.         self.tk.call(self._w, 'toggle')
  1285.  
  1286. class Entry(Widget):
  1287.     def __init__(self, master=None, cnf={}, **kw):
  1288.         Widget.__init__(self, master, 'entry', cnf, kw)
  1289.     def delete(self, first, last=None):
  1290.         self.tk.call(self._w, 'delete', first, last)
  1291.     def get(self):
  1292.         return self.tk.call(self._w, 'get')
  1293.     def icursor(self, index):
  1294.         self.tk.call(self._w, 'icursor', index)
  1295.     def index(self, index):
  1296.         return self.tk.getint(self.tk.call(
  1297.             self._w, 'index', index))
  1298.     def insert(self, index, string):
  1299.         self.tk.call(self._w, 'insert', index, string)
  1300.     def scan_mark(self, x):
  1301.         self.tk.call(self._w, 'scan', 'mark', x)
  1302.     def scan_dragto(self, x):
  1303.         self.tk.call(self._w, 'scan', 'dragto', x)
  1304.     def selection_adjust(self, index):
  1305.         self.tk.call(self._w, 'selection', 'adjust', index)
  1306.     select_adjust = selection_adjust
  1307.     def selection_clear(self):
  1308.         self.tk.call(self._w, 'selection', 'clear')
  1309.     select_clear = selection_clear
  1310.     def selection_from(self, index):
  1311.         self.tk.call(self._w, 'selection', 'from', index)
  1312.     select_from = selection_from
  1313.     def selection_present(self):
  1314.         return self.tk.getboolean(
  1315.             self.tk.call(self._w, 'selection', 'present'))
  1316.     select_present = selection_present
  1317.     def selection_range(self, start, end):
  1318.         self.tk.call(self._w, 'selection', 'range', start, end)
  1319.     select_range = selection_range
  1320.     def selection_to(self, index):
  1321.         self.tk.call(self._w, 'selection', 'to', index)
  1322.     select_to = selection_to
  1323.     def xview(self, index):
  1324.         self.tk.call(self._w, 'xview', index)
  1325.     def xview_moveto(self, fraction):
  1326.         self.tk.call(self._w, 'xview', 'moveto', fraction)
  1327.     def xview_scroll(self, number, what):
  1328.         self.tk.call(self._w, 'xview', 'scroll', number, what)
  1329.  
  1330. class Frame(Widget):
  1331.     def __init__(self, master=None, cnf={}, **kw):
  1332.         cnf = _cnfmerge((cnf, kw))
  1333.         extra = ()
  1334.         if cnf.has_key('class_'):
  1335.             extra = ('-class', cnf['class_'])
  1336.             del cnf['class_']
  1337.         elif cnf.has_key('class'):
  1338.             extra = ('-class', cnf['class'])
  1339.             del cnf['class']
  1340.         Widget.__init__(self, master, 'frame', cnf, {}, extra)
  1341.  
  1342. class Label(Widget):
  1343.     def __init__(self, master=None, cnf={}, **kw):
  1344.         Widget.__init__(self, master, 'label', cnf, kw)
  1345.  
  1346. class Listbox(Widget):
  1347.     def __init__(self, master=None, cnf={}, **kw):
  1348.         Widget.__init__(self, master, 'listbox', cnf, kw)
  1349.     def activate(self, index):
  1350.         self.tk.call(self._w, 'activate', index)
  1351.     def bbox(self, *args):
  1352.         return self._getints(self._do('bbox', args)) or None
  1353.     def curselection(self):
  1354.         # XXX Ought to apply self._getints()...
  1355.         return self.tk.splitlist(self.tk.call(
  1356.             self._w, 'curselection'))
  1357.     def delete(self, first, last=None):
  1358.         self.tk.call(self._w, 'delete', first, last)
  1359.     def get(self, first, last=None):
  1360.         if last:
  1361.             return self.tk.splitlist(self.tk.call(
  1362.                 self._w, 'get', first, last))
  1363.         else:
  1364.             return self.tk.call(self._w, 'get', first)
  1365.     def insert(self, index, *elements):
  1366.         apply(self.tk.call,
  1367.               (self._w, 'insert', index) + elements)
  1368.     def nearest(self, y):
  1369.         return self.tk.getint(self.tk.call(
  1370.             self._w, 'nearest', y))
  1371.     def scan_mark(self, x, y):
  1372.         self.tk.call(self._w, 'scan', 'mark', x, y)
  1373.     def scan_dragto(self, x, y):
  1374.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  1375.     def see(self, index):
  1376.         self.tk.call(self._w, 'see', index)
  1377.     def index(self, index):
  1378.         i = self.tk.call(self._w, 'index', index)
  1379.         if i == 'none': return None
  1380.         return self.tk.getint(i)
  1381.     def select_anchor(self, index):
  1382.         self.tk.call(self._w, 'selection', 'anchor', index)
  1383.     selection_anchor = select_anchor
  1384.     def select_clear(self, first, last=None):
  1385.         self.tk.call(self._w,
  1386.                  'selection', 'clear', first, last)
  1387.     selection_clear = select_clear
  1388.     def select_includes(self, index):
  1389.         return self.tk.getboolean(self.tk.call(
  1390.             self._w, 'selection', 'includes', index))
  1391.     selection_includes = select_includes
  1392.     def select_set(self, first, last=None):
  1393.         self.tk.call(self._w, 'selection', 'set', first, last)
  1394.     selection_set = select_set
  1395.     def size(self):
  1396.         return self.tk.getint(self.tk.call(self._w, 'size'))
  1397.     def xview(self, *what):
  1398.         if not what:
  1399.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  1400.         apply(self.tk.call, (self._w, 'xview')+what)
  1401.     def yview(self, *what):
  1402.         if not what:
  1403.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  1404.         apply(self.tk.call, (self._w, 'yview')+what)
  1405.  
  1406. class Menu(Widget):
  1407.     def __init__(self, master=None, cnf={}, **kw):
  1408.         Widget.__init__(self, master, 'menu', cnf, kw)
  1409.     def tk_bindForTraversal(self):
  1410.         pass # obsolete since Tk 4.0
  1411.     def tk_mbPost(self):
  1412.         self.tk.call('tk_mbPost', self._w)
  1413.     def tk_mbUnpost(self):
  1414.         self.tk.call('tk_mbUnpost')
  1415.     def tk_traverseToMenu(self, char):
  1416.         self.tk.call('tk_traverseToMenu', self._w, char)
  1417.     def tk_traverseWithinMenu(self, char):
  1418.         self.tk.call('tk_traverseWithinMenu', self._w, char)
  1419.     def tk_getMenuButtons(self):
  1420.         return self.tk.call('tk_getMenuButtons', self._w)
  1421.     def tk_nextMenu(self, count):
  1422.         self.tk.call('tk_nextMenu', count)
  1423.     def tk_nextMenuEntry(self, count):
  1424.         self.tk.call('tk_nextMenuEntry', count)
  1425.     def tk_invokeMenu(self):
  1426.         self.tk.call('tk_invokeMenu', self._w)
  1427.     def tk_firstMenu(self):
  1428.         self.tk.call('tk_firstMenu', self._w)
  1429.     def tk_mbButtonDown(self):
  1430.         self.tk.call('tk_mbButtonDown', self._w)
  1431.     def tk_popup(self, x, y, entry=""):
  1432.         self.tk.call('tk_popup', self._w, x, y, entry)
  1433.     def activate(self, index):
  1434.         self.tk.call(self._w, 'activate', index)
  1435.     def add(self, itemType, cnf={}, **kw):
  1436.         apply(self.tk.call, (self._w, 'add', itemType) 
  1437.               + self._options(cnf, kw))
  1438.     def add_cascade(self, cnf={}, **kw):
  1439.         self.add('cascade', cnf or kw)
  1440.     def add_checkbutton(self, cnf={}, **kw):
  1441.         self.add('checkbutton', cnf or kw)
  1442.     def add_command(self, cnf={}, **kw):
  1443.         self.add('command', cnf or kw)
  1444.     def add_radiobutton(self, cnf={}, **kw):
  1445.         self.add('radiobutton', cnf or kw)
  1446.     def add_separator(self, cnf={}, **kw):
  1447.         self.add('separator', cnf or kw)
  1448.     def insert(self, index, itemType, cnf={}, **kw):
  1449.         apply(self.tk.call, (self._w, 'insert', index, itemType) 
  1450.               + self._options(cnf, kw))
  1451.     def insert_cascade(self, index, cnf={}, **kw):
  1452.         self.insert(index, 'cascade', cnf or kw)
  1453.     def insert_checkbutton(self, index, cnf={}, **kw):
  1454.         self.insert(index, 'checkbutton', cnf or kw)
  1455.     def insert_command(self, index, cnf={}, **kw):
  1456.         self.insert(index, 'command', cnf or kw)
  1457.     def insert_radiobutton(self, index, cnf={}, **kw):
  1458.         self.insert(index, 'radiobutton', cnf or kw)
  1459.     def insert_separator(self, index, cnf={}, **kw):
  1460.         self.insert(index, 'separator', cnf or kw)
  1461.     def delete(self, index1, index2=None):
  1462.         self.tk.call(self._w, 'delete', index1, index2)
  1463.     def entrycget(self, index, option):
  1464.         return self.tk.call(self._w, 'entrycget', index, '-' + option)
  1465.     def entryconfigure(self, index, cnf=None, **kw):
  1466.         if cnf is None and not kw:
  1467.             cnf = {}
  1468.             for x in self.tk.split(apply(self.tk.call,
  1469.                 (self._w, 'entryconfigure', index))):
  1470.                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1471.             return cnf
  1472.         if type(cnf) == StringType and not kw:
  1473.             x = self.tk.split(apply(self.tk.call,
  1474.                 (self._w, 'entryconfigure', index, '-'+cnf)))
  1475.             return (x[0][1:],) + x[1:]
  1476.         apply(self.tk.call, (self._w, 'entryconfigure', index)
  1477.               + self._options(cnf, kw))
  1478.     entryconfig = entryconfigure
  1479.     def index(self, index):
  1480.         i = self.tk.call(self._w, 'index', index)
  1481.         if i == 'none': return None
  1482.         return self.tk.getint(i)
  1483.     def invoke(self, index):
  1484.         return self.tk.call(self._w, 'invoke', index)
  1485.     def post(self, x, y):
  1486.         self.tk.call(self._w, 'post', x, y)
  1487.     def type(self, index):
  1488.         return self.tk.call(self._w, 'type', index)
  1489.     def unpost(self):
  1490.         self.tk.call(self._w, 'unpost')
  1491.     def yposition(self, index):
  1492.         return self.tk.getint(self.tk.call(
  1493.             self._w, 'yposition', index))
  1494.  
  1495. class Menubutton(Widget):
  1496.     def __init__(self, master=None, cnf={}, **kw):
  1497.         Widget.__init__(self, master, 'menubutton', cnf, kw)
  1498.  
  1499. class Message(Widget):
  1500.     def __init__(self, master=None, cnf={}, **kw):
  1501.         Widget.__init__(self, master, 'message', cnf, kw)
  1502.  
  1503. class Radiobutton(Widget):
  1504.     def __init__(self, master=None, cnf={}, **kw):
  1505.         Widget.__init__(self, master, 'radiobutton', cnf, kw)
  1506.     def deselect(self):
  1507.         self.tk.call(self._w, 'deselect')
  1508.     def flash(self):
  1509.         self.tk.call(self._w, 'flash')
  1510.     def invoke(self):
  1511.         return self.tk.call(self._w, 'invoke')
  1512.     def select(self):
  1513.         self.tk.call(self._w, 'select')
  1514.  
  1515. class Scale(Widget):
  1516.     def __init__(self, master=None, cnf={}, **kw):
  1517.         Widget.__init__(self, master, 'scale', cnf, kw)
  1518.     def get(self):
  1519.         value = self.tk.call(self._w, 'get')
  1520.         try:
  1521.             return self.tk.getint(value)
  1522.         except TclError:
  1523.             return self.tk.getdouble(value)
  1524.     def set(self, value):
  1525.         self.tk.call(self._w, 'set', value)
  1526.  
  1527. class Scrollbar(Widget):
  1528.     def __init__(self, master=None, cnf={}, **kw):
  1529.         Widget.__init__(self, master, 'scrollbar', cnf, kw)
  1530.     def activate(self, index):
  1531.         self.tk.call(self._w, 'activate', index)
  1532.     def delta(self, deltax, deltay):
  1533.         return self.getdouble(self.tk.call(
  1534.             self._w, 'delta', deltax, deltay))
  1535.     def fraction(self, x, y):
  1536.         return self.getdouble(self.tk.call(
  1537.             self._w, 'fraction', x, y))
  1538.     def identify(self, x, y):
  1539.         return self.tk.call(self._w, 'identify', x, y)
  1540.     def get(self):
  1541.         return self._getdoubles(self.tk.call(self._w, 'get'))
  1542.     def set(self, *args):
  1543.         apply(self.tk.call, (self._w, 'set')+args)
  1544.  
  1545. class Text(Widget):
  1546.     def __init__(self, master=None, cnf={}, **kw):
  1547.         Widget.__init__(self, master, 'text', cnf, kw)
  1548.     def bbox(self, *args):
  1549.         return self._getints(self._do('bbox', args)) or None
  1550.     def tk_textSelectTo(self, index):
  1551.         self.tk.call('tk_textSelectTo', self._w, index)
  1552.     def tk_textBackspace(self):
  1553.         self.tk.call('tk_textBackspace', self._w)
  1554.     def tk_textIndexCloser(self, a, b, c):
  1555.         self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  1556.     def tk_textResetAnchor(self, index):
  1557.         self.tk.call('tk_textResetAnchor', self._w, index)
  1558.     def compare(self, index1, op, index2):
  1559.         return self.tk.getboolean(self.tk.call(
  1560.             self._w, 'compare', index1, op, index2))
  1561.     def debug(self, boolean=None):
  1562.         return self.tk.getboolean(self.tk.call(
  1563.             self._w, 'debug', boolean))
  1564.     def delete(self, index1, index2=None):
  1565.         self.tk.call(self._w, 'delete', index1, index2)
  1566.     def dlineinfo(self, index):
  1567.         return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  1568.     def get(self, index1, index2=None):
  1569.         return self.tk.call(self._w, 'get', index1, index2)
  1570.     def index(self, index):
  1571.         return self.tk.call(self._w, 'index', index)
  1572.     def insert(self, index, chars, *args):
  1573.         apply(self.tk.call, (self._w, 'insert', index, chars)+args)
  1574.     def mark_gravity(self, markName, direction=None):
  1575.         return apply(self.tk.call,
  1576.                  (self._w, 'mark', 'gravity', markName, direction))
  1577.     def mark_names(self):
  1578.         return self.tk.splitlist(self.tk.call(
  1579.             self._w, 'mark', 'names'))
  1580.     def mark_set(self, markName, index):
  1581.         self.tk.call(self._w, 'mark', 'set', markName, index)
  1582.     def mark_unset(self, *markNames):
  1583.         apply(self.tk.call, (self._w, 'mark', 'unset') + markNames)
  1584.     def scan_mark(self, x, y):
  1585.         self.tk.call(self._w, 'scan', 'mark', x, y)
  1586.     def scan_dragto(self, x, y):
  1587.         self.tk.call(self._w, 'scan', 'dragto', x, y)
  1588.     def search(self, pattern, index, stopindex=None,
  1589.            forwards=None, backwards=None, exact=None,
  1590.            regexp=None, nocase=None, count=None):
  1591.         args = [self._w, 'search']
  1592.         if forwards: args.append('-forwards')
  1593.         if backwards: args.append('-backwards')
  1594.         if exact: args.append('-exact')
  1595.         if regexp: args.append('-regexp')
  1596.         if nocase: args.append('-nocase')
  1597.         if count: args.append('-count'); args.append(count)
  1598.         if pattern[0] == '-': args.append('--')
  1599.         args.append(pattern)
  1600.         args.append(index)
  1601.         if stopindex: args.append(stopindex)
  1602.         return apply(self.tk.call, tuple(args))
  1603.     def see(self, index):
  1604.         self.tk.call(self._w, 'see', index)
  1605.     def tag_add(self, tagName, index1, index2=None):
  1606.         self.tk.call(
  1607.             self._w, 'tag', 'add', tagName, index1, index2)
  1608.     def tag_unbind(self, tagName, sequence, funcid=None):
  1609.         self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  1610.         if funcid:
  1611.             self.deletecommand(funcid)
  1612.     def tag_bind(self, tagName, sequence, func, add=None):
  1613.         return self._bind((self._w, 'tag', 'bind', tagName),
  1614.                   sequence, func, add)
  1615.     def tag_cget(self, tagName, option):
  1616.         if option[:1] != '-':
  1617.             option = '-' + option
  1618.         if option[-1:] == '_':
  1619.             option = option[:-1]
  1620.         return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  1621.     def tag_configure(self, tagName, cnf={}, **kw):
  1622.         if type(cnf) == StringType:
  1623.             x = self.tk.split(self.tk.call(
  1624.                 self._w, 'tag', 'configure', tagName, '-'+cnf))
  1625.             return (x[0][1:],) + x[1:]
  1626.         apply(self.tk.call, 
  1627.               (self._w, 'tag', 'configure', tagName)
  1628.               + self._options(cnf, kw))
  1629.     tag_config = tag_configure
  1630.     def tag_delete(self, *tagNames):
  1631.         apply(self.tk.call, (self._w, 'tag', 'delete') + tagNames)
  1632.     def tag_lower(self, tagName, belowThis=None):
  1633.         self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  1634.     def tag_names(self, index=None):
  1635.         return self.tk.splitlist(
  1636.             self.tk.call(self._w, 'tag', 'names', index))
  1637.     def tag_nextrange(self, tagName, index1, index2=None):
  1638.         return self.tk.splitlist(self.tk.call(
  1639.             self._w, 'tag', 'nextrange', tagName, index1, index2))
  1640.     def tag_prevrange(self, tagName, index1, index2=None):
  1641.         return self.tk.splitlist(self.tk.call(
  1642.             self._w, 'tag', 'prevrange', tagName, index1, index2))
  1643.     def tag_raise(self, tagName, aboveThis=None):
  1644.         self.tk.call(
  1645.             self._w, 'tag', 'raise', tagName, aboveThis)
  1646.     def tag_ranges(self, tagName):
  1647.         return self.tk.splitlist(self.tk.call(
  1648.             self._w, 'tag', 'ranges', tagName))
  1649.     def tag_remove(self, tagName, index1, index2=None):
  1650.         self.tk.call(
  1651.             self._w, 'tag', 'remove', tagName, index1, index2)
  1652.     def window_cget(self, index, option):
  1653.         if option[:1] != '-':
  1654.             option = '-' + option
  1655.         if option[-1:] == '_':
  1656.             option = option[:-1]
  1657.         return self.tk.call(self._w, 'window', 'cget', index, option)
  1658.     def window_configure(self, index, cnf={}, **kw):
  1659.         if type(cnf) == StringType:
  1660.             x = self.tk.split(self.tk.call(
  1661.                 self._w, 'window', 'configure',
  1662.                 index, '-'+cnf))
  1663.             return (x[0][1:],) + x[1:]
  1664.         apply(self.tk.call, 
  1665.               (self._w, 'window', 'configure', index)
  1666.               + self._options(cnf, kw))
  1667.     window_config = window_configure
  1668.     def window_create(self, index, cnf={}, **kw):
  1669.         apply(self.tk.call, 
  1670.               (self._w, 'window', 'create', index)
  1671.               + self._options(cnf, kw))
  1672.     def window_names(self):
  1673.         return self.tk.splitlist(
  1674.             self.tk.call(self._w, 'window', 'names'))
  1675.     def xview(self, *what):
  1676.         if not what:
  1677.             return self._getdoubles(self.tk.call(self._w, 'xview'))
  1678.         apply(self.tk.call, (self._w, 'xview')+what)
  1679.     def yview(self, *what):
  1680.         if not what:
  1681.             return self._getdoubles(self.tk.call(self._w, 'yview'))
  1682.         apply(self.tk.call, (self._w, 'yview')+what)
  1683.     def yview_pickplace(self, *what):
  1684.         apply(self.tk.call, (self._w, 'yview', '-pickplace')+what)
  1685.  
  1686. class _setit:
  1687.     def __init__(self, var, value):
  1688.         self.__value = value
  1689.         self.__var = var
  1690.     def __call__(self, *args):
  1691.         self.__var.set(self.__value)
  1692.  
  1693. class OptionMenu(Menubutton):
  1694.     def __init__(self, master, variable, value, *values):
  1695.         kw = {"borderwidth": 2, "textvariable": variable,
  1696.               "indicatoron": 1, "relief": RAISED, "anchor": "c",
  1697.               "highlightthickness": 2}
  1698.         Widget.__init__(self, master, "menubutton", kw)
  1699.         self.widgetName = 'tk_optionMenu'
  1700.         menu = self.__menu = Menu(self, name="menu", tearoff=0)
  1701.         self.menuname = menu._w
  1702.         menu.add_command(label=value, command=_setit(variable, value))
  1703.         for v in values:
  1704.             menu.add_command(label=v, command=_setit(variable, v))
  1705.         self["menu"] = menu
  1706.  
  1707.     def __getitem__(self, name):
  1708.         if name == 'menu':
  1709.             return self.__menu
  1710.         return Widget.__getitem__(self, name)
  1711.  
  1712.     def destroy(self):
  1713.         Menubutton.destroy(self)
  1714.         self.__menu = None
  1715.  
  1716. class Image:
  1717.     def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  1718.         self.name = None
  1719.         if not master:
  1720.             master = _default_root
  1721.             if not master:
  1722.                 raise RuntimeError, 'Too early to create image'
  1723.         self.tk = master.tk
  1724.         if not name:
  1725.             name = `id(self)`
  1726.             # The following is needed for systems where id(x)
  1727.             # can return a negative number, such as Linux/m68k:
  1728.             if name[0] == '-': name = '_' + name[1:]
  1729.         if kw and cnf: cnf = _cnfmerge((cnf, kw))
  1730.         elif kw: cnf = kw
  1731.         options = ()
  1732.         for k, v in cnf.items():
  1733.             if callable(v):
  1734.                 v = self._register(v)
  1735.             options = options + ('-'+k, v)
  1736.         apply(self.tk.call,
  1737.               ('image', 'create', imgtype, name,) + options)
  1738.         self.name = name
  1739.     def __str__(self): return self.name
  1740.     def __del__(self):
  1741.         if self.name:
  1742.             self.tk.call('image', 'delete', self.name)
  1743.     def __setitem__(self, key, value):
  1744.         self.tk.call(self.name, 'configure', '-'+key, value)
  1745.     def __getitem__(self, key):
  1746.         return self.tk.call(self.name, 'configure', '-'+key)
  1747.     def configure(self, **kw):
  1748.         res = ()
  1749.         for k, v in _cnfmerge(kw).items():
  1750.             if v is not None:
  1751.                 if k[-1] == '_': k = k[:-1]
  1752.                 if callable(v):
  1753.                     v = self._register(v)
  1754.                 res = res + ('-'+k, v)
  1755.         apply(self.tk.call, (self.name, 'config') + res)
  1756.     config = configure
  1757.     def height(self):
  1758.         return self.tk.getint(
  1759.             self.tk.call('image', 'height', self.name))
  1760.     def type(self):
  1761.         return self.tk.call('image', 'type', self.name)
  1762.     def width(self):
  1763.         return self.tk.getint(
  1764.             self.tk.call('image', 'width', self.name))
  1765.  
  1766. class PhotoImage(Image):
  1767.     def __init__(self, name=None, cnf={}, master=None, **kw):
  1768.         apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
  1769.     def blank(self):
  1770.         self.tk.call(self.name, 'blank')
  1771.     def cget(self, option):
  1772.         return self.tk.call(self.name, 'cget', '-' + option)
  1773.     # XXX config
  1774.     def __getitem__(self, key):
  1775.         return self.tk.call(self.name, 'cget', '-' + key)
  1776.     # XXX copy -from, -to, ...?
  1777.     def copy(self):
  1778.         destImage = PhotoImage()
  1779.         self.tk.call(destImage, 'copy', self.name)
  1780.         return destImage
  1781.     def zoom(self,x,y=''):
  1782.         destImage = PhotoImage()
  1783.         if y=='': y=x
  1784.         self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  1785.         return destImage
  1786.     def subsample(self,x,y=''):
  1787.         destImage = PhotoImage()
  1788.         if y=='': y=x
  1789.         self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  1790.         return destImage
  1791.     def get(self, x, y):
  1792.         return self.tk.call(self.name, 'get', x, y)
  1793.     def put(self, data, to=None):
  1794.         args = (self.name, 'put', data)
  1795.         if to:
  1796.             if to[0] == '-to':
  1797.                 to = to[1:]
  1798.             args = args + ('-to',) + tuple(to)
  1799.         apply(self.tk.call, args)
  1800.     # XXX read
  1801.     def write(self, filename, format=None, from_coords=None):
  1802.         args = (self.name, 'write', filename)
  1803.         if format:
  1804.             args = args + ('-format', format)
  1805.         if from_coords:
  1806.             args = args + ('-from',) + tuple(from_coords)
  1807.         apply(self.tk.call, args)
  1808.  
  1809. class BitmapImage(Image):
  1810.     def __init__(self, name=None, cnf={}, master=None, **kw):
  1811.         apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
  1812.  
  1813. def image_names(): return _default_root.tk.call('image', 'names')
  1814. def image_types(): return _default_root.tk.call('image', 'types')
  1815.  
  1816. ######################################################################
  1817. # Extensions:
  1818.  
  1819. class Studbutton(Button):
  1820.     def __init__(self, master=None, cnf={}, **kw):
  1821.         Widget.__init__(self, master, 'studbutton', cnf, kw)
  1822.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  1823.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  1824.         self.bind('<1>',               self.tkButtonDown)
  1825.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  1826.  
  1827. class Tributton(Button):
  1828.     def __init__(self, master=None, cnf={}, **kw):
  1829.         Widget.__init__(self, master, 'tributton', cnf, kw)
  1830.         self.bind('<Any-Enter>',       self.tkButtonEnter)
  1831.         self.bind('<Any-Leave>',       self.tkButtonLeave)
  1832.         self.bind('<1>',               self.tkButtonDown)
  1833.         self.bind('<ButtonRelease-1>', self.tkButtonUp)
  1834.         self['fg']               = self['bg']
  1835.         self['activebackground'] = self['bg']
  1836.  
  1837. ######################################################################
  1838. # Test:
  1839.  
  1840. def _test():
  1841.     root = Tk()
  1842.     label = Label(root, text="Proof-of-existence test for Tk")
  1843.     label.pack()
  1844.     test = Button(root, text="Click me!",
  1845.               command=lambda root=root: root.test.configure(
  1846.                   text="[%s]" % root.test['text']))
  1847.     test.pack()
  1848.     root.test = test
  1849.     quit = Button(root, text="QUIT", command=root.destroy)
  1850.     quit.pack()
  1851.     root.tkraise()
  1852.     root.mainloop()
  1853.  
  1854. if __name__ == '__main__':
  1855.     _test()
  1856.