Back to index

python3.2  3.2.2
__init__.py
Go to the documentation of this file.
00001 """Wrapper functions for Tcl/Tk.
00002 
00003 Tkinter provides classes which allow the display, positioning and
00004 control of widgets. Toplevel widgets are Tk and Toplevel. Other
00005 widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
00006 Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
00007 LabelFrame and PanedWindow.
00008 
00009 Properties of the widgets are specified with keyword arguments.
00010 Keyword arguments have the same name as the corresponding resource
00011 under Tk.
00012 
00013 Widgets are positioned with one of the geometry managers Place, Pack
00014 or Grid. These managers can be called with methods place, pack, grid
00015 available in every Widget.
00016 
00017 Actions are bound to events by resources (e.g. keyword argument
00018 command) or with the method bind.
00019 
00020 Example (Hello, World):
00021 import tkinter
00022 from tkinter.constants import *
00023 tk = tkinter.Tk()
00024 frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
00025 frame.pack(fill=BOTH,expand=1)
00026 label = tkinter.Label(frame, text="Hello, World")
00027 label.pack(fill=X, expand=1)
00028 button = tkinter.Button(frame,text="Exit",command=tk.destroy)
00029 button.pack(side=BOTTOM)
00030 tk.mainloop()
00031 """
00032 
00033 __version__ = "$Revision$"
00034 
00035 import sys
00036 if sys.platform == "win32":
00037     # Attempt to configure Tcl/Tk without requiring PATH
00038     from tkinter import _fix
00039 import _tkinter # If this fails your Python may not be configured for Tk
00040 TclError = _tkinter.TclError
00041 from tkinter.constants import *
00042 
00043 wantobjects = 1
00044 
00045 TkVersion = float(_tkinter.TK_VERSION)
00046 TclVersion = float(_tkinter.TCL_VERSION)
00047 
00048 READABLE = _tkinter.READABLE
00049 WRITABLE = _tkinter.WRITABLE
00050 EXCEPTION = _tkinter.EXCEPTION
00051 
00052 
00053 def _flatten(seq):
00054     """Internal function."""
00055     res = ()
00056     for item in seq:
00057         if isinstance(item, (tuple, list)):
00058             res = res + _flatten(item)
00059         elif item is not None:
00060             res = res + (item,)
00061     return res
00062 
00063 try: _flatten = _tkinter._flatten
00064 except AttributeError: pass
00065 
00066 def _cnfmerge(cnfs):
00067     """Internal function."""
00068     if isinstance(cnfs, dict):
00069         return cnfs
00070     elif isinstance(cnfs, (type(None), str)):
00071         return cnfs
00072     else:
00073         cnf = {}
00074         for c in _flatten(cnfs):
00075             try:
00076                 cnf.update(c)
00077             except (AttributeError, TypeError) as msg:
00078                 print("_cnfmerge: fallback due to:", msg)
00079                 for k, v in c.items():
00080                     cnf[k] = v
00081         return cnf
00082 
00083 try: _cnfmerge = _tkinter._cnfmerge
00084 except AttributeError: pass
00085 
00086 class Event:
00087     """Container for the properties of an event.
00088 
00089     Instances of this type are generated if one of the following events occurs:
00090 
00091     KeyPress, KeyRelease - for keyboard events
00092     ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
00093     Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
00094     Colormap, Gravity, Reparent, Property, Destroy, Activate,
00095     Deactivate - for window events.
00096 
00097     If a callback function for one of these events is registered
00098     using bind, bind_all, bind_class, or tag_bind, the callback is
00099     called with an Event as first argument. It will have the
00100     following attributes (in braces are the event types for which
00101     the attribute is valid):
00102 
00103         serial - serial number of event
00104     num - mouse button pressed (ButtonPress, ButtonRelease)
00105     focus - whether the window has the focus (Enter, Leave)
00106     height - height of the exposed window (Configure, Expose)
00107     width - width of the exposed window (Configure, Expose)
00108     keycode - keycode of the pressed key (KeyPress, KeyRelease)
00109     state - state of the event as a number (ButtonPress, ButtonRelease,
00110                             Enter, KeyPress, KeyRelease,
00111                             Leave, Motion)
00112     state - state as a string (Visibility)
00113     time - when the event occurred
00114     x - x-position of the mouse
00115     y - y-position of the mouse
00116     x_root - x-position of the mouse on the screen
00117              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
00118     y_root - y-position of the mouse on the screen
00119              (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
00120     char - pressed character (KeyPress, KeyRelease)
00121     send_event - see X/Windows documentation
00122     keysym - keysym of the event as a string (KeyPress, KeyRelease)
00123     keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
00124     type - type of the event as a number
00125     widget - widget in which the event occurred
00126     delta - delta of wheel movement (MouseWheel)
00127     """
00128     pass
00129 
00130 _support_default_root = 1
00131 _default_root = None
00132 
00133 def NoDefaultRoot():
00134     """Inhibit setting of default root window.
00135 
00136     Call this function to inhibit that the first instance of
00137     Tk is used for windows without an explicit parent window.
00138     """
00139     global _support_default_root
00140     _support_default_root = 0
00141     global _default_root
00142     _default_root = None
00143     del _default_root
00144 
00145 def _tkerror(err):
00146     """Internal function."""
00147     pass
00148 
00149 def _exit(code='0'):
00150     """Internal function. Calling it will throw the exception SystemExit."""
00151     raise SystemExit(code)
00152 
00153 _varnum = 0
00154 class Variable:
00155     """Class to define value holders for e.g. buttons.
00156 
00157     Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
00158     that constrain the type of the value returned from get()."""
00159     _default = ""
00160     def __init__(self, master=None, value=None, name=None):
00161         """Construct a variable
00162 
00163         MASTER can be given as master widget.
00164         VALUE is an optional value (defaults to "")
00165         NAME is an optional Tcl name (defaults to PY_VARnum).
00166 
00167         If NAME matches an existing variable and VALUE is omitted
00168         then the existing value is retained.
00169         """
00170         global _varnum
00171         if not master:
00172             master = _default_root
00173         self._master = master
00174         self._tk = master.tk
00175         if name:
00176             self._name = name
00177         else:
00178             self._name = 'PY_VAR' + repr(_varnum)
00179             _varnum += 1
00180         if value is not None:
00181             self.set(value)
00182         elif not self._tk.call("info", "exists", self._name):
00183             self.set(self._default)
00184     def __del__(self):
00185         """Unset the variable in Tcl."""
00186         self._tk.globalunsetvar(self._name)
00187     def __str__(self):
00188         """Return the name of the variable in Tcl."""
00189         return self._name
00190     def set(self, value):
00191         """Set the variable to VALUE."""
00192         return self._tk.globalsetvar(self._name, value)
00193     def get(self):
00194         """Return value of variable."""
00195         return self._tk.globalgetvar(self._name)
00196     def trace_variable(self, mode, callback):
00197         """Define a trace callback for the variable.
00198 
00199         MODE is one of "r", "w", "u" for read, write, undefine.
00200         CALLBACK must be a function which is called when
00201         the variable is read, written or undefined.
00202 
00203         Return the name of the callback.
00204         """
00205         cbname = self._master._register(callback)
00206         self._tk.call("trace", "variable", self._name, mode, cbname)
00207         return cbname
00208     trace = trace_variable
00209     def trace_vdelete(self, mode, cbname):
00210         """Delete the trace callback for a variable.
00211 
00212         MODE is one of "r", "w", "u" for read, write, undefine.
00213         CBNAME is the name of the callback returned from trace_variable or trace.
00214         """
00215         self._tk.call("trace", "vdelete", self._name, mode, cbname)
00216         self._master.deletecommand(cbname)
00217     def trace_vinfo(self):
00218         """Return all trace callback information."""
00219         return [self._tk.split(x) for x in self._tk.splitlist(
00220             self._tk.call("trace", "vinfo", self._name))]
00221     def __eq__(self, other):
00222         """Comparison for equality (==).
00223 
00224         Note: if the Variable's master matters to behavior
00225         also compare self._master == other._master
00226         """
00227         return self.__class__.__name__ == other.__class__.__name__ \
00228             and self._name == other._name
00229 
00230 class StringVar(Variable):
00231     """Value holder for strings variables."""
00232     _default = ""
00233     def __init__(self, master=None, value=None, name=None):
00234         """Construct a string variable.
00235 
00236         MASTER can be given as master widget.
00237         VALUE is an optional value (defaults to "")
00238         NAME is an optional Tcl name (defaults to PY_VARnum).
00239 
00240         If NAME matches an existing variable and VALUE is omitted
00241         then the existing value is retained.
00242         """
00243         Variable.__init__(self, master, value, name)
00244 
00245     def get(self):
00246         """Return value of variable as string."""
00247         value = self._tk.globalgetvar(self._name)
00248         if isinstance(value, str):
00249             return value
00250         return str(value)
00251 
00252 class IntVar(Variable):
00253     """Value holder for integer variables."""
00254     _default = 0
00255     def __init__(self, master=None, value=None, name=None):
00256         """Construct an integer variable.
00257 
00258         MASTER can be given as master widget.
00259         VALUE is an optional value (defaults to 0)
00260         NAME is an optional Tcl name (defaults to PY_VARnum).
00261 
00262         If NAME matches an existing variable and VALUE is omitted
00263         then the existing value is retained.
00264         """
00265         Variable.__init__(self, master, value, name)
00266 
00267     def set(self, value):
00268         """Set the variable to value, converting booleans to integers."""
00269         if isinstance(value, bool):
00270             value = int(value)
00271         return Variable.set(self, value)
00272 
00273     def get(self):
00274         """Return the value of the variable as an integer."""
00275         return getint(self._tk.globalgetvar(self._name))
00276 
00277 class DoubleVar(Variable):
00278     """Value holder for float variables."""
00279     _default = 0.0
00280     def __init__(self, master=None, value=None, name=None):
00281         """Construct a float variable.
00282 
00283         MASTER can be given as master widget.
00284         VALUE is an optional value (defaults to 0.0)
00285         NAME is an optional Tcl name (defaults to PY_VARnum).
00286 
00287         If NAME matches an existing variable and VALUE is omitted
00288         then the existing value is retained.
00289         """
00290         Variable.__init__(self, master, value, name)
00291 
00292     def get(self):
00293         """Return the value of the variable as a float."""
00294         return getdouble(self._tk.globalgetvar(self._name))
00295 
00296 class BooleanVar(Variable):
00297     """Value holder for boolean variables."""
00298     _default = False
00299     def __init__(self, master=None, value=None, name=None):
00300         """Construct a boolean variable.
00301 
00302         MASTER can be given as master widget.
00303         VALUE is an optional value (defaults to False)
00304         NAME is an optional Tcl name (defaults to PY_VARnum).
00305 
00306         If NAME matches an existing variable and VALUE is omitted
00307         then the existing value is retained.
00308         """
00309         Variable.__init__(self, master, value, name)
00310 
00311     def get(self):
00312         """Return the value of the variable as a bool."""
00313         return self._tk.getboolean(self._tk.globalgetvar(self._name))
00314 
00315 def mainloop(n=0):
00316     """Run the main loop of Tcl."""
00317     _default_root.tk.mainloop(n)
00318 
00319 getint = int
00320 
00321 getdouble = float
00322 
00323 def getboolean(s):
00324     """Convert true and false to integer values 1 and 0."""
00325     return _default_root.tk.getboolean(s)
00326 
00327 # Methods defined on both toplevel and interior widgets
00328 class Misc:
00329     """Internal class.
00330 
00331     Base class which defines methods common for interior widgets."""
00332 
00333     # XXX font command?
00334     _tclCommands = None
00335     def destroy(self):
00336         """Internal function.
00337 
00338         Delete all Tcl commands created for
00339         this widget in the Tcl interpreter."""
00340         if self._tclCommands is not None:
00341             for name in self._tclCommands:
00342                 #print '- Tkinter: deleted command', name
00343                 self.tk.deletecommand(name)
00344             self._tclCommands = None
00345     def deletecommand(self, name):
00346         """Internal function.
00347 
00348         Delete the Tcl command provided in NAME."""
00349         #print '- Tkinter: deleted command', name
00350         self.tk.deletecommand(name)
00351         try:
00352             self._tclCommands.remove(name)
00353         except ValueError:
00354             pass
00355     def tk_strictMotif(self, boolean=None):
00356         """Set Tcl internal variable, whether the look and feel
00357         should adhere to Motif.
00358 
00359         A parameter of 1 means adhere to Motif (e.g. no color
00360         change if mouse passes over slider).
00361         Returns the set value."""
00362         return self.tk.getboolean(self.tk.call(
00363             'set', 'tk_strictMotif', boolean))
00364     def tk_bisque(self):
00365         """Change the color scheme to light brown as used in Tk 3.6 and before."""
00366         self.tk.call('tk_bisque')
00367     def tk_setPalette(self, *args, **kw):
00368         """Set a new color scheme for all widget elements.
00369 
00370         A single color as argument will cause that all colors of Tk
00371         widget elements are derived from this.
00372         Alternatively several keyword parameters and its associated
00373         colors can be given. The following keywords are valid:
00374         activeBackground, foreground, selectColor,
00375         activeForeground, highlightBackground, selectBackground,
00376         background, highlightColor, selectForeground,
00377         disabledForeground, insertBackground, troughColor."""
00378         self.tk.call(('tk_setPalette',)
00379               + _flatten(args) + _flatten(kw.items()))
00380     def tk_menuBar(self, *args):
00381         """Do not use. Needed in Tk 3.6 and earlier."""
00382         pass # obsolete since Tk 4.0
00383     def wait_variable(self, name='PY_VAR'):
00384         """Wait until the variable is modified.
00385 
00386         A parameter of type IntVar, StringVar, DoubleVar or
00387         BooleanVar must be given."""
00388         self.tk.call('tkwait', 'variable', name)
00389     waitvar = wait_variable # XXX b/w compat
00390     def wait_window(self, window=None):
00391         """Wait until a WIDGET is destroyed.
00392 
00393         If no parameter is given self is used."""
00394         if window is None:
00395             window = self
00396         self.tk.call('tkwait', 'window', window._w)
00397     def wait_visibility(self, window=None):
00398         """Wait until the visibility of a WIDGET changes
00399         (e.g. it appears).
00400 
00401         If no parameter is given self is used."""
00402         if window is None:
00403             window = self
00404         self.tk.call('tkwait', 'visibility', window._w)
00405     def setvar(self, name='PY_VAR', value='1'):
00406         """Set Tcl variable NAME to VALUE."""
00407         self.tk.setvar(name, value)
00408     def getvar(self, name='PY_VAR'):
00409         """Return value of Tcl variable NAME."""
00410         return self.tk.getvar(name)
00411     getint = int
00412     getdouble = float
00413     def getboolean(self, s):
00414         """Return a boolean value for Tcl boolean values true and false given as parameter."""
00415         return self.tk.getboolean(s)
00416     def focus_set(self):
00417         """Direct input focus to this widget.
00418 
00419         If the application currently does not have the focus
00420         this widget will get the focus if the application gets
00421         the focus through the window manager."""
00422         self.tk.call('focus', self._w)
00423     focus = focus_set # XXX b/w compat?
00424     def focus_force(self):
00425         """Direct input focus to this widget even if the
00426         application does not have the focus. Use with
00427         caution!"""
00428         self.tk.call('focus', '-force', self._w)
00429     def focus_get(self):
00430         """Return the widget which has currently the focus in the
00431         application.
00432 
00433         Use focus_displayof to allow working with several
00434         displays. Return None if application does not have
00435         the focus."""
00436         name = self.tk.call('focus')
00437         if name == 'none' or not name: return None
00438         return self._nametowidget(name)
00439     def focus_displayof(self):
00440         """Return the widget which has currently the focus on the
00441         display where this widget is located.
00442 
00443         Return None if the application does not have the focus."""
00444         name = self.tk.call('focus', '-displayof', self._w)
00445         if name == 'none' or not name: return None
00446         return self._nametowidget(name)
00447     def focus_lastfor(self):
00448         """Return the widget which would have the focus if top level
00449         for this widget gets the focus from the window manager."""
00450         name = self.tk.call('focus', '-lastfor', self._w)
00451         if name == 'none' or not name: return None
00452         return self._nametowidget(name)
00453     def tk_focusFollowsMouse(self):
00454         """The widget under mouse will get automatically focus. Can not
00455         be disabled easily."""
00456         self.tk.call('tk_focusFollowsMouse')
00457     def tk_focusNext(self):
00458         """Return the next widget in the focus order which follows
00459         widget which has currently the focus.
00460 
00461         The focus order first goes to the next child, then to
00462         the children of the child recursively and then to the
00463         next sibling which is higher in the stacking order.  A
00464         widget is omitted if it has the takefocus resource set
00465         to 0."""
00466         name = self.tk.call('tk_focusNext', self._w)
00467         if not name: return None
00468         return self._nametowidget(name)
00469     def tk_focusPrev(self):
00470         """Return previous widget in the focus order. See tk_focusNext for details."""
00471         name = self.tk.call('tk_focusPrev', self._w)
00472         if not name: return None
00473         return self._nametowidget(name)
00474     def after(self, ms, func=None, *args):
00475         """Call function once after given time.
00476 
00477         MS specifies the time in milliseconds. FUNC gives the
00478         function which shall be called. Additional parameters
00479         are given as parameters to the function call.  Return
00480         identifier to cancel scheduling with after_cancel."""
00481         if not func:
00482             # I'd rather use time.sleep(ms*0.001)
00483             self.tk.call('after', ms)
00484         else:
00485             def callit():
00486                 try:
00487                     func(*args)
00488                 finally:
00489                     try:
00490                         self.deletecommand(name)
00491                     except TclError:
00492                         pass
00493             name = self._register(callit)
00494             return self.tk.call('after', ms, name)
00495     def after_idle(self, func, *args):
00496         """Call FUNC once if the Tcl main loop has no event to
00497         process.
00498 
00499         Return an identifier to cancel the scheduling with
00500         after_cancel."""
00501         return self.after('idle', func, *args)
00502     def after_cancel(self, id):
00503         """Cancel scheduling of function identified with ID.
00504 
00505         Identifier returned by after or after_idle must be
00506         given as first parameter."""
00507         try:
00508             data = self.tk.call('after', 'info', id)
00509             # In Tk 8.3, splitlist returns: (script, type)
00510             # In Tk 8.4, splitlist may return (script, type) or (script,)
00511             script = self.tk.splitlist(data)[0]
00512             self.deletecommand(script)
00513         except TclError:
00514             pass
00515         self.tk.call('after', 'cancel', id)
00516     def bell(self, displayof=0):
00517         """Ring a display's bell."""
00518         self.tk.call(('bell',) + self._displayof(displayof))
00519 
00520     # Clipboard handling:
00521     def clipboard_get(self, **kw):
00522         """Retrieve data from the clipboard on window's display.
00523 
00524         The window keyword defaults to the root window of the Tkinter
00525         application.
00526 
00527         The type keyword specifies the form in which the data is
00528         to be returned and should be an atom name such as STRING
00529         or FILE_NAME.  Type defaults to STRING.
00530 
00531         This command is equivalent to:
00532 
00533         selection_get(CLIPBOARD)
00534         """
00535         return self.tk.call(('clipboard', 'get') + self._options(kw))
00536 
00537     def clipboard_clear(self, **kw):
00538         """Clear the data in the Tk clipboard.
00539 
00540         A widget specified for the optional displayof keyword
00541         argument specifies the target display."""
00542         if 'displayof' not in kw: kw['displayof'] = self._w
00543         self.tk.call(('clipboard', 'clear') + self._options(kw))
00544     def clipboard_append(self, string, **kw):
00545         """Append STRING to the Tk clipboard.
00546 
00547         A widget specified at the optional displayof keyword
00548         argument specifies the target display. The clipboard
00549         can be retrieved with selection_get."""
00550         if 'displayof' not in kw: kw['displayof'] = self._w
00551         self.tk.call(('clipboard', 'append') + self._options(kw)
00552               + ('--', string))
00553     # XXX grab current w/o window argument
00554     def grab_current(self):
00555         """Return widget which has currently the grab in this application
00556         or None."""
00557         name = self.tk.call('grab', 'current', self._w)
00558         if not name: return None
00559         return self._nametowidget(name)
00560     def grab_release(self):
00561         """Release grab for this widget if currently set."""
00562         self.tk.call('grab', 'release', self._w)
00563     def grab_set(self):
00564         """Set grab for this widget.
00565 
00566         A grab directs all events to this and descendant
00567         widgets in the application."""
00568         self.tk.call('grab', 'set', self._w)
00569     def grab_set_global(self):
00570         """Set global grab for this widget.
00571 
00572         A global grab directs all events to this and
00573         descendant widgets on the display. Use with caution -
00574         other applications do not get events anymore."""
00575         self.tk.call('grab', 'set', '-global', self._w)
00576     def grab_status(self):
00577         """Return None, "local" or "global" if this widget has
00578         no, a local or a global grab."""
00579         status = self.tk.call('grab', 'status', self._w)
00580         if status == 'none': status = None
00581         return status
00582     def option_add(self, pattern, value, priority = None):
00583         """Set a VALUE (second parameter) for an option
00584         PATTERN (first parameter).
00585 
00586         An optional third parameter gives the numeric priority
00587         (defaults to 80)."""
00588         self.tk.call('option', 'add', pattern, value, priority)
00589     def option_clear(self):
00590         """Clear the option database.
00591 
00592         It will be reloaded if option_add is called."""
00593         self.tk.call('option', 'clear')
00594     def option_get(self, name, className):
00595         """Return the value for an option NAME for this widget
00596         with CLASSNAME.
00597 
00598         Values with higher priority override lower values."""
00599         return self.tk.call('option', 'get', self._w, name, className)
00600     def option_readfile(self, fileName, priority = None):
00601         """Read file FILENAME into the option database.
00602 
00603         An optional second parameter gives the numeric
00604         priority."""
00605         self.tk.call('option', 'readfile', fileName, priority)
00606     def selection_clear(self, **kw):
00607         """Clear the current X selection."""
00608         if 'displayof' not in kw: kw['displayof'] = self._w
00609         self.tk.call(('selection', 'clear') + self._options(kw))
00610     def selection_get(self, **kw):
00611         """Return the contents of the current X selection.
00612 
00613         A keyword parameter selection specifies the name of
00614         the selection and defaults to PRIMARY.  A keyword
00615         parameter displayof specifies a widget on the display
00616         to use."""
00617         if 'displayof' not in kw: kw['displayof'] = self._w
00618         return self.tk.call(('selection', 'get') + self._options(kw))
00619     def selection_handle(self, command, **kw):
00620         """Specify a function COMMAND to call if the X
00621         selection owned by this widget is queried by another
00622         application.
00623 
00624         This function must return the contents of the
00625         selection. The function will be called with the
00626         arguments OFFSET and LENGTH which allows the chunking
00627         of very long selections. The following keyword
00628         parameters can be provided:
00629         selection - name of the selection (default PRIMARY),
00630         type - type of the selection (e.g. STRING, FILE_NAME)."""
00631         name = self._register(command)
00632         self.tk.call(('selection', 'handle') + self._options(kw)
00633               + (self._w, name))
00634     def selection_own(self, **kw):
00635         """Become owner of X selection.
00636 
00637         A keyword parameter selection specifies the name of
00638         the selection (default PRIMARY)."""
00639         self.tk.call(('selection', 'own') +
00640                  self._options(kw) + (self._w,))
00641     def selection_own_get(self, **kw):
00642         """Return owner of X selection.
00643 
00644         The following keyword parameter can
00645         be provided:
00646         selection - name of the selection (default PRIMARY),
00647         type - type of the selection (e.g. STRING, FILE_NAME)."""
00648         if 'displayof' not in kw: kw['displayof'] = self._w
00649         name = self.tk.call(('selection', 'own') + self._options(kw))
00650         if not name: return None
00651         return self._nametowidget(name)
00652     def send(self, interp, cmd, *args):
00653         """Send Tcl command CMD to different interpreter INTERP to be executed."""
00654         return self.tk.call(('send', interp, cmd) + args)
00655     def lower(self, belowThis=None):
00656         """Lower this widget in the stacking order."""
00657         self.tk.call('lower', self._w, belowThis)
00658     def tkraise(self, aboveThis=None):
00659         """Raise this widget in the stacking order."""
00660         self.tk.call('raise', self._w, aboveThis)
00661     lift = tkraise
00662     def colormodel(self, value=None):
00663         """Useless. Not implemented in Tk."""
00664         return self.tk.call('tk', 'colormodel', self._w, value)
00665     def winfo_atom(self, name, displayof=0):
00666         """Return integer which represents atom NAME."""
00667         args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
00668         return getint(self.tk.call(args))
00669     def winfo_atomname(self, id, displayof=0):
00670         """Return name of atom with identifier ID."""
00671         args = ('winfo', 'atomname') \
00672                + self._displayof(displayof) + (id,)
00673         return self.tk.call(args)
00674     def winfo_cells(self):
00675         """Return number of cells in the colormap for this widget."""
00676         return getint(
00677             self.tk.call('winfo', 'cells', self._w))
00678     def winfo_children(self):
00679         """Return a list of all widgets which are children of this widget."""
00680         result = []
00681         for child in self.tk.splitlist(
00682             self.tk.call('winfo', 'children', self._w)):
00683             try:
00684                 # Tcl sometimes returns extra windows, e.g. for
00685                 # menus; those need to be skipped
00686                 result.append(self._nametowidget(child))
00687             except KeyError:
00688                 pass
00689         return result
00690 
00691     def winfo_class(self):
00692         """Return window class name of this widget."""
00693         return self.tk.call('winfo', 'class', self._w)
00694     def winfo_colormapfull(self):
00695         """Return true if at the last color request the colormap was full."""
00696         return self.tk.getboolean(
00697             self.tk.call('winfo', 'colormapfull', self._w))
00698     def winfo_containing(self, rootX, rootY, displayof=0):
00699         """Return the widget which is at the root coordinates ROOTX, ROOTY."""
00700         args = ('winfo', 'containing') \
00701                + self._displayof(displayof) + (rootX, rootY)
00702         name = self.tk.call(args)
00703         if not name: return None
00704         return self._nametowidget(name)
00705     def winfo_depth(self):
00706         """Return the number of bits per pixel."""
00707         return getint(self.tk.call('winfo', 'depth', self._w))
00708     def winfo_exists(self):
00709         """Return true if this widget exists."""
00710         return getint(
00711             self.tk.call('winfo', 'exists', self._w))
00712     def winfo_fpixels(self, number):
00713         """Return the number of pixels for the given distance NUMBER
00714         (e.g. "3c") as float."""
00715         return getdouble(self.tk.call(
00716             'winfo', 'fpixels', self._w, number))
00717     def winfo_geometry(self):
00718         """Return geometry string for this widget in the form "widthxheight+X+Y"."""
00719         return self.tk.call('winfo', 'geometry', self._w)
00720     def winfo_height(self):
00721         """Return height of this widget."""
00722         return getint(
00723             self.tk.call('winfo', 'height', self._w))
00724     def winfo_id(self):
00725         """Return identifier ID for this widget."""
00726         return self.tk.getint(
00727             self.tk.call('winfo', 'id', self._w))
00728     def winfo_interps(self, displayof=0):
00729         """Return the name of all Tcl interpreters for this display."""
00730         args = ('winfo', 'interps') + self._displayof(displayof)
00731         return self.tk.splitlist(self.tk.call(args))
00732     def winfo_ismapped(self):
00733         """Return true if this widget is mapped."""
00734         return getint(
00735             self.tk.call('winfo', 'ismapped', self._w))
00736     def winfo_manager(self):
00737         """Return the window mananger name for this widget."""
00738         return self.tk.call('winfo', 'manager', self._w)
00739     def winfo_name(self):
00740         """Return the name of this widget."""
00741         return self.tk.call('winfo', 'name', self._w)
00742     def winfo_parent(self):
00743         """Return the name of the parent of this widget."""
00744         return self.tk.call('winfo', 'parent', self._w)
00745     def winfo_pathname(self, id, displayof=0):
00746         """Return the pathname of the widget given by ID."""
00747         args = ('winfo', 'pathname') \
00748                + self._displayof(displayof) + (id,)
00749         return self.tk.call(args)
00750     def winfo_pixels(self, number):
00751         """Rounded integer value of winfo_fpixels."""
00752         return getint(
00753             self.tk.call('winfo', 'pixels', self._w, number))
00754     def winfo_pointerx(self):
00755         """Return the x coordinate of the pointer on the root window."""
00756         return getint(
00757             self.tk.call('winfo', 'pointerx', self._w))
00758     def winfo_pointerxy(self):
00759         """Return a tuple of x and y coordinates of the pointer on the root window."""
00760         return self._getints(
00761             self.tk.call('winfo', 'pointerxy', self._w))
00762     def winfo_pointery(self):
00763         """Return the y coordinate of the pointer on the root window."""
00764         return getint(
00765             self.tk.call('winfo', 'pointery', self._w))
00766     def winfo_reqheight(self):
00767         """Return requested height of this widget."""
00768         return getint(
00769             self.tk.call('winfo', 'reqheight', self._w))
00770     def winfo_reqwidth(self):
00771         """Return requested width of this widget."""
00772         return getint(
00773             self.tk.call('winfo', 'reqwidth', self._w))
00774     def winfo_rgb(self, color):
00775         """Return tuple of decimal values for red, green, blue for
00776         COLOR in this widget."""
00777         return self._getints(
00778             self.tk.call('winfo', 'rgb', self._w, color))
00779     def winfo_rootx(self):
00780         """Return x coordinate of upper left corner of this widget on the
00781         root window."""
00782         return getint(
00783             self.tk.call('winfo', 'rootx', self._w))
00784     def winfo_rooty(self):
00785         """Return y coordinate of upper left corner of this widget on the
00786         root window."""
00787         return getint(
00788             self.tk.call('winfo', 'rooty', self._w))
00789     def winfo_screen(self):
00790         """Return the screen name of this widget."""
00791         return self.tk.call('winfo', 'screen', self._w)
00792     def winfo_screencells(self):
00793         """Return the number of the cells in the colormap of the screen
00794         of this widget."""
00795         return getint(
00796             self.tk.call('winfo', 'screencells', self._w))
00797     def winfo_screendepth(self):
00798         """Return the number of bits per pixel of the root window of the
00799         screen of this widget."""
00800         return getint(
00801             self.tk.call('winfo', 'screendepth', self._w))
00802     def winfo_screenheight(self):
00803         """Return the number of pixels of the height of the screen of this widget
00804         in pixel."""
00805         return getint(
00806             self.tk.call('winfo', 'screenheight', self._w))
00807     def winfo_screenmmheight(self):
00808         """Return the number of pixels of the height of the screen of
00809         this widget in mm."""
00810         return getint(
00811             self.tk.call('winfo', 'screenmmheight', self._w))
00812     def winfo_screenmmwidth(self):
00813         """Return the number of pixels of the width of the screen of
00814         this widget in mm."""
00815         return getint(
00816             self.tk.call('winfo', 'screenmmwidth', self._w))
00817     def winfo_screenvisual(self):
00818         """Return one of the strings directcolor, grayscale, pseudocolor,
00819         staticcolor, staticgray, or truecolor for the default
00820         colormodel of this screen."""
00821         return self.tk.call('winfo', 'screenvisual', self._w)
00822     def winfo_screenwidth(self):
00823         """Return the number of pixels of the width of the screen of
00824         this widget in pixel."""
00825         return getint(
00826             self.tk.call('winfo', 'screenwidth', self._w))
00827     def winfo_server(self):
00828         """Return information of the X-Server of the screen of this widget in
00829         the form "XmajorRminor vendor vendorVersion"."""
00830         return self.tk.call('winfo', 'server', self._w)
00831     def winfo_toplevel(self):
00832         """Return the toplevel widget of this widget."""
00833         return self._nametowidget(self.tk.call(
00834             'winfo', 'toplevel', self._w))
00835     def winfo_viewable(self):
00836         """Return true if the widget and all its higher ancestors are mapped."""
00837         return getint(
00838             self.tk.call('winfo', 'viewable', self._w))
00839     def winfo_visual(self):
00840         """Return one of the strings directcolor, grayscale, pseudocolor,
00841         staticcolor, staticgray, or truecolor for the
00842         colormodel of this widget."""
00843         return self.tk.call('winfo', 'visual', self._w)
00844     def winfo_visualid(self):
00845         """Return the X identifier for the visual for this widget."""
00846         return self.tk.call('winfo', 'visualid', self._w)
00847     def winfo_visualsavailable(self, includeids=0):
00848         """Return a list of all visuals available for the screen
00849         of this widget.
00850 
00851         Each item in the list consists of a visual name (see winfo_visual), a
00852         depth and if INCLUDEIDS=1 is given also the X identifier."""
00853         data = self.tk.split(
00854             self.tk.call('winfo', 'visualsavailable', self._w,
00855                      includeids and 'includeids' or None))
00856         if isinstance(data, str):
00857             data = [self.tk.split(data)]
00858         return [self.__winfo_parseitem(x) for x in  data]
00859     def __winfo_parseitem(self, t):
00860         """Internal function."""
00861         return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
00862     def __winfo_getint(self, x):
00863         """Internal function."""
00864         return int(x, 0)
00865     def winfo_vrootheight(self):
00866         """Return the height of the virtual root window associated with this
00867         widget in pixels. If there is no virtual root window return the
00868         height of the screen."""
00869         return getint(
00870             self.tk.call('winfo', 'vrootheight', self._w))
00871     def winfo_vrootwidth(self):
00872         """Return the width of the virtual root window associated with this
00873         widget in pixel. If there is no virtual root window return the
00874         width of the screen."""
00875         return getint(
00876             self.tk.call('winfo', 'vrootwidth', self._w))
00877     def winfo_vrootx(self):
00878         """Return the x offset of the virtual root relative to the root
00879         window of the screen of this widget."""
00880         return getint(
00881             self.tk.call('winfo', 'vrootx', self._w))
00882     def winfo_vrooty(self):
00883         """Return the y offset of the virtual root relative to the root
00884         window of the screen of this widget."""
00885         return getint(
00886             self.tk.call('winfo', 'vrooty', self._w))
00887     def winfo_width(self):
00888         """Return the width of this widget."""
00889         return getint(
00890             self.tk.call('winfo', 'width', self._w))
00891     def winfo_x(self):
00892         """Return the x coordinate of the upper left corner of this widget
00893         in the parent."""
00894         return getint(
00895             self.tk.call('winfo', 'x', self._w))
00896     def winfo_y(self):
00897         """Return the y coordinate of the upper left corner of this widget
00898         in the parent."""
00899         return getint(
00900             self.tk.call('winfo', 'y', self._w))
00901     def update(self):
00902         """Enter event loop until all pending events have been processed by Tcl."""
00903         self.tk.call('update')
00904     def update_idletasks(self):
00905         """Enter event loop until all idle callbacks have been called. This
00906         will update the display of windows but not process events caused by
00907         the user."""
00908         self.tk.call('update', 'idletasks')
00909     def bindtags(self, tagList=None):
00910         """Set or get the list of bindtags for this widget.
00911 
00912         With no argument return the list of all bindtags associated with
00913         this widget. With a list of strings as argument the bindtags are
00914         set to this list. The bindtags determine in which order events are
00915         processed (see bind)."""
00916         if tagList is None:
00917             return self.tk.splitlist(
00918                 self.tk.call('bindtags', self._w))
00919         else:
00920             self.tk.call('bindtags', self._w, tagList)
00921     def _bind(self, what, sequence, func, add, needcleanup=1):
00922         """Internal function."""
00923         if isinstance(func, str):
00924             self.tk.call(what + (sequence, func))
00925         elif func:
00926             funcid = self._register(func, self._substitute,
00927                         needcleanup)
00928             cmd = ('%sif {"[%s %s]" == "break"} break\n'
00929                    %
00930                    (add and '+' or '',
00931                 funcid, self._subst_format_str))
00932             self.tk.call(what + (sequence, cmd))
00933             return funcid
00934         elif sequence:
00935             return self.tk.call(what + (sequence,))
00936         else:
00937             return self.tk.splitlist(self.tk.call(what))
00938     def bind(self, sequence=None, func=None, add=None):
00939         """Bind to this widget at event SEQUENCE a call to function FUNC.
00940 
00941         SEQUENCE is a string of concatenated event
00942         patterns. An event pattern is of the form
00943         <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
00944         of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
00945         Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
00946         B3, Alt, Button4, B4, Double, Button5, B5 Triple,
00947         Mod1, M1. TYPE is one of Activate, Enter, Map,
00948         ButtonPress, Button, Expose, Motion, ButtonRelease
00949         FocusIn, MouseWheel, Circulate, FocusOut, Property,
00950         Colormap, Gravity Reparent, Configure, KeyPress, Key,
00951         Unmap, Deactivate, KeyRelease Visibility, Destroy,
00952         Leave and DETAIL is the button number for ButtonPress,
00953         ButtonRelease and DETAIL is the Keysym for KeyPress and
00954         KeyRelease. Examples are
00955         <Control-Button-1> for pressing Control and mouse button 1 or
00956         <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
00957         An event pattern can also be a virtual event of the form
00958         <<AString>> where AString can be arbitrary. This
00959         event can be generated by event_generate.
00960         If events are concatenated they must appear shortly
00961         after each other.
00962 
00963         FUNC will be called if the event sequence occurs with an
00964         instance of Event as argument. If the return value of FUNC is
00965         "break" no further bound function is invoked.
00966 
00967         An additional boolean parameter ADD specifies whether FUNC will
00968         be called additionally to the other bound function or whether
00969         it will replace the previous function.
00970 
00971         Bind will return an identifier to allow deletion of the bound function with
00972         unbind without memory leak.
00973 
00974         If FUNC or SEQUENCE is omitted the bound function or list
00975         of bound events are returned."""
00976 
00977         return self._bind(('bind', self._w), sequence, func, add)
00978     def unbind(self, sequence, funcid=None):
00979         """Unbind for this widget for event SEQUENCE  the
00980         function identified with FUNCID."""
00981         self.tk.call('bind', self._w, sequence, '')
00982         if funcid:
00983             self.deletecommand(funcid)
00984     def bind_all(self, sequence=None, func=None, add=None):
00985         """Bind to all widgets at an event SEQUENCE a call to function FUNC.
00986         An additional boolean parameter ADD specifies whether FUNC will
00987         be called additionally to the other bound function or whether
00988         it will replace the previous function. See bind for the return value."""
00989         return self._bind(('bind', 'all'), sequence, func, add, 0)
00990     def unbind_all(self, sequence):
00991         """Unbind for all widgets for event SEQUENCE all functions."""
00992         self.tk.call('bind', 'all' , sequence, '')
00993     def bind_class(self, className, sequence=None, func=None, add=None):
00994 
00995         """Bind to widgets with bindtag CLASSNAME at event
00996         SEQUENCE a call of function FUNC. An additional
00997         boolean parameter ADD specifies whether FUNC will be
00998         called additionally to the other bound function or
00999         whether it will replace the previous function. See bind for
01000         the return value."""
01001 
01002         return self._bind(('bind', className), sequence, func, add, 0)
01003     def unbind_class(self, className, sequence):
01004         """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
01005         all functions."""
01006         self.tk.call('bind', className , sequence, '')
01007     def mainloop(self, n=0):
01008         """Call the mainloop of Tk."""
01009         self.tk.mainloop(n)
01010     def quit(self):
01011         """Quit the Tcl interpreter. All widgets will be destroyed."""
01012         self.tk.quit()
01013     def _getints(self, string):
01014         """Internal function."""
01015         if string:
01016             return tuple(map(getint, self.tk.splitlist(string)))
01017     def _getdoubles(self, string):
01018         """Internal function."""
01019         if string:
01020             return tuple(map(getdouble, self.tk.splitlist(string)))
01021     def _getboolean(self, string):
01022         """Internal function."""
01023         if string:
01024             return self.tk.getboolean(string)
01025     def _displayof(self, displayof):
01026         """Internal function."""
01027         if displayof:
01028             return ('-displayof', displayof)
01029         if displayof is None:
01030             return ('-displayof', self._w)
01031         return ()
01032     def _options(self, cnf, kw = None):
01033         """Internal function."""
01034         if kw:
01035             cnf = _cnfmerge((cnf, kw))
01036         else:
01037             cnf = _cnfmerge(cnf)
01038         res = ()
01039         for k, v in cnf.items():
01040             if v is not None:
01041                 if k[-1] == '_': k = k[:-1]
01042                 if hasattr(v, '__call__'):
01043                     v = self._register(v)
01044                 elif isinstance(v, (tuple, list)):
01045                     nv = []
01046                     for item in v:
01047                         if isinstance(item, int):
01048                             nv.append(str(item))
01049                         elif isinstance(item, str):
01050                             nv.append(('{%s}' if ' ' in item else '%s') % item)
01051                         else:
01052                             break
01053                     else:
01054                         v = ' '.join(nv)
01055                 res = res + ('-'+k, v)
01056         return res
01057     def nametowidget(self, name):
01058         """Return the Tkinter instance of a widget identified by
01059         its Tcl name NAME."""
01060         name = str(name).split('.')
01061         w = self
01062 
01063         if not name[0]:
01064             w = w._root()
01065             name = name[1:]
01066 
01067         for n in name:
01068             if not n:
01069                 break
01070             w = w.children[n]
01071 
01072         return w
01073     _nametowidget = nametowidget
01074     def _register(self, func, subst=None, needcleanup=1):
01075         """Return a newly created Tcl function. If this
01076         function is called, the Python function FUNC will
01077         be executed. An optional function SUBST can
01078         be given which will be executed before FUNC."""
01079         f = CallWrapper(func, subst, self).__call__
01080         name = repr(id(f))
01081         try:
01082             func = func.__func__
01083         except AttributeError:
01084             pass
01085         try:
01086             name = name + func.__name__
01087         except AttributeError:
01088             pass
01089         self.tk.createcommand(name, f)
01090         if needcleanup:
01091             if self._tclCommands is None:
01092                 self._tclCommands = []
01093             self._tclCommands.append(name)
01094         return name
01095     register = _register
01096     def _root(self):
01097         """Internal function."""
01098         w = self
01099         while w.master: w = w.master
01100         return w
01101     _subst_format = ('%#', '%b', '%f', '%h', '%k',
01102              '%s', '%t', '%w', '%x', '%y',
01103              '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
01104     _subst_format_str = " ".join(_subst_format)
01105     def _substitute(self, *args):
01106         """Internal function."""
01107         if len(args) != len(self._subst_format): return args
01108         getboolean = self.tk.getboolean
01109 
01110         getint = int
01111         def getint_event(s):
01112             """Tk changed behavior in 8.4.2, returning "??" rather more often."""
01113             try:
01114                 return int(s)
01115             except ValueError:
01116                 return s
01117 
01118         nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
01119         # Missing: (a, c, d, m, o, v, B, R)
01120         e = Event()
01121         # serial field: valid vor all events
01122         # number of button: ButtonPress and ButtonRelease events only
01123         # height field: Configure, ConfigureRequest, Create,
01124         # ResizeRequest, and Expose events only
01125         # keycode field: KeyPress and KeyRelease events only
01126         # time field: "valid for events that contain a time field"
01127         # width field: Configure, ConfigureRequest, Create, ResizeRequest,
01128         # and Expose events only
01129         # x field: "valid for events that contain a x field"
01130         # y field: "valid for events that contain a y field"
01131         # keysym as decimal: KeyPress and KeyRelease events only
01132         # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
01133         # KeyRelease,and Motion events
01134         e.serial = getint(nsign)
01135         e.num = getint_event(b)
01136         try: e.focus = getboolean(f)
01137         except TclError: pass
01138         e.height = getint_event(h)
01139         e.keycode = getint_event(k)
01140         e.state = getint_event(s)
01141         e.time = getint_event(t)
01142         e.width = getint_event(w)
01143         e.x = getint_event(x)
01144         e.y = getint_event(y)
01145         e.char = A
01146         try: e.send_event = getboolean(E)
01147         except TclError: pass
01148         e.keysym = K
01149         e.keysym_num = getint_event(N)
01150         e.type = T
01151         try:
01152             e.widget = self._nametowidget(W)
01153         except KeyError:
01154             e.widget = W
01155         e.x_root = getint_event(X)
01156         e.y_root = getint_event(Y)
01157         try:
01158             e.delta = getint(D)
01159         except ValueError:
01160             e.delta = 0
01161         return (e,)
01162     def _report_exception(self):
01163         """Internal function."""
01164         import sys
01165         exc, val, tb = sys.exc_info()
01166         root = self._root()
01167         root.report_callback_exception(exc, val, tb)
01168     def _configure(self, cmd, cnf, kw):
01169         """Internal function."""
01170         if kw:
01171             cnf = _cnfmerge((cnf, kw))
01172         elif cnf:
01173             cnf = _cnfmerge(cnf)
01174         if cnf is None:
01175             cnf = {}
01176             for x in self.tk.split(
01177                     self.tk.call(_flatten((self._w, cmd)))):
01178                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
01179             return cnf
01180         if isinstance(cnf, str):
01181             x = self.tk.split(
01182                     self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
01183             return (x[0][1:],) + x[1:]
01184         self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
01185     # These used to be defined in Widget:
01186     def configure(self, cnf=None, **kw):
01187         """Configure resources of a widget.
01188 
01189         The values for resources are specified as keyword
01190         arguments. To get an overview about
01191         the allowed keyword arguments call the method keys.
01192         """
01193         return self._configure('configure', cnf, kw)
01194     config = configure
01195     def cget(self, key):
01196         """Return the resource value for a KEY given as string."""
01197         return self.tk.call(self._w, 'cget', '-' + key)
01198     __getitem__ = cget
01199     def __setitem__(self, key, value):
01200         self.configure({key: value})
01201     def keys(self):
01202         """Return a list of all resource names of this widget."""
01203         return [x[0][1:] for x in
01204                 self.tk.split(self.tk.call(self._w, 'configure'))]
01205     def __str__(self):
01206         """Return the window path name of this widget."""
01207         return self._w
01208     # Pack methods that apply to the master
01209     _noarg_ = ['_noarg_']
01210     def pack_propagate(self, flag=_noarg_):
01211         """Set or get the status for propagation of geometry information.
01212 
01213         A boolean argument specifies whether the geometry information
01214         of the slaves will determine the size of this widget. If no argument
01215         is given the current setting will be returned.
01216         """
01217         if flag is Misc._noarg_:
01218             return self._getboolean(self.tk.call(
01219                 'pack', 'propagate', self._w))
01220         else:
01221             self.tk.call('pack', 'propagate', self._w, flag)
01222     propagate = pack_propagate
01223     def pack_slaves(self):
01224         """Return a list of all slaves of this widget
01225         in its packing order."""
01226         return [self._nametowidget(x) for x in
01227                 self.tk.splitlist(
01228                    self.tk.call('pack', 'slaves', self._w))]
01229     slaves = pack_slaves
01230     # Place method that applies to the master
01231     def place_slaves(self):
01232         """Return a list of all slaves of this widget
01233         in its packing order."""
01234         return [self._nametowidget(x) for x in
01235                 self.tk.splitlist(
01236                    self.tk.call(
01237                        'place', 'slaves', self._w))]
01238     # Grid methods that apply to the master
01239     def grid_bbox(self, column=None, row=None, col2=None, row2=None):
01240         """Return a tuple of integer coordinates for the bounding
01241         box of this widget controlled by the geometry manager grid.
01242 
01243         If COLUMN, ROW is given the bounding box applies from
01244         the cell with row and column 0 to the specified
01245         cell. If COL2 and ROW2 are given the bounding box
01246         starts at that cell.
01247 
01248         The returned integers specify the offset of the upper left
01249         corner in the master widget and the width and height.
01250         """
01251         args = ('grid', 'bbox', self._w)
01252         if column is not None and row is not None:
01253             args = args + (column, row)
01254         if col2 is not None and row2 is not None:
01255             args = args + (col2, row2)
01256         return self._getints(self.tk.call(*args)) or None
01257 
01258     bbox = grid_bbox
01259     def _grid_configure(self, command, index, cnf, kw):
01260         """Internal function."""
01261         if isinstance(cnf, str) and not kw:
01262             if cnf[-1:] == '_':
01263                 cnf = cnf[:-1]
01264             if cnf[:1] != '-':
01265                 cnf = '-'+cnf
01266             options = (cnf,)
01267         else:
01268             options = self._options(cnf, kw)
01269         if not options:
01270             res = self.tk.call('grid',
01271                        command, self._w, index)
01272             words = self.tk.splitlist(res)
01273             dict = {}
01274             for i in range(0, len(words), 2):
01275                 key = words[i][1:]
01276                 value = words[i+1]
01277                 if not value:
01278                     value = None
01279                 elif '.' in value:
01280                     value = getdouble(value)
01281                 else:
01282                     value = getint(value)
01283                 dict[key] = value
01284             return dict
01285         res = self.tk.call(
01286                   ('grid', command, self._w, index)
01287                   + options)
01288         if len(options) == 1:
01289             if not res: return None
01290             # In Tk 7.5, -width can be a float
01291             if '.' in res: return getdouble(res)
01292             return getint(res)
01293     def grid_columnconfigure(self, index, cnf={}, **kw):
01294         """Configure column INDEX of a grid.
01295 
01296         Valid resources are minsize (minimum size of the column),
01297         weight (how much does additional space propagate to this column)
01298         and pad (how much space to let additionally)."""
01299         return self._grid_configure('columnconfigure', index, cnf, kw)
01300     columnconfigure = grid_columnconfigure
01301     def grid_location(self, x, y):
01302         """Return a tuple of column and row which identify the cell
01303         at which the pixel at position X and Y inside the master
01304         widget is located."""
01305         return self._getints(
01306             self.tk.call(
01307                 'grid', 'location', self._w, x, y)) or None
01308     def grid_propagate(self, flag=_noarg_):
01309         """Set or get the status for propagation of geometry information.
01310 
01311         A boolean argument specifies whether the geometry information
01312         of the slaves will determine the size of this widget. If no argument
01313         is given, the current setting will be returned.
01314         """
01315         if flag is Misc._noarg_:
01316             return self._getboolean(self.tk.call(
01317                 'grid', 'propagate', self._w))
01318         else:
01319             self.tk.call('grid', 'propagate', self._w, flag)
01320     def grid_rowconfigure(self, index, cnf={}, **kw):
01321         """Configure row INDEX of a grid.
01322 
01323         Valid resources are minsize (minimum size of the row),
01324         weight (how much does additional space propagate to this row)
01325         and pad (how much space to let additionally)."""
01326         return self._grid_configure('rowconfigure', index, cnf, kw)
01327     rowconfigure = grid_rowconfigure
01328     def grid_size(self):
01329         """Return a tuple of the number of column and rows in the grid."""
01330         return self._getints(
01331             self.tk.call('grid', 'size', self._w)) or None
01332     size = grid_size
01333     def grid_slaves(self, row=None, column=None):
01334         """Return a list of all slaves of this widget
01335         in its packing order."""
01336         args = ()
01337         if row is not None:
01338             args = args + ('-row', row)
01339         if column is not None:
01340             args = args + ('-column', column)
01341         return [self._nametowidget(x) for x in
01342                 self.tk.splitlist(self.tk.call(
01343                    ('grid', 'slaves', self._w) + args))]
01344 
01345     # Support for the "event" command, new in Tk 4.2.
01346     # By Case Roole.
01347 
01348     def event_add(self, virtual, *sequences):
01349         """Bind a virtual event VIRTUAL (of the form <<Name>>)
01350         to an event SEQUENCE such that the virtual event is triggered
01351         whenever SEQUENCE occurs."""
01352         args = ('event', 'add', virtual) + sequences
01353         self.tk.call(args)
01354 
01355     def event_delete(self, virtual, *sequences):
01356         """Unbind a virtual event VIRTUAL from SEQUENCE."""
01357         args = ('event', 'delete', virtual) + sequences
01358         self.tk.call(args)
01359 
01360     def event_generate(self, sequence, **kw):
01361         """Generate an event SEQUENCE. Additional
01362         keyword arguments specify parameter of the event
01363         (e.g. x, y, rootx, rooty)."""
01364         args = ('event', 'generate', self._w, sequence)
01365         for k, v in kw.items():
01366             args = args + ('-%s' % k, str(v))
01367         self.tk.call(args)
01368 
01369     def event_info(self, virtual=None):
01370         """Return a list of all virtual events or the information
01371         about the SEQUENCE bound to the virtual event VIRTUAL."""
01372         return self.tk.splitlist(
01373             self.tk.call('event', 'info', virtual))
01374 
01375     # Image related commands
01376 
01377     def image_names(self):
01378         """Return a list of all existing image names."""
01379         return self.tk.call('image', 'names')
01380 
01381     def image_types(self):
01382         """Return a list of all available image types (e.g. phote bitmap)."""
01383         return self.tk.call('image', 'types')
01384 
01385 
01386 class CallWrapper:
01387     """Internal class. Stores function to call when some user
01388     defined Tcl function is called e.g. after an event occurred."""
01389     def __init__(self, func, subst, widget):
01390         """Store FUNC, SUBST and WIDGET as members."""
01391         self.func = func
01392         self.subst = subst
01393         self.widget = widget
01394     def __call__(self, *args):
01395         """Apply first function SUBST to arguments, than FUNC."""
01396         try:
01397             if self.subst:
01398                 args = self.subst(*args)
01399             return self.func(*args)
01400         except SystemExit as msg:
01401             raise SystemExit(msg)
01402         except:
01403             self.widget._report_exception()
01404 
01405 
01406 class XView:
01407     """Mix-in class for querying and changing the horizontal position
01408     of a widget's window."""
01409 
01410     def xview(self, *args):
01411         """Query and change the horizontal position of the view."""
01412         res = self.tk.call(self._w, 'xview', *args)
01413         if not args:
01414             return self._getdoubles(res)
01415 
01416     def xview_moveto(self, fraction):
01417         """Adjusts the view in the window so that FRACTION of the
01418         total width of the canvas is off-screen to the left."""
01419         self.tk.call(self._w, 'xview', 'moveto', fraction)
01420 
01421     def xview_scroll(self, number, what):
01422         """Shift the x-view according to NUMBER which is measured in "units"
01423         or "pages" (WHAT)."""
01424         self.tk.call(self._w, 'xview', 'scroll', number, what)
01425 
01426 
01427 class YView:
01428     """Mix-in class for querying and changing the vertical position
01429     of a widget's window."""
01430 
01431     def yview(self, *args):
01432         """Query and change the vertical position of the view."""
01433         res = self.tk.call(self._w, 'yview', *args)
01434         if not args:
01435             return self._getdoubles(res)
01436 
01437     def yview_moveto(self, fraction):
01438         """Adjusts the view in the window so that FRACTION of the
01439         total height of the canvas is off-screen to the top."""
01440         self.tk.call(self._w, 'yview', 'moveto', fraction)
01441 
01442     def yview_scroll(self, number, what):
01443         """Shift the y-view according to NUMBER which is measured in
01444         "units" or "pages" (WHAT)."""
01445         self.tk.call(self._w, 'yview', 'scroll', number, what)
01446 
01447 
01448 class Wm:
01449     """Provides functions for the communication with the window manager."""
01450 
01451     def wm_aspect(self,
01452               minNumer=None, minDenom=None,
01453               maxNumer=None, maxDenom=None):
01454         """Instruct the window manager to set the aspect ratio (width/height)
01455         of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
01456         of the actual values if no argument is given."""
01457         return self._getints(
01458             self.tk.call('wm', 'aspect', self._w,
01459                      minNumer, minDenom,
01460                      maxNumer, maxDenom))
01461     aspect = wm_aspect
01462 
01463     def wm_attributes(self, *args):
01464         """This subcommand returns or sets platform specific attributes
01465 
01466         The first form returns a list of the platform specific flags and
01467         their values. The second form returns the value for the specific
01468         option. The third form sets one or more of the values. The values
01469         are as follows:
01470 
01471         On Windows, -disabled gets or sets whether the window is in a
01472         disabled state. -toolwindow gets or sets the style of the window
01473         to toolwindow (as defined in the MSDN). -topmost gets or sets
01474         whether this is a topmost window (displays above all other
01475         windows).
01476 
01477         On Macintosh, XXXXX
01478 
01479         On Unix, there are currently no special attribute values.
01480         """
01481         args = ('wm', 'attributes', self._w) + args
01482         return self.tk.call(args)
01483     attributes=wm_attributes
01484 
01485     def wm_client(self, name=None):
01486         """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
01487         current value."""
01488         return self.tk.call('wm', 'client', self._w, name)
01489     client = wm_client
01490     def wm_colormapwindows(self, *wlist):
01491         """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
01492         of this widget. This list contains windows whose colormaps differ from their
01493         parents. Return current list of widgets if WLIST is empty."""
01494         if len(wlist) > 1:
01495             wlist = (wlist,) # Tk needs a list of windows here
01496         args = ('wm', 'colormapwindows', self._w) + wlist
01497         return [self._nametowidget(x) for x in  self.tk.call(args)]
01498     colormapwindows = wm_colormapwindows
01499     def wm_command(self, value=None):
01500         """Store VALUE in WM_COMMAND property. It is the command
01501         which shall be used to invoke the application. Return current
01502         command if VALUE is None."""
01503         return self.tk.call('wm', 'command', self._w, value)
01504     command = wm_command
01505     def wm_deiconify(self):
01506         """Deiconify this widget. If it was never mapped it will not be mapped.
01507         On Windows it will raise this widget and give it the focus."""
01508         return self.tk.call('wm', 'deiconify', self._w)
01509     deiconify = wm_deiconify
01510     def wm_focusmodel(self, model=None):
01511         """Set focus model to MODEL. "active" means that this widget will claim
01512         the focus itself, "passive" means that the window manager shall give
01513         the focus. Return current focus model if MODEL is None."""
01514         return self.tk.call('wm', 'focusmodel', self._w, model)
01515     focusmodel = wm_focusmodel
01516     def wm_frame(self):
01517         """Return identifier for decorative frame of this widget if present."""
01518         return self.tk.call('wm', 'frame', self._w)
01519     frame = wm_frame
01520     def wm_geometry(self, newGeometry=None):
01521         """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
01522         current value if None is given."""
01523         return self.tk.call('wm', 'geometry', self._w, newGeometry)
01524     geometry = wm_geometry
01525     def wm_grid(self,
01526          baseWidth=None, baseHeight=None,
01527          widthInc=None, heightInc=None):
01528         """Instruct the window manager that this widget shall only be
01529         resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
01530         height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
01531         number of grid units requested in Tk_GeometryRequest."""
01532         return self._getints(self.tk.call(
01533             'wm', 'grid', self._w,
01534             baseWidth, baseHeight, widthInc, heightInc))
01535     grid = wm_grid
01536     def wm_group(self, pathName=None):
01537         """Set the group leader widgets for related widgets to PATHNAME. Return
01538         the group leader of this widget if None is given."""
01539         return self.tk.call('wm', 'group', self._w, pathName)
01540     group = wm_group
01541     def wm_iconbitmap(self, bitmap=None, default=None):
01542         """Set bitmap for the iconified widget to BITMAP. Return
01543         the bitmap if None is given.
01544 
01545         Under Windows, the DEFAULT parameter can be used to set the icon
01546         for the widget and any descendents that don't have an icon set
01547         explicitly.  DEFAULT can be the relative path to a .ico file
01548         (example: root.iconbitmap(default='myicon.ico') ).  See Tk
01549         documentation for more information."""
01550         if default:
01551             return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
01552         else:
01553             return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
01554     iconbitmap = wm_iconbitmap
01555     def wm_iconify(self):
01556         """Display widget as icon."""
01557         return self.tk.call('wm', 'iconify', self._w)
01558     iconify = wm_iconify
01559     def wm_iconmask(self, bitmap=None):
01560         """Set mask for the icon bitmap of this widget. Return the
01561         mask if None is given."""
01562         return self.tk.call('wm', 'iconmask', self._w, bitmap)
01563     iconmask = wm_iconmask
01564     def wm_iconname(self, newName=None):
01565         """Set the name of the icon for this widget. Return the name if
01566         None is given."""
01567         return self.tk.call('wm', 'iconname', self._w, newName)
01568     iconname = wm_iconname
01569     def wm_iconposition(self, x=None, y=None):
01570         """Set the position of the icon of this widget to X and Y. Return
01571         a tuple of the current values of X and X if None is given."""
01572         return self._getints(self.tk.call(
01573             'wm', 'iconposition', self._w, x, y))
01574     iconposition = wm_iconposition
01575     def wm_iconwindow(self, pathName=None):
01576         """Set widget PATHNAME to be displayed instead of icon. Return the current
01577         value if None is given."""
01578         return self.tk.call('wm', 'iconwindow', self._w, pathName)
01579     iconwindow = wm_iconwindow
01580     def wm_maxsize(self, width=None, height=None):
01581         """Set max WIDTH and HEIGHT for this widget. If the window is gridded
01582         the values are given in grid units. Return the current values if None
01583         is given."""
01584         return self._getints(self.tk.call(
01585             'wm', 'maxsize', self._w, width, height))
01586     maxsize = wm_maxsize
01587     def wm_minsize(self, width=None, height=None):
01588         """Set min WIDTH and HEIGHT for this widget. If the window is gridded
01589         the values are given in grid units. Return the current values if None
01590         is given."""
01591         return self._getints(self.tk.call(
01592             'wm', 'minsize', self._w, width, height))
01593     minsize = wm_minsize
01594     def wm_overrideredirect(self, boolean=None):
01595         """Instruct the window manager to ignore this widget
01596         if BOOLEAN is given with 1. Return the current value if None
01597         is given."""
01598         return self._getboolean(self.tk.call(
01599             'wm', 'overrideredirect', self._w, boolean))
01600     overrideredirect = wm_overrideredirect
01601     def wm_positionfrom(self, who=None):
01602         """Instruct the window manager that the position of this widget shall
01603         be defined by the user if WHO is "user", and by its own policy if WHO is
01604         "program"."""
01605         return self.tk.call('wm', 'positionfrom', self._w, who)
01606     positionfrom = wm_positionfrom
01607     def wm_protocol(self, name=None, func=None):
01608         """Bind function FUNC to command NAME for this widget.
01609         Return the function bound to NAME if None is given. NAME could be
01610         e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
01611         if hasattr(func, '__call__'):
01612             command = self._register(func)
01613         else:
01614             command = func
01615         return self.tk.call(
01616             'wm', 'protocol', self._w, name, command)
01617     protocol = wm_protocol
01618     def wm_resizable(self, width=None, height=None):
01619         """Instruct the window manager whether this width can be resized
01620         in WIDTH or HEIGHT. Both values are boolean values."""
01621         return self.tk.call('wm', 'resizable', self._w, width, height)
01622     resizable = wm_resizable
01623     def wm_sizefrom(self, who=None):
01624         """Instruct the window manager that the size of this widget shall
01625         be defined by the user if WHO is "user", and by its own policy if WHO is
01626         "program"."""
01627         return self.tk.call('wm', 'sizefrom', self._w, who)
01628     sizefrom = wm_sizefrom
01629     def wm_state(self, newstate=None):
01630         """Query or set the state of this widget as one of normal, icon,
01631         iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
01632         return self.tk.call('wm', 'state', self._w, newstate)
01633     state = wm_state
01634     def wm_title(self, string=None):
01635         """Set the title of this widget."""
01636         return self.tk.call('wm', 'title', self._w, string)
01637     title = wm_title
01638     def wm_transient(self, master=None):
01639         """Instruct the window manager that this widget is transient
01640         with regard to widget MASTER."""
01641         return self.tk.call('wm', 'transient', self._w, master)
01642     transient = wm_transient
01643     def wm_withdraw(self):
01644         """Withdraw this widget from the screen such that it is unmapped
01645         and forgotten by the window manager. Re-draw it with wm_deiconify."""
01646         return self.tk.call('wm', 'withdraw', self._w)
01647     withdraw = wm_withdraw
01648 
01649 
01650 class Tk(Misc, Wm):
01651     """Toplevel widget of Tk which represents mostly the main window
01652     of an application. It has an associated Tcl interpreter."""
01653     _w = '.'
01654     def __init__(self, screenName=None, baseName=None, className='Tk',
01655                  useTk=1, sync=0, use=None):
01656         """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
01657         be created. BASENAME will be used for the identification of the profile file (see
01658         readprofile).
01659         It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
01660         is the name of the widget class."""
01661         self.master = None
01662         self.children = {}
01663         self._tkloaded = 0
01664         # to avoid recursions in the getattr code in case of failure, we
01665         # ensure that self.tk is always _something_.
01666         self.tk = None
01667         if baseName is None:
01668             import sys, os
01669             baseName = os.path.basename(sys.argv[0])
01670             baseName, ext = os.path.splitext(baseName)
01671             if ext not in ('.py', '.pyc', '.pyo'):
01672                 baseName = baseName + ext
01673         interactive = 0
01674         self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
01675         if useTk:
01676             self._loadtk()
01677         self.readprofile(baseName, className)
01678     def loadtk(self):
01679         if not self._tkloaded:
01680             self.tk.loadtk()
01681             self._loadtk()
01682     def _loadtk(self):
01683         self._tkloaded = 1
01684         global _default_root
01685         # Version sanity checks
01686         tk_version = self.tk.getvar('tk_version')
01687         if tk_version != _tkinter.TK_VERSION:
01688             raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
01689                                % (_tkinter.TK_VERSION, tk_version))
01690         # Under unknown circumstances, tcl_version gets coerced to float
01691         tcl_version = str(self.tk.getvar('tcl_version'))
01692         if tcl_version != _tkinter.TCL_VERSION:
01693             raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
01694                                % (_tkinter.TCL_VERSION, tcl_version))
01695         if TkVersion < 4.0:
01696             raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
01697                                % str(TkVersion))
01698         # Create and register the tkerror and exit commands
01699         # We need to inline parts of _register here, _ register
01700         # would register differently-named commands.
01701         if self._tclCommands is None:
01702             self._tclCommands = []
01703         self.tk.createcommand('tkerror', _tkerror)
01704         self.tk.createcommand('exit', _exit)
01705         self._tclCommands.append('tkerror')
01706         self._tclCommands.append('exit')
01707         if _support_default_root and not _default_root:
01708             _default_root = self
01709         self.protocol("WM_DELETE_WINDOW", self.destroy)
01710     def destroy(self):
01711         """Destroy this and all descendants widgets. This will
01712         end the application of this Tcl interpreter."""
01713         for c in list(self.children.values()): c.destroy()
01714         self.tk.call('destroy', self._w)
01715         Misc.destroy(self)
01716         global _default_root
01717         if _support_default_root and _default_root is self:
01718             _default_root = None
01719     def readprofile(self, baseName, className):
01720         """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
01721         the Tcl Interpreter and calls exec on the contents of BASENAME.py and
01722         CLASSNAME.py if such a file exists in the home directory."""
01723         import os
01724         if 'HOME' in os.environ: home = os.environ['HOME']
01725         else: home = os.curdir
01726         class_tcl = os.path.join(home, '.%s.tcl' % className)
01727         class_py = os.path.join(home, '.%s.py' % className)
01728         base_tcl = os.path.join(home, '.%s.tcl' % baseName)
01729         base_py = os.path.join(home, '.%s.py' % baseName)
01730         dir = {'self': self}
01731         exec('from tkinter import *', dir)
01732         if os.path.isfile(class_tcl):
01733             self.tk.call('source', class_tcl)
01734         if os.path.isfile(class_py):
01735             exec(open(class_py).read(), dir)
01736         if os.path.isfile(base_tcl):
01737             self.tk.call('source', base_tcl)
01738         if os.path.isfile(base_py):
01739             exec(open(base_py).read(), dir)
01740     def report_callback_exception(self, exc, val, tb):
01741         """Internal function. It reports exception on sys.stderr."""
01742         import traceback, sys
01743         sys.stderr.write("Exception in Tkinter callback\n")
01744         sys.last_type = exc
01745         sys.last_value = val
01746         sys.last_traceback = tb
01747         traceback.print_exception(exc, val, tb)
01748     def __getattr__(self, attr):
01749         "Delegate attribute access to the interpreter object"
01750         return getattr(self.tk, attr)
01751 
01752 # Ideally, the classes Pack, Place and Grid disappear, the
01753 # pack/place/grid methods are defined on the Widget class, and
01754 # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
01755 # ...), with pack(), place() and grid() being short for
01756 # pack_configure(), place_configure() and grid_columnconfigure(), and
01757 # forget() being short for pack_forget().  As a practical matter, I'm
01758 # afraid that there is too much code out there that may be using the
01759 # Pack, Place or Grid class, so I leave them intact -- but only as
01760 # backwards compatibility features.  Also note that those methods that
01761 # take a master as argument (e.g. pack_propagate) have been moved to
01762 # the Misc class (which now incorporates all methods common between
01763 # toplevel and interior widgets).  Again, for compatibility, these are
01764 # copied into the Pack, Place or Grid class.
01765 
01766 
01767 def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
01768     return Tk(screenName, baseName, className, useTk)
01769 
01770 class Pack:
01771     """Geometry manager Pack.
01772 
01773     Base class to use the methods pack_* in every widget."""
01774     def pack_configure(self, cnf={}, **kw):
01775         """Pack a widget in the parent widget. Use as options:
01776         after=widget - pack it after you have packed widget
01777         anchor=NSEW (or subset) - position widget according to
01778                                   given direction
01779         before=widget - pack it before you will pack widget
01780         expand=bool - expand widget if parent size grows
01781         fill=NONE or X or Y or BOTH - fill widget if widget grows
01782         in=master - use master to contain this widget
01783         in_=master - see 'in' option description
01784         ipadx=amount - add internal padding in x direction
01785         ipady=amount - add internal padding in y direction
01786         padx=amount - add padding in x direction
01787         pady=amount - add padding in y direction
01788         side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
01789         """
01790         self.tk.call(
01791               ('pack', 'configure', self._w)
01792               + self._options(cnf, kw))
01793     pack = configure = config = pack_configure
01794     def pack_forget(self):
01795         """Unmap this widget and do not use it for the packing order."""
01796         self.tk.call('pack', 'forget', self._w)
01797     forget = pack_forget
01798     def pack_info(self):
01799         """Return information about the packing options
01800         for this widget."""
01801         words = self.tk.splitlist(
01802             self.tk.call('pack', 'info', self._w))
01803         dict = {}
01804         for i in range(0, len(words), 2):
01805             key = words[i][1:]
01806             value = words[i+1]
01807             if value[:1] == '.':
01808                 value = self._nametowidget(value)
01809             dict[key] = value
01810         return dict
01811     info = pack_info
01812     propagate = pack_propagate = Misc.pack_propagate
01813     slaves = pack_slaves = Misc.pack_slaves
01814 
01815 class Place:
01816     """Geometry manager Place.
01817 
01818     Base class to use the methods place_* in every widget."""
01819     def place_configure(self, cnf={}, **kw):
01820         """Place a widget in the parent widget. Use as options:
01821         in=master - master relative to which the widget is placed
01822         in_=master - see 'in' option description
01823         x=amount - locate anchor of this widget at position x of master
01824         y=amount - locate anchor of this widget at position y of master
01825         relx=amount - locate anchor of this widget between 0.0 and 1.0
01826                       relative to width of master (1.0 is right edge)
01827         rely=amount - locate anchor of this widget between 0.0 and 1.0
01828                       relative to height of master (1.0 is bottom edge)
01829         anchor=NSEW (or subset) - position anchor according to given direction
01830         width=amount - width of this widget in pixel
01831         height=amount - height of this widget in pixel
01832         relwidth=amount - width of this widget between 0.0 and 1.0
01833                           relative to width of master (1.0 is the same width
01834                           as the master)
01835         relheight=amount - height of this widget between 0.0 and 1.0
01836                            relative to height of master (1.0 is the same
01837                            height as the master)
01838         bordermode="inside" or "outside" - whether to take border width of
01839                                            master widget into account
01840         """
01841         self.tk.call(
01842               ('place', 'configure', self._w)
01843               + self._options(cnf, kw))
01844     place = configure = config = place_configure
01845     def place_forget(self):
01846         """Unmap this widget."""
01847         self.tk.call('place', 'forget', self._w)
01848     forget = place_forget
01849     def place_info(self):
01850         """Return information about the placing options
01851         for this widget."""
01852         words = self.tk.splitlist(
01853             self.tk.call('place', 'info', self._w))
01854         dict = {}
01855         for i in range(0, len(words), 2):
01856             key = words[i][1:]
01857             value = words[i+1]
01858             if value[:1] == '.':
01859                 value = self._nametowidget(value)
01860             dict[key] = value
01861         return dict
01862     info = place_info
01863     slaves = place_slaves = Misc.place_slaves
01864 
01865 class Grid:
01866     """Geometry manager Grid.
01867 
01868     Base class to use the methods grid_* in every widget."""
01869     # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
01870     def grid_configure(self, cnf={}, **kw):
01871         """Position a widget in the parent widget in a grid. Use as options:
01872         column=number - use cell identified with given column (starting with 0)
01873         columnspan=number - this widget will span several columns
01874         in=master - use master to contain this widget
01875         in_=master - see 'in' option description
01876         ipadx=amount - add internal padding in x direction
01877         ipady=amount - add internal padding in y direction
01878         padx=amount - add padding in x direction
01879         pady=amount - add padding in y direction
01880         row=number - use cell identified with given row (starting with 0)
01881         rowspan=number - this widget will span several rows
01882         sticky=NSEW - if cell is larger on which sides will this
01883                       widget stick to the cell boundary
01884         """
01885         self.tk.call(
01886               ('grid', 'configure', self._w)
01887               + self._options(cnf, kw))
01888     grid = configure = config = grid_configure
01889     bbox = grid_bbox = Misc.grid_bbox
01890     columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
01891     def grid_forget(self):
01892         """Unmap this widget."""
01893         self.tk.call('grid', 'forget', self._w)
01894     forget = grid_forget
01895     def grid_remove(self):
01896         """Unmap this widget but remember the grid options."""
01897         self.tk.call('grid', 'remove', self._w)
01898     def grid_info(self):
01899         """Return information about the options
01900         for positioning this widget in a grid."""
01901         words = self.tk.splitlist(
01902             self.tk.call('grid', 'info', self._w))
01903         dict = {}
01904         for i in range(0, len(words), 2):
01905             key = words[i][1:]
01906             value = words[i+1]
01907             if value[:1] == '.':
01908                 value = self._nametowidget(value)
01909             dict[key] = value
01910         return dict
01911     info = grid_info
01912     location = grid_location = Misc.grid_location
01913     propagate = grid_propagate = Misc.grid_propagate
01914     rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
01915     size = grid_size = Misc.grid_size
01916     slaves = grid_slaves = Misc.grid_slaves
01917 
01918 class BaseWidget(Misc):
01919     """Internal class."""
01920     def _setup(self, master, cnf):
01921         """Internal function. Sets up information about children."""
01922         if _support_default_root:
01923             global _default_root
01924             if not master:
01925                 if not _default_root:
01926                     _default_root = Tk()
01927                 master = _default_root
01928         self.master = master
01929         self.tk = master.tk
01930         name = None
01931         if 'name' in cnf:
01932             name = cnf['name']
01933             del cnf['name']
01934         if not name:
01935             name = repr(id(self))
01936         self._name = name
01937         if master._w=='.':
01938             self._w = '.' + name
01939         else:
01940             self._w = master._w + '.' + name
01941         self.children = {}
01942         if self._name in self.master.children:
01943             self.master.children[self._name].destroy()
01944         self.master.children[self._name] = self
01945     def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
01946         """Construct a widget with the parent widget MASTER, a name WIDGETNAME
01947         and appropriate options."""
01948         if kw:
01949             cnf = _cnfmerge((cnf, kw))
01950         self.widgetName = widgetName
01951         BaseWidget._setup(self, master, cnf)
01952         if self._tclCommands is None:
01953             self._tclCommands = []
01954         classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
01955         for k, v in classes:
01956             del cnf[k]
01957         self.tk.call(
01958             (widgetName, self._w) + extra + self._options(cnf))
01959         for k, v in classes:
01960             k.configure(self, v)
01961     def destroy(self):
01962         """Destroy this and all descendants widgets."""
01963         for c in list(self.children.values()): c.destroy()
01964         self.tk.call('destroy', self._w)
01965         if self._name in self.master.children:
01966             del self.master.children[self._name]
01967         Misc.destroy(self)
01968     def _do(self, name, args=()):
01969         # XXX Obsolete -- better use self.tk.call directly!
01970         return self.tk.call((self._w, name) + args)
01971 
01972 class Widget(BaseWidget, Pack, Place, Grid):
01973     """Internal class.
01974 
01975     Base class for a widget which can be positioned with the geometry managers
01976     Pack, Place or Grid."""
01977     pass
01978 
01979 class Toplevel(BaseWidget, Wm):
01980     """Toplevel widget, e.g. for dialogs."""
01981     def __init__(self, master=None, cnf={}, **kw):
01982         """Construct a toplevel widget with the parent MASTER.
01983 
01984         Valid resource names: background, bd, bg, borderwidth, class,
01985         colormap, container, cursor, height, highlightbackground,
01986         highlightcolor, highlightthickness, menu, relief, screen, takefocus,
01987         use, visual, width."""
01988         if kw:
01989             cnf = _cnfmerge((cnf, kw))
01990         extra = ()
01991         for wmkey in ['screen', 'class_', 'class', 'visual',
01992                   'colormap']:
01993             if wmkey in cnf:
01994                 val = cnf[wmkey]
01995                 # TBD: a hack needed because some keys
01996                 # are not valid as keyword arguments
01997                 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
01998                 else: opt = '-'+wmkey
01999                 extra = extra + (opt, val)
02000                 del cnf[wmkey]
02001         BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
02002         root = self._root()
02003         self.iconname(root.iconname())
02004         self.title(root.title())
02005         self.protocol("WM_DELETE_WINDOW", self.destroy)
02006 
02007 class Button(Widget):
02008     """Button widget."""
02009     def __init__(self, master=None, cnf={}, **kw):
02010         """Construct a button widget with the parent MASTER.
02011 
02012         STANDARD OPTIONS
02013 
02014             activebackground, activeforeground, anchor,
02015             background, bitmap, borderwidth, cursor,
02016             disabledforeground, font, foreground
02017             highlightbackground, highlightcolor,
02018             highlightthickness, image, justify,
02019             padx, pady, relief, repeatdelay,
02020             repeatinterval, takefocus, text,
02021             textvariable, underline, wraplength
02022 
02023         WIDGET-SPECIFIC OPTIONS
02024 
02025             command, compound, default, height,
02026             overrelief, state, width
02027         """
02028         Widget.__init__(self, master, 'button', cnf, kw)
02029 
02030     def tkButtonEnter(self, *dummy):
02031         self.tk.call('tkButtonEnter', self._w)
02032 
02033     def tkButtonLeave(self, *dummy):
02034         self.tk.call('tkButtonLeave', self._w)
02035 
02036     def tkButtonDown(self, *dummy):
02037         self.tk.call('tkButtonDown', self._w)
02038 
02039     def tkButtonUp(self, *dummy):
02040         self.tk.call('tkButtonUp', self._w)
02041 
02042     def tkButtonInvoke(self, *dummy):
02043         self.tk.call('tkButtonInvoke', self._w)
02044 
02045     def flash(self):
02046         """Flash the button.
02047 
02048         This is accomplished by redisplaying
02049         the button several times, alternating between active and
02050         normal colors. At the end of the flash the button is left
02051         in the same normal/active state as when the command was
02052         invoked. This command is ignored if the button's state is
02053         disabled.
02054         """
02055         self.tk.call(self._w, 'flash')
02056 
02057     def invoke(self):
02058         """Invoke the command associated with the button.
02059 
02060         The return value is the return value from the command,
02061         or an empty string if there is no command associated with
02062         the button. This command is ignored if the button's state
02063         is disabled.
02064         """
02065         return self.tk.call(self._w, 'invoke')
02066 
02067 # Indices:
02068 # XXX I don't like these -- take them away
02069 def AtEnd():
02070     return 'end'
02071 def AtInsert(*args):
02072     s = 'insert'
02073     for a in args:
02074         if a: s = s + (' ' + a)
02075     return s
02076 def AtSelFirst():
02077     return 'sel.first'
02078 def AtSelLast():
02079     return 'sel.last'
02080 def At(x, y=None):
02081     if y is None:
02082         return '@%r' % (x,)
02083     else:
02084         return '@%r,%r' % (x, y)
02085 
02086 class Canvas(Widget, XView, YView):
02087     """Canvas widget to display graphical elements like lines or text."""
02088     def __init__(self, master=None, cnf={}, **kw):
02089         """Construct a canvas widget with the parent MASTER.
02090 
02091         Valid resource names: background, bd, bg, borderwidth, closeenough,
02092         confine, cursor, height, highlightbackground, highlightcolor,
02093         highlightthickness, insertbackground, insertborderwidth,
02094         insertofftime, insertontime, insertwidth, offset, relief,
02095         scrollregion, selectbackground, selectborderwidth, selectforeground,
02096         state, takefocus, width, xscrollcommand, xscrollincrement,
02097         yscrollcommand, yscrollincrement."""
02098         Widget.__init__(self, master, 'canvas', cnf, kw)
02099     def addtag(self, *args):
02100         """Internal function."""
02101         self.tk.call((self._w, 'addtag') + args)
02102     def addtag_above(self, newtag, tagOrId):
02103         """Add tag NEWTAG to all items above TAGORID."""
02104         self.addtag(newtag, 'above', tagOrId)
02105     def addtag_all(self, newtag):
02106         """Add tag NEWTAG to all items."""
02107         self.addtag(newtag, 'all')
02108     def addtag_below(self, newtag, tagOrId):
02109         """Add tag NEWTAG to all items below TAGORID."""
02110         self.addtag(newtag, 'below', tagOrId)
02111     def addtag_closest(self, newtag, x, y, halo=None, start=None):
02112         """Add tag NEWTAG to item which is closest to pixel at X, Y.
02113         If several match take the top-most.
02114         All items closer than HALO are considered overlapping (all are
02115         closests). If START is specified the next below this tag is taken."""
02116         self.addtag(newtag, 'closest', x, y, halo, start)
02117     def addtag_enclosed(self, newtag, x1, y1, x2, y2):
02118         """Add tag NEWTAG to all items in the rectangle defined
02119         by X1,Y1,X2,Y2."""
02120         self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
02121     def addtag_overlapping(self, newtag, x1, y1, x2, y2):
02122         """Add tag NEWTAG to all items which overlap the rectangle
02123         defined by X1,Y1,X2,Y2."""
02124         self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
02125     def addtag_withtag(self, newtag, tagOrId):
02126         """Add tag NEWTAG to all items with TAGORID."""
02127         self.addtag(newtag, 'withtag', tagOrId)
02128     def bbox(self, *args):
02129         """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
02130         which encloses all items with tags specified as arguments."""
02131         return self._getints(
02132             self.tk.call((self._w, 'bbox') + args)) or None
02133     def tag_unbind(self, tagOrId, sequence, funcid=None):
02134         """Unbind for all items with TAGORID for event SEQUENCE  the
02135         function identified with FUNCID."""
02136         self.tk.call(self._w, 'bind', tagOrId, sequence, '')
02137         if funcid:
02138             self.deletecommand(funcid)
02139     def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
02140         """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
02141 
02142         An additional boolean parameter ADD specifies whether FUNC will be
02143         called additionally to the other bound function or whether it will
02144         replace the previous function. See bind for the return value."""
02145         return self._bind((self._w, 'bind', tagOrId),
02146                   sequence, func, add)
02147     def canvasx(self, screenx, gridspacing=None):
02148         """Return the canvas x coordinate of pixel position SCREENX rounded
02149         to nearest multiple of GRIDSPACING units."""
02150         return getdouble(self.tk.call(
02151             self._w, 'canvasx', screenx, gridspacing))
02152     def canvasy(self, screeny, gridspacing=None):
02153         """Return the canvas y coordinate of pixel position SCREENY rounded
02154         to nearest multiple of GRIDSPACING units."""
02155         return getdouble(self.tk.call(
02156             self._w, 'canvasy', screeny, gridspacing))
02157     def coords(self, *args):
02158         """Return a list of coordinates for the item given in ARGS."""
02159         # XXX Should use _flatten on args
02160         return [getdouble(x) for x in
02161                            self.tk.splitlist(
02162                    self.tk.call((self._w, 'coords') + args))]
02163     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
02164         """Internal function."""
02165         args = _flatten(args)
02166         cnf = args[-1]
02167         if isinstance(cnf, (dict, tuple)):
02168             args = args[:-1]
02169         else:
02170             cnf = {}
02171         return getint(self.tk.call(
02172             self._w, 'create', itemType,
02173             *(args + self._options(cnf, kw))))
02174     def create_arc(self, *args, **kw):
02175         """Create arc shaped region with coordinates x1,y1,x2,y2."""
02176         return self._create('arc', args, kw)
02177     def create_bitmap(self, *args, **kw):
02178         """Create bitmap with coordinates x1,y1."""
02179         return self._create('bitmap', args, kw)
02180     def create_image(self, *args, **kw):
02181         """Create image item with coordinates x1,y1."""
02182         return self._create('image', args, kw)
02183     def create_line(self, *args, **kw):
02184         """Create line with coordinates x1,y1,...,xn,yn."""
02185         return self._create('line', args, kw)
02186     def create_oval(self, *args, **kw):
02187         """Create oval with coordinates x1,y1,x2,y2."""
02188         return self._create('oval', args, kw)
02189     def create_polygon(self, *args, **kw):
02190         """Create polygon with coordinates x1,y1,...,xn,yn."""
02191         return self._create('polygon', args, kw)
02192     def create_rectangle(self, *args, **kw):
02193         """Create rectangle with coordinates x1,y1,x2,y2."""
02194         return self._create('rectangle', args, kw)
02195     def create_text(self, *args, **kw):
02196         """Create text with coordinates x1,y1."""
02197         return self._create('text', args, kw)
02198     def create_window(self, *args, **kw):
02199         """Create window with coordinates x1,y1,x2,y2."""
02200         return self._create('window', args, kw)
02201     def dchars(self, *args):
02202         """Delete characters of text items identified by tag or id in ARGS (possibly
02203         several times) from FIRST to LAST character (including)."""
02204         self.tk.call((self._w, 'dchars') + args)
02205     def delete(self, *args):
02206         """Delete items identified by all tag or ids contained in ARGS."""
02207         self.tk.call((self._w, 'delete') + args)
02208     def dtag(self, *args):
02209         """Delete tag or id given as last arguments in ARGS from items
02210         identified by first argument in ARGS."""
02211         self.tk.call((self._w, 'dtag') + args)
02212     def find(self, *args):
02213         """Internal function."""
02214         return self._getints(
02215             self.tk.call((self._w, 'find') + args)) or ()
02216     def find_above(self, tagOrId):
02217         """Return items above TAGORID."""
02218         return self.find('above', tagOrId)
02219     def find_all(self):
02220         """Return all items."""
02221         return self.find('all')
02222     def find_below(self, tagOrId):
02223         """Return all items below TAGORID."""
02224         return self.find('below', tagOrId)
02225     def find_closest(self, x, y, halo=None, start=None):
02226         """Return item which is closest to pixel at X, Y.
02227         If several match take the top-most.
02228         All items closer than HALO are considered overlapping (all are
02229         closests). If START is specified the next below this tag is taken."""
02230         return self.find('closest', x, y, halo, start)
02231     def find_enclosed(self, x1, y1, x2, y2):
02232         """Return all items in rectangle defined
02233         by X1,Y1,X2,Y2."""
02234         return self.find('enclosed', x1, y1, x2, y2)
02235     def find_overlapping(self, x1, y1, x2, y2):
02236         """Return all items which overlap the rectangle
02237         defined by X1,Y1,X2,Y2."""
02238         return self.find('overlapping', x1, y1, x2, y2)
02239     def find_withtag(self, tagOrId):
02240         """Return all items with TAGORID."""
02241         return self.find('withtag', tagOrId)
02242     def focus(self, *args):
02243         """Set focus to the first item specified in ARGS."""
02244         return self.tk.call((self._w, 'focus') + args)
02245     def gettags(self, *args):
02246         """Return tags associated with the first item specified in ARGS."""
02247         return self.tk.splitlist(
02248             self.tk.call((self._w, 'gettags') + args))
02249     def icursor(self, *args):
02250         """Set cursor at position POS in the item identified by TAGORID.
02251         In ARGS TAGORID must be first."""
02252         self.tk.call((self._w, 'icursor') + args)
02253     def index(self, *args):
02254         """Return position of cursor as integer in item specified in ARGS."""
02255         return getint(self.tk.call((self._w, 'index') + args))
02256     def insert(self, *args):
02257         """Insert TEXT in item TAGORID at position POS. ARGS must
02258         be TAGORID POS TEXT."""
02259         self.tk.call((self._w, 'insert') + args)
02260     def itemcget(self, tagOrId, option):
02261         """Return the resource value for an OPTION for item TAGORID."""
02262         return self.tk.call(
02263             (self._w, 'itemcget') + (tagOrId, '-'+option))
02264     def itemconfigure(self, tagOrId, cnf=None, **kw):
02265         """Configure resources of an item TAGORID.
02266 
02267         The values for resources are specified as keyword
02268         arguments. To get an overview about
02269         the allowed keyword arguments call the method without arguments.
02270         """
02271         return self._configure(('itemconfigure', tagOrId), cnf, kw)
02272     itemconfig = itemconfigure
02273     # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
02274     # so the preferred name for them is tag_lower, tag_raise
02275     # (similar to tag_bind, and similar to the Text widget);
02276     # unfortunately can't delete the old ones yet (maybe in 1.6)
02277     def tag_lower(self, *args):
02278         """Lower an item TAGORID given in ARGS
02279         (optional below another item)."""
02280         self.tk.call((self._w, 'lower') + args)
02281     lower = tag_lower
02282     def move(self, *args):
02283         """Move an item TAGORID given in ARGS."""
02284         self.tk.call((self._w, 'move') + args)
02285     def postscript(self, cnf={}, **kw):
02286         """Print the contents of the canvas to a postscript
02287         file. Valid options: colormap, colormode, file, fontmap,
02288         height, pageanchor, pageheight, pagewidth, pagex, pagey,
02289         rotate, witdh, x, y."""
02290         return self.tk.call((self._w, 'postscript') +
02291                     self._options(cnf, kw))
02292     def tag_raise(self, *args):
02293         """Raise an item TAGORID given in ARGS
02294         (optional above another item)."""
02295         self.tk.call((self._w, 'raise') + args)
02296     lift = tkraise = tag_raise
02297     def scale(self, *args):
02298         """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
02299         self.tk.call((self._w, 'scale') + args)
02300     def scan_mark(self, x, y):
02301         """Remember the current X, Y coordinates."""
02302         self.tk.call(self._w, 'scan', 'mark', x, y)
02303     def scan_dragto(self, x, y, gain=10):
02304         """Adjust the view of the canvas to GAIN times the
02305         difference between X and Y and the coordinates given in
02306         scan_mark."""
02307         self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
02308     def select_adjust(self, tagOrId, index):
02309         """Adjust the end of the selection near the cursor of an item TAGORID to index."""
02310         self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
02311     def select_clear(self):
02312         """Clear the selection if it is in this widget."""
02313         self.tk.call(self._w, 'select', 'clear')
02314     def select_from(self, tagOrId, index):
02315         """Set the fixed end of a selection in item TAGORID to INDEX."""
02316         self.tk.call(self._w, 'select', 'from', tagOrId, index)
02317     def select_item(self):
02318         """Return the item which has the selection."""
02319         return self.tk.call(self._w, 'select', 'item') or None
02320     def select_to(self, tagOrId, index):
02321         """Set the variable end of a selection in item TAGORID to INDEX."""
02322         self.tk.call(self._w, 'select', 'to', tagOrId, index)
02323     def type(self, tagOrId):
02324         """Return the type of the item TAGORID."""
02325         return self.tk.call(self._w, 'type', tagOrId) or None
02326 
02327 class Checkbutton(Widget):
02328     """Checkbutton widget which is either in on- or off-state."""
02329     def __init__(self, master=None, cnf={}, **kw):
02330         """Construct a checkbutton widget with the parent MASTER.
02331 
02332         Valid resource names: activebackground, activeforeground, anchor,
02333         background, bd, bg, bitmap, borderwidth, command, cursor,
02334         disabledforeground, fg, font, foreground, height,
02335         highlightbackground, highlightcolor, highlightthickness, image,
02336         indicatoron, justify, offvalue, onvalue, padx, pady, relief,
02337         selectcolor, selectimage, state, takefocus, text, textvariable,
02338         underline, variable, width, wraplength."""
02339         Widget.__init__(self, master, 'checkbutton', cnf, kw)
02340     def deselect(self):
02341         """Put the button in off-state."""
02342         self.tk.call(self._w, 'deselect')
02343     def flash(self):
02344         """Flash the button."""
02345         self.tk.call(self._w, 'flash')
02346     def invoke(self):
02347         """Toggle the button and invoke a command if given as resource."""
02348         return self.tk.call(self._w, 'invoke')
02349     def select(self):
02350         """Put the button in on-state."""
02351         self.tk.call(self._w, 'select')
02352     def toggle(self):
02353         """Toggle the button."""
02354         self.tk.call(self._w, 'toggle')
02355 
02356 class Entry(Widget, XView):
02357     """Entry widget which allows to display simple text."""
02358     def __init__(self, master=None, cnf={}, **kw):
02359         """Construct an entry widget with the parent MASTER.
02360 
02361         Valid resource names: background, bd, bg, borderwidth, cursor,
02362         exportselection, fg, font, foreground, highlightbackground,
02363         highlightcolor, highlightthickness, insertbackground,
02364         insertborderwidth, insertofftime, insertontime, insertwidth,
02365         invalidcommand, invcmd, justify, relief, selectbackground,
02366         selectborderwidth, selectforeground, show, state, takefocus,
02367         textvariable, validate, validatecommand, vcmd, width,
02368         xscrollcommand."""
02369         Widget.__init__(self, master, 'entry', cnf, kw)
02370     def delete(self, first, last=None):
02371         """Delete text from FIRST to LAST (not included)."""
02372         self.tk.call(self._w, 'delete', first, last)
02373     def get(self):
02374         """Return the text."""
02375         return self.tk.call(self._w, 'get')
02376     def icursor(self, index):
02377         """Insert cursor at INDEX."""
02378         self.tk.call(self._w, 'icursor', index)
02379     def index(self, index):
02380         """Return position of cursor."""
02381         return getint(self.tk.call(
02382             self._w, 'index', index))
02383     def insert(self, index, string):
02384         """Insert STRING at INDEX."""
02385         self.tk.call(self._w, 'insert', index, string)
02386     def scan_mark(self, x):
02387         """Remember the current X, Y coordinates."""
02388         self.tk.call(self._w, 'scan', 'mark', x)
02389     def scan_dragto(self, x):
02390         """Adjust the view of the canvas to 10 times the
02391         difference between X and Y and the coordinates given in
02392         scan_mark."""
02393         self.tk.call(self._w, 'scan', 'dragto', x)
02394     def selection_adjust(self, index):
02395         """Adjust the end of the selection near the cursor to INDEX."""
02396         self.tk.call(self._w, 'selection', 'adjust', index)
02397     select_adjust = selection_adjust
02398     def selection_clear(self):
02399         """Clear the selection if it is in this widget."""
02400         self.tk.call(self._w, 'selection', 'clear')
02401     select_clear = selection_clear
02402     def selection_from(self, index):
02403         """Set the fixed end of a selection to INDEX."""
02404         self.tk.call(self._w, 'selection', 'from', index)
02405     select_from = selection_from
02406     def selection_present(self):
02407         """Return True if there are characters selected in the entry, False
02408         otherwise."""
02409         return self.tk.getboolean(
02410             self.tk.call(self._w, 'selection', 'present'))
02411     select_present = selection_present
02412     def selection_range(self, start, end):
02413         """Set the selection from START to END (not included)."""
02414         self.tk.call(self._w, 'selection', 'range', start, end)
02415     select_range = selection_range
02416     def selection_to(self, index):
02417         """Set the variable end of a selection to INDEX."""
02418         self.tk.call(self._w, 'selection', 'to', index)
02419     select_to = selection_to
02420 
02421 class Frame(Widget):
02422     """Frame widget which may contain other widgets and can have a 3D border."""
02423     def __init__(self, master=None, cnf={}, **kw):
02424         """Construct a frame widget with the parent MASTER.
02425 
02426         Valid resource names: background, bd, bg, borderwidth, class,
02427         colormap, container, cursor, height, highlightbackground,
02428         highlightcolor, highlightthickness, relief, takefocus, visual, width."""
02429         cnf = _cnfmerge((cnf, kw))
02430         extra = ()
02431         if 'class_' in cnf:
02432             extra = ('-class', cnf['class_'])
02433             del cnf['class_']
02434         elif 'class' in cnf:
02435             extra = ('-class', cnf['class'])
02436             del cnf['class']
02437         Widget.__init__(self, master, 'frame', cnf, {}, extra)
02438 
02439 class Label(Widget):
02440     """Label widget which can display text and bitmaps."""
02441     def __init__(self, master=None, cnf={}, **kw):
02442         """Construct a label widget with the parent MASTER.
02443 
02444         STANDARD OPTIONS
02445 
02446             activebackground, activeforeground, anchor,
02447             background, bitmap, borderwidth, cursor,
02448             disabledforeground, font, foreground,
02449             highlightbackground, highlightcolor,
02450             highlightthickness, image, justify,
02451             padx, pady, relief, takefocus, text,
02452             textvariable, underline, wraplength
02453 
02454         WIDGET-SPECIFIC OPTIONS
02455 
02456             height, state, width
02457 
02458         """
02459         Widget.__init__(self, master, 'label', cnf, kw)
02460 
02461 class Listbox(Widget, XView, YView):
02462     """Listbox widget which can display a list of strings."""
02463     def __init__(self, master=None, cnf={}, **kw):
02464         """Construct a listbox widget with the parent MASTER.
02465 
02466         Valid resource names: background, bd, bg, borderwidth, cursor,
02467         exportselection, fg, font, foreground, height, highlightbackground,
02468         highlightcolor, highlightthickness, relief, selectbackground,
02469         selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
02470         width, xscrollcommand, yscrollcommand, listvariable."""
02471         Widget.__init__(self, master, 'listbox', cnf, kw)
02472     def activate(self, index):
02473         """Activate item identified by INDEX."""
02474         self.tk.call(self._w, 'activate', index)
02475     def bbox(self, *args):
02476         """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
02477         which encloses the item identified by index in ARGS."""
02478         return self._getints(
02479             self.tk.call((self._w, 'bbox') + args)) or None
02480     def curselection(self):
02481         """Return list of indices of currently selected item."""
02482         # XXX Ought to apply self._getints()...
02483         return self.tk.splitlist(self.tk.call(
02484             self._w, 'curselection'))
02485     def delete(self, first, last=None):
02486         """Delete items from FIRST to LAST (not included)."""
02487         self.tk.call(self._w, 'delete', first, last)
02488     def get(self, first, last=None):
02489         """Get list of items from FIRST to LAST (not included)."""
02490         if last:
02491             return self.tk.splitlist(self.tk.call(
02492                 self._w, 'get', first, last))
02493         else:
02494             return self.tk.call(self._w, 'get', first)
02495     def index(self, index):
02496         """Return index of item identified with INDEX."""
02497         i = self.tk.call(self._w, 'index', index)
02498         if i == 'none': return None
02499         return getint(i)
02500     def insert(self, index, *elements):
02501         """Insert ELEMENTS at INDEX."""
02502         self.tk.call((self._w, 'insert', index) + elements)
02503     def nearest(self, y):
02504         """Get index of item which is nearest to y coordinate Y."""
02505         return getint(self.tk.call(
02506             self._w, 'nearest', y))
02507     def scan_mark(self, x, y):
02508         """Remember the current X, Y coordinates."""
02509         self.tk.call(self._w, 'scan', 'mark', x, y)
02510     def scan_dragto(self, x, y):
02511         """Adjust the view of the listbox to 10 times the
02512         difference between X and Y and the coordinates given in
02513         scan_mark."""
02514         self.tk.call(self._w, 'scan', 'dragto', x, y)
02515     def see(self, index):
02516         """Scroll such that INDEX is visible."""
02517         self.tk.call(self._w, 'see', index)
02518     def selection_anchor(self, index):
02519         """Set the fixed end oft the selection to INDEX."""
02520         self.tk.call(self._w, 'selection', 'anchor', index)
02521     select_anchor = selection_anchor
02522     def selection_clear(self, first, last=None):
02523         """Clear the selection from FIRST to LAST (not included)."""
02524         self.tk.call(self._w,
02525                  'selection', 'clear', first, last)
02526     select_clear = selection_clear
02527     def selection_includes(self, index):
02528         """Return 1 if INDEX is part of the selection."""
02529         return self.tk.getboolean(self.tk.call(
02530             self._w, 'selection', 'includes', index))
02531     select_includes = selection_includes
02532     def selection_set(self, first, last=None):
02533         """Set the selection from FIRST to LAST (not included) without
02534         changing the currently selected elements."""
02535         self.tk.call(self._w, 'selection', 'set', first, last)
02536     select_set = selection_set
02537     def size(self):
02538         """Return the number of elements in the listbox."""
02539         return getint(self.tk.call(self._w, 'size'))
02540     def itemcget(self, index, option):
02541         """Return the resource value for an ITEM and an OPTION."""
02542         return self.tk.call(
02543             (self._w, 'itemcget') + (index, '-'+option))
02544     def itemconfigure(self, index, cnf=None, **kw):
02545         """Configure resources of an ITEM.
02546 
02547         The values for resources are specified as keyword arguments.
02548         To get an overview about the allowed keyword arguments
02549         call the method without arguments.
02550         Valid resource names: background, bg, foreground, fg,
02551         selectbackground, selectforeground."""
02552         return self._configure(('itemconfigure', index), cnf, kw)
02553     itemconfig = itemconfigure
02554 
02555 class Menu(Widget):
02556     """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
02557     def __init__(self, master=None, cnf={}, **kw):
02558         """Construct menu widget with the parent MASTER.
02559 
02560         Valid resource names: activebackground, activeborderwidth,
02561         activeforeground, background, bd, bg, borderwidth, cursor,
02562         disabledforeground, fg, font, foreground, postcommand, relief,
02563         selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
02564         Widget.__init__(self, master, 'menu', cnf, kw)
02565     def tk_bindForTraversal(self):
02566         pass # obsolete since Tk 4.0
02567     def tk_mbPost(self):
02568         self.tk.call('tk_mbPost', self._w)
02569     def tk_mbUnpost(self):
02570         self.tk.call('tk_mbUnpost')
02571     def tk_traverseToMenu(self, char):
02572         self.tk.call('tk_traverseToMenu', self._w, char)
02573     def tk_traverseWithinMenu(self, char):
02574         self.tk.call('tk_traverseWithinMenu', self._w, char)
02575     def tk_getMenuButtons(self):
02576         return self.tk.call('tk_getMenuButtons', self._w)
02577     def tk_nextMenu(self, count):
02578         self.tk.call('tk_nextMenu', count)
02579     def tk_nextMenuEntry(self, count):
02580         self.tk.call('tk_nextMenuEntry', count)
02581     def tk_invokeMenu(self):
02582         self.tk.call('tk_invokeMenu', self._w)
02583     def tk_firstMenu(self):
02584         self.tk.call('tk_firstMenu', self._w)
02585     def tk_mbButtonDown(self):
02586         self.tk.call('tk_mbButtonDown', self._w)
02587     def tk_popup(self, x, y, entry=""):
02588         """Post the menu at position X,Y with entry ENTRY."""
02589         self.tk.call('tk_popup', self._w, x, y, entry)
02590     def activate(self, index):
02591         """Activate entry at INDEX."""
02592         self.tk.call(self._w, 'activate', index)
02593     def add(self, itemType, cnf={}, **kw):
02594         """Internal function."""
02595         self.tk.call((self._w, 'add', itemType) +
02596                  self._options(cnf, kw))
02597     def add_cascade(self, cnf={}, **kw):
02598         """Add hierarchical menu item."""
02599         self.add('cascade', cnf or kw)
02600     def add_checkbutton(self, cnf={}, **kw):
02601         """Add checkbutton menu item."""
02602         self.add('checkbutton', cnf or kw)
02603     def add_command(self, cnf={}, **kw):
02604         """Add command menu item."""
02605         self.add('command', cnf or kw)
02606     def add_radiobutton(self, cnf={}, **kw):
02607         """Addd radio menu item."""
02608         self.add('radiobutton', cnf or kw)
02609     def add_separator(self, cnf={}, **kw):
02610         """Add separator."""
02611         self.add('separator', cnf or kw)
02612     def insert(self, index, itemType, cnf={}, **kw):
02613         """Internal function."""
02614         self.tk.call((self._w, 'insert', index, itemType) +
02615                  self._options(cnf, kw))
02616     def insert_cascade(self, index, cnf={}, **kw):
02617         """Add hierarchical menu item at INDEX."""
02618         self.insert(index, 'cascade', cnf or kw)
02619     def insert_checkbutton(self, index, cnf={}, **kw):
02620         """Add checkbutton menu item at INDEX."""
02621         self.insert(index, 'checkbutton', cnf or kw)
02622     def insert_command(self, index, cnf={}, **kw):
02623         """Add command menu item at INDEX."""
02624         self.insert(index, 'command', cnf or kw)
02625     def insert_radiobutton(self, index, cnf={}, **kw):
02626         """Addd radio menu item at INDEX."""
02627         self.insert(index, 'radiobutton', cnf or kw)
02628     def insert_separator(self, index, cnf={}, **kw):
02629         """Add separator at INDEX."""
02630         self.insert(index, 'separator', cnf or kw)
02631     def delete(self, index1, index2=None):
02632         """Delete menu items between INDEX1 and INDEX2 (included)."""
02633         if index2 is None:
02634             index2 = index1
02635 
02636         num_index1, num_index2 = self.index(index1), self.index(index2)
02637         if (num_index1 is None) or (num_index2 is None):
02638             num_index1, num_index2 = 0, -1
02639 
02640         for i in range(num_index1, num_index2 + 1):
02641             if 'command' in self.entryconfig(i):
02642                 c = str(self.entrycget(i, 'command'))
02643                 if c:
02644                     self.deletecommand(c)
02645         self.tk.call(self._w, 'delete', index1, index2)
02646     def entrycget(self, index, option):
02647         """Return the resource value of an menu item for OPTION at INDEX."""
02648         return self.tk.call(self._w, 'entrycget', index, '-' + option)
02649     def entryconfigure(self, index, cnf=None, **kw):
02650         """Configure a menu item at INDEX."""
02651         return self._configure(('entryconfigure', index), cnf, kw)
02652     entryconfig = entryconfigure
02653     def index(self, index):
02654         """Return the index of a menu item identified by INDEX."""
02655         i = self.tk.call(self._w, 'index', index)
02656         if i == 'none': return None
02657         return getint(i)
02658     def invoke(self, index):
02659         """Invoke a menu item identified by INDEX and execute
02660         the associated command."""
02661         return self.tk.call(self._w, 'invoke', index)
02662     def post(self, x, y):
02663         """Display a menu at position X,Y."""
02664         self.tk.call(self._w, 'post', x, y)
02665     def type(self, index):
02666         """Return the type of the menu item at INDEX."""
02667         return self.tk.call(self._w, 'type', index)
02668     def unpost(self):
02669         """Unmap a menu."""
02670         self.tk.call(self._w, 'unpost')
02671     def yposition(self, index):
02672         """Return the y-position of the topmost pixel of the menu item at INDEX."""
02673         return getint(self.tk.call(
02674             self._w, 'yposition', index))
02675 
02676 class Menubutton(Widget):
02677     """Menubutton widget, obsolete since Tk8.0."""
02678     def __init__(self, master=None, cnf={}, **kw):
02679         Widget.__init__(self, master, 'menubutton', cnf, kw)
02680 
02681 class Message(Widget):
02682     """Message widget to display multiline text. Obsolete since Label does it too."""
02683     def __init__(self, master=None, cnf={}, **kw):
02684         Widget.__init__(self, master, 'message', cnf, kw)
02685 
02686 class Radiobutton(Widget):
02687     """Radiobutton widget which shows only one of several buttons in on-state."""
02688     def __init__(self, master=None, cnf={}, **kw):
02689         """Construct a radiobutton widget with the parent MASTER.
02690 
02691         Valid resource names: activebackground, activeforeground, anchor,
02692         background, bd, bg, bitmap, borderwidth, command, cursor,
02693         disabledforeground, fg, font, foreground, height,
02694         highlightbackground, highlightcolor, highlightthickness, image,
02695         indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
02696         state, takefocus, text, textvariable, underline, value, variable,
02697         width, wraplength."""
02698         Widget.__init__(self, master, 'radiobutton', cnf, kw)
02699     def deselect(self):
02700         """Put the button in off-state."""
02701 
02702         self.tk.call(self._w, 'deselect')
02703     def flash(self):
02704         """Flash the button."""
02705         self.tk.call(self._w, 'flash')
02706     def invoke(self):
02707         """Toggle the button and invoke a command if given as resource."""
02708         return self.tk.call(self._w, 'invoke')
02709     def select(self):
02710         """Put the button in on-state."""
02711         self.tk.call(self._w, 'select')
02712 
02713 class Scale(Widget):
02714     """Scale widget which can display a numerical scale."""
02715     def __init__(self, master=None, cnf={}, **kw):
02716         """Construct a scale widget with the parent MASTER.
02717 
02718         Valid resource names: activebackground, background, bigincrement, bd,
02719         bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
02720         highlightbackground, highlightcolor, highlightthickness, label,
02721         length, orient, relief, repeatdelay, repeatinterval, resolution,
02722         showvalue, sliderlength, sliderrelief, state, takefocus,
02723         tickinterval, to, troughcolor, variable, width."""
02724         Widget.__init__(self, master, 'scale', cnf, kw)
02725     def get(self):
02726         """Get the current value as integer or float."""
02727         value = self.tk.call(self._w, 'get')
02728         try:
02729             return getint(value)
02730         except ValueError:
02731             return getdouble(value)
02732     def set(self, value):
02733         """Set the value to VALUE."""
02734         self.tk.call(self._w, 'set', value)
02735     def coords(self, value=None):
02736         """Return a tuple (X,Y) of the point along the centerline of the
02737         trough that corresponds to VALUE or the current value if None is
02738         given."""
02739 
02740         return self._getints(self.tk.call(self._w, 'coords', value))
02741     def identify(self, x, y):
02742         """Return where the point X,Y lies. Valid return values are "slider",
02743         "though1" and "though2"."""
02744         return self.tk.call(self._w, 'identify', x, y)
02745 
02746 class Scrollbar(Widget):
02747     """Scrollbar widget which displays a slider at a certain position."""
02748     def __init__(self, master=None, cnf={}, **kw):
02749         """Construct a scrollbar widget with the parent MASTER.
02750 
02751         Valid resource names: activebackground, activerelief,
02752         background, bd, bg, borderwidth, command, cursor,
02753         elementborderwidth, highlightbackground,
02754         highlightcolor, highlightthickness, jump, orient,
02755         relief, repeatdelay, repeatinterval, takefocus,
02756         troughcolor, width."""
02757         Widget.__init__(self, master, 'scrollbar', cnf, kw)
02758     def activate(self, index):
02759         """Display the element at INDEX with activebackground and activerelief.
02760         INDEX can be "arrow1","slider" or "arrow2"."""
02761         self.tk.call(self._w, 'activate', index)
02762     def delta(self, deltax, deltay):
02763         """Return the fractional change of the scrollbar setting if it
02764         would be moved by DELTAX or DELTAY pixels."""
02765         return getdouble(
02766             self.tk.call(self._w, 'delta', deltax, deltay))
02767     def fraction(self, x, y):
02768         """Return the fractional value which corresponds to a slider
02769         position of X,Y."""
02770         return getdouble(self.tk.call(self._w, 'fraction', x, y))
02771     def identify(self, x, y):
02772         """Return the element under position X,Y as one of
02773         "arrow1","slider","arrow2" or ""."""
02774         return self.tk.call(self._w, 'identify', x, y)
02775     def get(self):
02776         """Return the current fractional values (upper and lower end)
02777         of the slider position."""
02778         return self._getdoubles(self.tk.call(self._w, 'get'))
02779     def set(self, *args):
02780         """Set the fractional values of the slider position (upper and
02781         lower ends as value between 0 and 1)."""
02782         self.tk.call((self._w, 'set') + args)
02783 
02784 
02785 
02786 class Text(Widget, XView, YView):
02787     """Text widget which can display text in various forms."""
02788     def __init__(self, master=None, cnf={}, **kw):
02789         """Construct a text widget with the parent MASTER.
02790 
02791         STANDARD OPTIONS
02792 
02793             background, borderwidth, cursor,
02794             exportselection, font, foreground,
02795             highlightbackground, highlightcolor,
02796             highlightthickness, insertbackground,
02797             insertborderwidth, insertofftime,
02798             insertontime, insertwidth, padx, pady,
02799             relief, selectbackground,
02800             selectborderwidth, selectforeground,
02801             setgrid, takefocus,
02802             xscrollcommand, yscrollcommand,
02803 
02804         WIDGET-SPECIFIC OPTIONS
02805 
02806             autoseparators, height, maxundo,
02807             spacing1, spacing2, spacing3,
02808             state, tabs, undo, width, wrap,
02809 
02810         """
02811         Widget.__init__(self, master, 'text', cnf, kw)
02812     def bbox(self, *args):
02813         """Return a tuple of (x,y,width,height) which gives the bounding
02814         box of the visible part of the character at the index in ARGS."""
02815         return self._getints(
02816             self.tk.call((self._w, 'bbox') + args)) or None
02817     def tk_textSelectTo(self, index):
02818         self.tk.call('tk_textSelectTo', self._w, index)
02819     def tk_textBackspace(self):
02820         self.tk.call('tk_textBackspace', self._w)
02821     def tk_textIndexCloser(self, a, b, c):
02822         self.tk.call('tk_textIndexCloser', self._w, a, b, c)
02823     def tk_textResetAnchor(self, index):
02824         self.tk.call('tk_textResetAnchor', self._w, index)
02825     def compare(self, index1, op, index2):
02826         """Return whether between index INDEX1 and index INDEX2 the
02827         relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
02828         return self.tk.getboolean(self.tk.call(
02829             self._w, 'compare', index1, op, index2))
02830     def debug(self, boolean=None):
02831         """Turn on the internal consistency checks of the B-Tree inside the text
02832         widget according to BOOLEAN."""
02833         return self.tk.getboolean(self.tk.call(
02834             self._w, 'debug', boolean))
02835     def delete(self, index1, index2=None):
02836         """Delete the characters between INDEX1 and INDEX2 (not included)."""
02837         self.tk.call(self._w, 'delete', index1, index2)
02838     def dlineinfo(self, index):
02839         """Return tuple (x,y,width,height,baseline) giving the bounding box
02840         and baseline position of the visible part of the line containing
02841         the character at INDEX."""
02842         return self._getints(self.tk.call(self._w, 'dlineinfo', index))
02843     def dump(self, index1, index2=None, command=None, **kw):
02844         """Return the contents of the widget between index1 and index2.
02845 
02846         The type of contents returned in filtered based on the keyword
02847         parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
02848         given and true, then the corresponding items are returned. The result
02849         is a list of triples of the form (key, value, index). If none of the
02850         keywords are true then 'all' is used by default.
02851 
02852         If the 'command' argument is given, it is called once for each element
02853         of the list of triples, with the values of each triple serving as the
02854         arguments to the function. In this case the list is not returned."""
02855         args = []
02856         func_name = None
02857         result = None
02858         if not command:
02859             # Never call the dump command without the -command flag, since the
02860             # output could involve Tcl quoting and would be a pain to parse
02861             # right. Instead just set the command to build a list of triples
02862             # as if we had done the parsing.
02863             result = []
02864             def append_triple(key, value, index, result=result):
02865                 result.append((key, value, index))
02866             command = append_triple
02867         try:
02868             if not isinstance(command, str):
02869                 func_name = command = self._register(command)
02870             args += ["-command", command]
02871             for key in kw:
02872                 if kw[key]: args.append("-" + key)
02873             args.append(index1)
02874             if index2:
02875                 args.append(index2)
02876             self.tk.call(self._w, "dump", *args)
02877             return result
02878         finally:
02879             if func_name:
02880                 self.deletecommand(func_name)
02881 
02882     ## new in tk8.4
02883     def edit(self, *args):
02884         """Internal method
02885 
02886         This method controls the undo mechanism and
02887         the modified flag. The exact behavior of the
02888         command depends on the option argument that
02889         follows the edit argument. The following forms
02890         of the command are currently supported:
02891 
02892         edit_modified, edit_redo, edit_reset, edit_separator
02893         and edit_undo
02894 
02895         """
02896         return self.tk.call(self._w, 'edit', *args)
02897 
02898     def edit_modified(self, arg=None):
02899         """Get or Set the modified flag
02900 
02901         If arg is not specified, returns the modified
02902         flag of the widget. The insert, delete, edit undo and
02903         edit redo commands or the user can set or clear the
02904         modified flag. If boolean is specified, sets the
02905         modified flag of the widget to arg.
02906         """
02907         return self.edit("modified", arg)
02908 
02909     def edit_redo(self):
02910         """Redo the last undone edit
02911 
02912         When the undo option is true, reapplies the last
02913         undone edits provided no other edits were done since
02914         then. Generates an error when the redo stack is empty.
02915         Does nothing when the undo option is false.
02916         """
02917         return self.edit("redo")
02918 
02919     def edit_reset(self):
02920         """Clears the undo and redo stacks
02921         """
02922         return self.edit("reset")
02923 
02924     def edit_separator(self):
02925         """Inserts a separator (boundary) on the undo stack.
02926 
02927         Does nothing when the undo option is false
02928         """
02929         return self.edit("separator")
02930 
02931     def edit_undo(self):
02932         """Undoes the last edit action
02933 
02934         If the undo option is true. An edit action is defined
02935         as all the insert and delete commands that are recorded
02936         on the undo stack in between two separators. Generates
02937         an error when the undo stack is empty. Does nothing
02938         when the undo option is false
02939         """
02940         return self.edit("undo")
02941 
02942     def get(self, index1, index2=None):
02943         """Return the text from INDEX1 to INDEX2 (not included)."""
02944         return self.tk.call(self._w, 'get', index1, index2)
02945     # (Image commands are new in 8.0)
02946     def image_cget(self, index, option):
02947         """Return the value of OPTION of an embedded image at INDEX."""
02948         if option[:1] != "-":
02949             option = "-" + option
02950         if option[-1:] == "_":
02951             option = option[:-1]
02952         return self.tk.call(self._w, "image", "cget", index, option)
02953     def image_configure(self, index, cnf=None, **kw):
02954         """Configure an embedded image at INDEX."""
02955         return self._configure(('image', 'configure', index), cnf, kw)
02956     def image_create(self, index, cnf={}, **kw):
02957         """Create an embedded image at INDEX."""
02958         return self.tk.call(
02959                  self._w, "image", "create", index,
02960                  *self._options(cnf, kw))
02961     def image_names(self):
02962         """Return all names of embedded images in this widget."""
02963         return self.tk.call(self._w, "image", "names")
02964     def index(self, index):
02965         """Return the index in the form line.char for INDEX."""
02966         return str(self.tk.call(self._w, 'index', index))
02967     def insert(self, index, chars, *args):
02968         """Insert CHARS before the characters at INDEX. An additional
02969         tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
02970         self.tk.call((self._w, 'insert', index, chars) + args)
02971     def mark_gravity(self, markName, direction=None):
02972         """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
02973         Return the current value if None is given for DIRECTION."""
02974         return self.tk.call(
02975             (self._w, 'mark', 'gravity', markName, direction))
02976     def mark_names(self):
02977         """Return all mark names."""
02978         return self.tk.splitlist(self.tk.call(
02979             self._w, 'mark', 'names'))
02980     def mark_set(self, markName, index):
02981         """Set mark MARKNAME before the character at INDEX."""
02982         self.tk.call(self._w, 'mark', 'set', markName, index)
02983     def mark_unset(self, *markNames):
02984         """Delete all marks in MARKNAMES."""
02985         self.tk.call((self._w, 'mark', 'unset') + markNames)
02986     def mark_next(self, index):
02987         """Return the name of the next mark after INDEX."""
02988         return self.tk.call(self._w, 'mark', 'next', index) or None
02989     def mark_previous(self, index):
02990         """Return the name of the previous mark before INDEX."""
02991         return self.tk.call(self._w, 'mark', 'previous', index) or None
02992     def scan_mark(self, x, y):
02993         """Remember the current X, Y coordinates."""
02994         self.tk.call(self._w, 'scan', 'mark', x, y)
02995     def scan_dragto(self, x, y):
02996         """Adjust the view of the text to 10 times the
02997         difference between X and Y and the coordinates given in
02998         scan_mark."""
02999         self.tk.call(self._w, 'scan', 'dragto', x, y)
03000     def search(self, pattern, index, stopindex=None,
03001            forwards=None, backwards=None, exact=None,
03002            regexp=None, nocase=None, count=None, elide=None):
03003         """Search PATTERN beginning from INDEX until STOPINDEX.
03004         Return the index of the first character of a match or an
03005         empty string."""
03006         args = [self._w, 'search']
03007         if forwards: args.append('-forwards')
03008         if backwards: args.append('-backwards')
03009         if exact: args.append('-exact')
03010         if regexp: args.append('-regexp')
03011         if nocase: args.append('-nocase')
03012         if elide: args.append('-elide')
03013         if count: args.append('-count'); args.append(count)
03014         if pattern and pattern[0] == '-': args.append('--')
03015         args.append(pattern)
03016         args.append(index)
03017         if stopindex: args.append(stopindex)
03018         return str(self.tk.call(tuple(args)))
03019     def see(self, index):
03020         """Scroll such that the character at INDEX is visible."""
03021         self.tk.call(self._w, 'see', index)
03022     def tag_add(self, tagName, index1, *args):
03023         """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
03024         Additional pairs of indices may follow in ARGS."""
03025         self.tk.call(
03026             (self._w, 'tag', 'add', tagName, index1) + args)
03027     def tag_unbind(self, tagName, sequence, funcid=None):
03028         """Unbind for all characters with TAGNAME for event SEQUENCE  the
03029         function identified with FUNCID."""
03030         self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
03031         if funcid:
03032             self.deletecommand(funcid)
03033     def tag_bind(self, tagName, sequence, func, add=None):
03034         """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
03035 
03036         An additional boolean parameter ADD specifies whether FUNC will be
03037         called additionally to the other bound function or whether it will
03038         replace the previous function. See bind for the return value."""
03039         return self._bind((self._w, 'tag', 'bind', tagName),
03040                   sequence, func, add)
03041     def tag_cget(self, tagName, option):
03042         """Return the value of OPTION for tag TAGNAME."""
03043         if option[:1] != '-':
03044             option = '-' + option
03045         if option[-1:] == '_':
03046             option = option[:-1]
03047         return self.tk.call(self._w, 'tag', 'cget', tagName, option)
03048     def tag_configure(self, tagName, cnf=None, **kw):
03049         """Configure a tag TAGNAME."""
03050         return self._configure(('tag', 'configure', tagName), cnf, kw)
03051     tag_config = tag_configure
03052     def tag_delete(self, *tagNames):
03053         """Delete all tags in TAGNAMES."""
03054         self.tk.call((self._w, 'tag', 'delete') + tagNames)
03055     def tag_lower(self, tagName, belowThis=None):
03056         """Change the priority of tag TAGNAME such that it is lower
03057         than the priority of BELOWTHIS."""
03058         self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
03059     def tag_names(self, index=None):
03060         """Return a list of all tag names."""
03061         return self.tk.splitlist(
03062             self.tk.call(self._w, 'tag', 'names', index))
03063     def tag_nextrange(self, tagName, index1, index2=None):
03064         """Return a list of start and end index for the first sequence of
03065         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
03066         The text is searched forward from INDEX1."""
03067         return self.tk.splitlist(self.tk.call(
03068             self._w, 'tag', 'nextrange', tagName, index1, index2))
03069     def tag_prevrange(self, tagName, index1, index2=None):
03070         """Return a list of start and end index for the first sequence of
03071         characters between INDEX1 and INDEX2 which all have tag TAGNAME.
03072         The text is searched backwards from INDEX1."""
03073         return self.tk.splitlist(self.tk.call(
03074             self._w, 'tag', 'prevrange', tagName, index1, index2))
03075     def tag_raise(self, tagName, aboveThis=None):
03076         """Change the priority of tag TAGNAME such that it is higher
03077         than the priority of ABOVETHIS."""
03078         self.tk.call(
03079             self._w, 'tag', 'raise', tagName, aboveThis)
03080     def tag_ranges(self, tagName):
03081         """Return a list of ranges of text which have tag TAGNAME."""
03082         return self.tk.splitlist(self.tk.call(
03083             self._w, 'tag', 'ranges', tagName))
03084     def tag_remove(self, tagName, index1, index2=None):
03085         """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
03086         self.tk.call(
03087             self._w, 'tag', 'remove', tagName, index1, index2)
03088     def window_cget(self, index, option):
03089         """Return the value of OPTION of an embedded window at INDEX."""
03090         if option[:1] != '-':
03091             option = '-' + option
03092         if option[-1:] == '_':
03093             option = option[:-1]
03094         return self.tk.call(self._w, 'window', 'cget', index, option)
03095     def window_configure(self, index, cnf=None, **kw):
03096         """Configure an embedded window at INDEX."""
03097         return self._configure(('window', 'configure', index), cnf, kw)
03098     window_config = window_configure
03099     def window_create(self, index, cnf={}, **kw):
03100         """Create a window at INDEX."""
03101         self.tk.call(
03102               (self._w, 'window', 'create', index)
03103               + self._options(cnf, kw))
03104     def window_names(self):
03105         """Return all names of embedded windows in this widget."""
03106         return self.tk.splitlist(
03107             self.tk.call(self._w, 'window', 'names'))
03108     def yview_pickplace(self, *what):
03109         """Obsolete function, use see."""
03110         self.tk.call((self._w, 'yview', '-pickplace') + what)
03111 
03112 
03113 class _setit:
03114     """Internal class. It wraps the command in the widget OptionMenu."""
03115     def __init__(self, var, value, callback=None):
03116         self.__value = value
03117         self.__var = var
03118         self.__callback = callback
03119     def __call__(self, *args):
03120         self.__var.set(self.__value)
03121         if self.__callback:
03122             self.__callback(self.__value, *args)
03123 
03124 class OptionMenu(Menubutton):
03125     """OptionMenu which allows the user to select a value from a menu."""
03126     def __init__(self, master, variable, value, *values, **kwargs):
03127         """Construct an optionmenu widget with the parent MASTER, with
03128         the resource textvariable set to VARIABLE, the initially selected
03129         value VALUE, the other menu values VALUES and an additional
03130         keyword argument command."""
03131         kw = {"borderwidth": 2, "textvariable": variable,
03132               "indicatoron": 1, "relief": RAISED, "anchor": "c",
03133               "highlightthickness": 2}
03134         Widget.__init__(self, master, "menubutton", kw)
03135         self.widgetName = 'tk_optionMenu'
03136         menu = self.__menu = Menu(self, name="menu", tearoff=0)
03137         self.menuname = menu._w
03138         # 'command' is the only supported keyword
03139         callback = kwargs.get('command')
03140         if 'command' in kwargs:
03141             del kwargs['command']
03142         if kwargs:
03143             raise TclError('unknown option -'+kwargs.keys()[0])
03144         menu.add_command(label=value,
03145                  command=_setit(variable, value, callback))
03146         for v in values:
03147             menu.add_command(label=v,
03148                      command=_setit(variable, v, callback))
03149         self["menu"] = menu
03150 
03151     def __getitem__(self, name):
03152         if name == 'menu':
03153             return self.__menu
03154         return Widget.__getitem__(self, name)
03155 
03156     def destroy(self):
03157         """Destroy this widget and the associated menu."""
03158         Menubutton.destroy(self)
03159         self.__menu = None
03160 
03161 class Image:
03162     """Base class for images."""
03163     _last_id = 0
03164     def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
03165         self.name = None
03166         if not master:
03167             master = _default_root
03168             if not master:
03169                 raise RuntimeError('Too early to create image')
03170         self.tk = master.tk
03171         if not name:
03172             Image._last_id += 1
03173             name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
03174             # The following is needed for systems where id(x)
03175             # can return a negative number, such as Linux/m68k:
03176             if name[0] == '-': name = '_' + name[1:]
03177         if kw and cnf: cnf = _cnfmerge((cnf, kw))
03178         elif kw: cnf = kw
03179         options = ()
03180         for k, v in cnf.items():
03181             if hasattr(v, '__call__'):
03182                 v = self._register(v)
03183             options = options + ('-'+k, v)
03184         self.tk.call(('image', 'create', imgtype, name,) + options)
03185         self.name = name
03186     def __str__(self): return self.name
03187     def __del__(self):
03188         if self.name:
03189             try:
03190                 self.tk.call('image', 'delete', self.name)
03191             except TclError:
03192                 # May happen if the root was destroyed
03193                 pass
03194     def __setitem__(self, key, value):
03195         self.tk.call(self.name, 'configure', '-'+key, value)
03196     def __getitem__(self, key):
03197         return self.tk.call(self.name, 'configure', '-'+key)
03198     def configure(self, **kw):
03199         """Configure the image."""
03200         res = ()
03201         for k, v in _cnfmerge(kw).items():
03202             if v is not None:
03203                 if k[-1] == '_': k = k[:-1]
03204                 if hasattr(v, '__call__'):
03205                     v = self._register(v)
03206                 res = res + ('-'+k, v)
03207         self.tk.call((self.name, 'config') + res)
03208     config = configure
03209     def height(self):
03210         """Return the height of the image."""
03211         return getint(
03212             self.tk.call('image', 'height', self.name))
03213     def type(self):
03214         """Return the type of the imgage, e.g. "photo" or "bitmap"."""
03215         return self.tk.call('image', 'type', self.name)
03216     def width(self):
03217         """Return the width of the image."""
03218         return getint(
03219             self.tk.call('image', 'width', self.name))
03220 
03221 class PhotoImage(Image):
03222     """Widget which can display colored images in GIF, PPM/PGM format."""
03223     def __init__(self, name=None, cnf={}, master=None, **kw):
03224         """Create an image with NAME.
03225 
03226         Valid resource names: data, format, file, gamma, height, palette,
03227         width."""
03228         Image.__init__(self, 'photo', name, cnf, master, **kw)
03229     def blank(self):
03230         """Display a transparent image."""
03231         self.tk.call(self.name, 'blank')
03232     def cget(self, option):
03233         """Return the value of OPTION."""
03234         return self.tk.call(self.name, 'cget', '-' + option)
03235     # XXX config
03236     def __getitem__(self, key):
03237         return self.tk.call(self.name, 'cget', '-' + key)
03238     # XXX copy -from, -to, ...?
03239     def copy(self):
03240         """Return a new PhotoImage with the same image as this widget."""
03241         destImage = PhotoImage()
03242         self.tk.call(destImage, 'copy', self.name)
03243         return destImage
03244     def zoom(self,x,y=''):
03245         """Return a new PhotoImage with the same image as this widget
03246         but zoom it with X and Y."""
03247         destImage = PhotoImage()
03248         if y=='': y=x
03249         self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
03250         return destImage
03251     def subsample(self,x,y=''):
03252         """Return a new PhotoImage based on the same image as this widget
03253         but use only every Xth or Yth pixel."""
03254         destImage = PhotoImage()
03255         if y=='': y=x
03256         self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
03257         return destImage
03258     def get(self, x, y):
03259         """Return the color (red, green, blue) of the pixel at X,Y."""
03260         return self.tk.call(self.name, 'get', x, y)
03261     def put(self, data, to=None):
03262         """Put row formatted colors to image starting from
03263         position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
03264         args = (self.name, 'put', data)
03265         if to:
03266             if to[0] == '-to':
03267                 to = to[1:]
03268             args = args + ('-to',) + tuple(to)
03269         self.tk.call(args)
03270     # XXX read
03271     def write(self, filename, format=None, from_coords=None):
03272         """Write image to file FILENAME in FORMAT starting from
03273         position FROM_COORDS."""
03274         args = (self.name, 'write', filename)
03275         if format:
03276             args = args + ('-format', format)
03277         if from_coords:
03278             args = args + ('-from',) + tuple(from_coords)
03279         self.tk.call(args)
03280 
03281 class BitmapImage(Image):
03282     """Widget which can display a bitmap."""
03283     def __init__(self, name=None, cnf={}, master=None, **kw):
03284         """Create a bitmap with NAME.
03285 
03286         Valid resource names: background, data, file, foreground, maskdata, maskfile."""
03287         Image.__init__(self, 'bitmap', name, cnf, master, **kw)
03288 
03289 def image_names(): return _default_root.tk.call('image', 'names')
03290 def image_types(): return _default_root.tk.call('image', 'types')
03291 
03292 
03293 class Spinbox(Widget, XView):
03294     """spinbox widget."""
03295     def __init__(self, master=None, cnf={}, **kw):
03296         """Construct a spinbox widget with the parent MASTER.
03297 
03298         STANDARD OPTIONS
03299 
03300             activebackground, background, borderwidth,
03301             cursor, exportselection, font, foreground,
03302             highlightbackground, highlightcolor,
03303             highlightthickness, insertbackground,
03304             insertborderwidth, insertofftime,
03305             insertontime, insertwidth, justify, relief,
03306             repeatdelay, repeatinterval,
03307             selectbackground, selectborderwidth
03308             selectforeground, takefocus, textvariable
03309             xscrollcommand.
03310 
03311         WIDGET-SPECIFIC OPTIONS
03312 
03313             buttonbackground, buttoncursor,
03314             buttondownrelief, buttonuprelief,
03315             command, disabledbackground,
03316             disabledforeground, format, from,
03317             invalidcommand, increment,
03318             readonlybackground, state, to,
03319             validate, validatecommand values,
03320             width, wrap,
03321         """
03322         Widget.__init__(self, master, 'spinbox', cnf, kw)
03323 
03324     def bbox(self, index):
03325         """Return a tuple of X1,Y1,X2,Y2 coordinates for a
03326         rectangle which encloses the character given by index.
03327 
03328         The first two elements of the list give the x and y
03329         coordinates of the upper-left corner of the screen
03330         area covered by the character (in pixels relative
03331         to the widget) and the last two elements give the
03332         width and height of the character, in pixels. The
03333         bounding box may refer to a region outside the
03334         visible area of the window.
03335         """
03336         return self.tk.call(self._w, 'bbox', index)
03337 
03338     def delete(self, first, last=None):
03339         """Delete one or more elements of the spinbox.
03340 
03341         First is the index of the first character to delete,
03342         and last is the index of the character just after
03343         the last one to delete. If last isn't specified it
03344         defaults to first+1, i.e. a single character is
03345         deleted.  This command returns an empty string.
03346         """
03347         return self.tk.call(self._w, 'delete', first, last)
03348 
03349     def get(self):
03350         """Returns the spinbox's string"""
03351         return self.tk.call(self._w, 'get')
03352 
03353     def icursor(self, index):
03354         """Alter the position of the insertion cursor.
03355 
03356         The insertion cursor will be displayed just before
03357         the character given by index. Returns an empty string
03358         """
03359         return self.tk.call(self._w, 'icursor', index)
03360 
03361     def identify(self, x, y):
03362         """Returns the name of the widget at position x, y
03363 
03364         Return value is one of: none, buttondown, buttonup, entry
03365         """
03366         return self.tk.call(self._w, 'identify', x, y)
03367 
03368     def index(self, index):
03369         """Returns the numerical index corresponding to index
03370         """
03371         return self.tk.call(self._w, 'index', index)
03372 
03373     def insert(self, index, s):
03374         """Insert string s at index
03375 
03376          Returns an empty string.
03377         """
03378         return self.tk.call(self._w, 'insert', index, s)
03379 
03380     def invoke(self, element):
03381         """Causes the specified element to be invoked
03382 
03383         The element could be buttondown or buttonup
03384         triggering the action associated with it.
03385         """
03386         return self.tk.call(self._w, 'invoke', element)
03387 
03388     def scan(self, *args):
03389         """Internal function."""
03390         return self._getints(
03391             self.tk.call((self._w, 'scan') + args)) or ()
03392 
03393     def scan_mark(self, x):
03394         """Records x and the current view in the spinbox window;
03395 
03396         used in conjunction with later scan dragto commands.
03397         Typically this command is associated with a mouse button
03398         press in the widget. It returns an empty string.
03399         """
03400         return self.scan("mark", x)
03401 
03402     def scan_dragto(self, x):
03403         """Compute the difference between the given x argument
03404         and the x argument to the last scan mark command
03405 
03406         It then adjusts the view left or right by 10 times the
03407         difference in x-coordinates. This command is typically
03408         associated with mouse motion events in the widget, to
03409         produce the effect of dragging the spinbox at high speed
03410         through the window. The return value is an empty string.
03411         """
03412         return self.scan("dragto", x)
03413 
03414     def selection(self, *args):
03415         """Internal function."""
03416         return self._getints(
03417             self.tk.call((self._w, 'selection') + args)) or ()
03418 
03419     def selection_adjust(self, index):
03420         """Locate the end of the selection nearest to the character
03421         given by index,
03422 
03423         Then adjust that end of the selection to be at index
03424         (i.e including but not going beyond index). The other
03425         end of the selection is made the anchor point for future
03426         select to commands. If the selection isn't currently in
03427         the spinbox, then a new selection is created to include
03428         the characters between index and the most recent selection
03429         anchor point, inclusive. Returns an empty string.
03430         """
03431         return self.selection("adjust", index)
03432 
03433     def selection_clear(self):
03434         """Clear the selection
03435 
03436         If the selection isn't in this widget then the
03437         command has no effect. Returns an empty string.
03438         """
03439         return self.selection("clear")
03440 
03441     def selection_element(self, element=None):
03442         """Sets or gets the currently selected element.
03443 
03444         If a spinbutton element is specified, it will be
03445         displayed depressed
03446         """
03447         return self.selection("element", element)
03448 
03449 ###########################################################################
03450 
03451 class LabelFrame(Widget):
03452     """labelframe widget."""
03453     def __init__(self, master=None, cnf={}, **kw):
03454         """Construct a labelframe widget with the parent MASTER.
03455 
03456         STANDARD OPTIONS
03457 
03458             borderwidth, cursor, font, foreground,
03459             highlightbackground, highlightcolor,
03460             highlightthickness, padx, pady, relief,
03461             takefocus, text
03462 
03463         WIDGET-SPECIFIC OPTIONS
03464 
03465             background, class, colormap, container,
03466             height, labelanchor, labelwidget,
03467             visual, width
03468         """
03469         Widget.__init__(self, master, 'labelframe', cnf, kw)
03470 
03471 ########################################################################
03472 
03473 class PanedWindow(Widget):
03474     """panedwindow widget."""
03475     def __init__(self, master=None, cnf={}, **kw):
03476         """Construct a panedwindow widget with the parent MASTER.
03477 
03478         STANDARD OPTIONS
03479 
03480             background, borderwidth, cursor, height,
03481             orient, relief, width
03482 
03483         WIDGET-SPECIFIC OPTIONS
03484 
03485             handlepad, handlesize, opaqueresize,
03486             sashcursor, sashpad, sashrelief,
03487             sashwidth, showhandle,
03488         """
03489         Widget.__init__(self, master, 'panedwindow', cnf, kw)
03490 
03491     def add(self, child, **kw):
03492         """Add a child widget to the panedwindow in a new pane.
03493 
03494         The child argument is the name of the child widget
03495         followed by pairs of arguments that specify how to
03496         manage the windows. The possible options and values
03497         are the ones accepted by the paneconfigure method.
03498         """
03499         self.tk.call((self._w, 'add', child) + self._options(kw))
03500 
03501     def remove(self, child):
03502         """Remove the pane containing child from the panedwindow
03503 
03504         All geometry management options for child will be forgotten.
03505         """
03506         self.tk.call(self._w, 'forget', child)
03507     forget=remove
03508 
03509     def identify(self, x, y):
03510         """Identify the panedwindow component at point x, y
03511 
03512         If the point is over a sash or a sash handle, the result
03513         is a two element list containing the index of the sash or
03514         handle, and a word indicating whether it is over a sash
03515         or a handle, such as {0 sash} or {2 handle}. If the point
03516         is over any other part of the panedwindow, the result is
03517         an empty list.
03518         """
03519         return self.tk.call(self._w, 'identify', x, y)
03520 
03521     def proxy(self, *args):
03522         """Internal function."""
03523         return self._getints(
03524             self.tk.call((self._w, 'proxy') + args)) or ()
03525 
03526     def proxy_coord(self):
03527         """Return the x and y pair of the most recent proxy location
03528         """
03529         return self.proxy("coord")
03530 
03531     def proxy_forget(self):
03532         """Remove the proxy from the display.
03533         """
03534         return self.proxy("forget")
03535 
03536     def proxy_place(self, x, y):
03537         """Place the proxy at the given x and y coordinates.
03538         """
03539         return self.proxy("place", x, y)
03540 
03541     def sash(self, *args):
03542         """Internal function."""
03543         return self._getints(
03544             self.tk.call((self._w, 'sash') + args)) or ()
03545 
03546     def sash_coord(self, index):
03547         """Return the current x and y pair for the sash given by index.
03548 
03549         Index must be an integer between 0 and 1 less than the
03550         number of panes in the panedwindow. The coordinates given are
03551         those of the top left corner of the region containing the sash.
03552         pathName sash dragto index x y This command computes the
03553         difference between the given coordinates and the coordinates
03554         given to the last sash coord command for the given sash. It then
03555         moves that sash the computed difference. The return value is the
03556         empty string.
03557         """
03558         return self.sash("coord", index)
03559 
03560     def sash_mark(self, index):
03561         """Records x and y for the sash given by index;
03562 
03563         Used in conjunction with later dragto commands to move the sash.
03564         """
03565         return self.sash("mark", index)
03566 
03567     def sash_place(self, index, x, y):
03568         """Place the sash given by index at the given coordinates
03569         """
03570         return self.sash("place", index, x, y)
03571 
03572     def panecget(self, child, option):
03573         """Query a management option for window.
03574 
03575         Option may be any value allowed by the paneconfigure subcommand
03576         """
03577         return self.tk.call(
03578             (self._w, 'panecget') + (child, '-'+option))
03579 
03580     def paneconfigure(self, tagOrId, cnf=None, **kw):
03581         """Query or modify the management options for window.
03582 
03583         If no option is specified, returns a list describing all
03584         of the available options for pathName.  If option is
03585         specified with no value, then the command returns a list
03586         describing the one named option (this list will be identical
03587         to the corresponding sublist of the value returned if no
03588         option is specified). If one or more option-value pairs are
03589         specified, then the command modifies the given widget
03590         option(s) to have the given value(s); in this case the
03591         command returns an empty string. The following options
03592         are supported:
03593 
03594         after window
03595             Insert the window after the window specified. window
03596             should be the name of a window already managed by pathName.
03597         before window
03598             Insert the window before the window specified. window
03599             should be the name of a window already managed by pathName.
03600         height size
03601             Specify a height for the window. The height will be the
03602             outer dimension of the window including its border, if
03603             any. If size is an empty string, or if -height is not
03604             specified, then the height requested internally by the
03605             window will be used initially; the height may later be
03606             adjusted by the movement of sashes in the panedwindow.
03607             Size may be any value accepted by Tk_GetPixels.
03608         minsize n
03609             Specifies that the size of the window cannot be made
03610             less than n. This constraint only affects the size of
03611             the widget in the paned dimension -- the x dimension
03612             for horizontal panedwindows, the y dimension for
03613             vertical panedwindows. May be any value accepted by
03614             Tk_GetPixels.
03615         padx n
03616             Specifies a non-negative value indicating how much
03617             extra space to leave on each side of the window in
03618             the X-direction. The value may have any of the forms
03619             accepted by Tk_GetPixels.
03620         pady n
03621             Specifies a non-negative value indicating how much
03622             extra space to leave on each side of the window in
03623             the Y-direction. The value may have any of the forms
03624             accepted by Tk_GetPixels.
03625         sticky style
03626             If a window's pane is larger than the requested
03627             dimensions of the window, this option may be used
03628             to position (or stretch) the window within its pane.
03629             Style is a string that contains zero or more of the
03630             characters n, s, e or w. The string can optionally
03631             contains spaces or commas, but they are ignored. Each
03632             letter refers to a side (north, south, east, or west)
03633             that the window will "stick" to. If both n and s
03634             (or e and w) are specified, the window will be
03635             stretched to fill the entire height (or width) of
03636             its cavity.
03637         width size
03638             Specify a width for the window. The width will be
03639             the outer dimension of the window including its
03640             border, if any. If size is an empty string, or
03641             if -width is not specified, then the width requested
03642             internally by the window will be used initially; the
03643             width may later be adjusted by the movement of sashes
03644             in the panedwindow. Size may be any value accepted by
03645             Tk_GetPixels.
03646 
03647         """
03648         if cnf is None and not kw:
03649             cnf = {}
03650             for x in self.tk.split(
03651                 self.tk.call(self._w,
03652                          'paneconfigure', tagOrId)):
03653                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
03654             return cnf
03655         if isinstance(cnf, str) and not kw:
03656             x = self.tk.split(self.tk.call(
03657                 self._w, 'paneconfigure', tagOrId, '-'+cnf))
03658             return (x[0][1:],) + x[1:]
03659         self.tk.call((self._w, 'paneconfigure', tagOrId) +
03660                  self._options(cnf, kw))
03661     paneconfig = paneconfigure
03662 
03663     def panes(self):
03664         """Returns an ordered list of the child panes."""
03665         return self.tk.call(self._w, 'panes')
03666 
03667 ######################################################################
03668 # Extensions:
03669 
03670 class Studbutton(Button):
03671     def __init__(self, master=None, cnf={}, **kw):
03672         Widget.__init__(self, master, 'studbutton', cnf, kw)
03673         self.bind('<Any-Enter>',       self.tkButtonEnter)
03674         self.bind('<Any-Leave>',       self.tkButtonLeave)
03675         self.bind('<1>',               self.tkButtonDown)
03676         self.bind('<ButtonRelease-1>', self.tkButtonUp)
03677 
03678 class Tributton(Button):
03679     def __init__(self, master=None, cnf={}, **kw):
03680         Widget.__init__(self, master, 'tributton', cnf, kw)
03681         self.bind('<Any-Enter>',       self.tkButtonEnter)
03682         self.bind('<Any-Leave>',       self.tkButtonLeave)
03683         self.bind('<1>',               self.tkButtonDown)
03684         self.bind('<ButtonRelease-1>', self.tkButtonUp)
03685         self['fg']               = self['bg']
03686         self['activebackground'] = self['bg']
03687 
03688 ######################################################################
03689 # Test:
03690 
03691 def _test():
03692     root = Tk()
03693     text = "This is Tcl/Tk version %s" % TclVersion
03694     if TclVersion >= 8.1:
03695         text += "\nThis should be a cedilla: \xe7"
03696     label = Label(root, text=text)
03697     label.pack()
03698     test = Button(root, text="Click me!",
03699               command=lambda root=root: root.test.configure(
03700                   text="[%s]" % root.test['text']))
03701     test.pack()
03702     root.test = test
03703     quit = Button(root, text="QUIT", command=root.destroy)
03704     quit.pack()
03705     # The following three commands are needed so the window pops
03706     # up on top on Windows...
03707     root.iconify()
03708     root.update()
03709     root.deiconify()
03710     root.mainloop()
03711 
03712 if __name__ == '__main__':
03713     _test()