home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / lib-tk / Tkinter.py < prev    next >
Text File  |  1997-12-29  |  60KB  |  1,828 lines

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