PageRenderTime 13ms CodeModel.GetById 741ms app.highlight 1506ms RepoModel.GetById 166ms app.codeStats 2ms

/Lib/lib-tk/Tkinter.py

http://unladen-swallow.googlecode.com/
Python | 3774 lines | 3749 code | 0 blank | 25 comment | 6 complexity | 77f6245e4d47ba42fe974c0a4dbee464 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1"""Wrapper functions for Tcl/Tk.
   2
   3Tkinter provides classes which allow the display, positioning and
   4control of widgets. Toplevel widgets are Tk and Toplevel. Other
   5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
   6Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
   7LabelFrame and PanedWindow.
   8
   9Properties of the widgets are specified with keyword arguments.
  10Keyword arguments have the same name as the corresponding resource
  11under Tk.
  12
  13Widgets are positioned with one of the geometry managers Place, Pack
  14or Grid. These managers can be called with methods place, pack, grid
  15available in every Widget.
  16
  17Actions are bound to events by resources (e.g. keyword argument
  18command) or with the method bind.
  19
  20Example (Hello, World):
  21import Tkinter
  22from Tkconstants import *
  23tk = Tkinter.Tk()
  24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
  25frame.pack(fill=BOTH,expand=1)
  26label = Tkinter.Label(frame, text="Hello, World")
  27label.pack(fill=X, expand=1)
  28button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
  29button.pack(side=BOTTOM)
  30tk.mainloop()
  31"""
  32
  33__version__ = "$Revision: 73770 $"
  34
  35import sys
  36if sys.platform == "win32":
  37    # Attempt to configure Tcl/Tk without requiring PATH
  38    import FixTk
  39import _tkinter # If this fails your Python may not be configured for Tk
  40tkinter = _tkinter # b/w compat for export
  41TclError = _tkinter.TclError
  42from types import *
  43from Tkconstants import *
  44
  45wantobjects = 1
  46
  47TkVersion = float(_tkinter.TK_VERSION)
  48TclVersion = float(_tkinter.TCL_VERSION)
  49
  50READABLE = _tkinter.READABLE
  51WRITABLE = _tkinter.WRITABLE
  52EXCEPTION = _tkinter.EXCEPTION
  53
  54# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  55try: _tkinter.createfilehandler
  56except AttributeError: _tkinter.createfilehandler = None
  57try: _tkinter.deletefilehandler
  58except AttributeError: _tkinter.deletefilehandler = None
  59
  60
  61def _flatten(tuple):
  62    """Internal function."""
  63    res = ()
  64    for item in tuple:
  65        if type(item) in (TupleType, ListType):
  66            res = res + _flatten(item)
  67        elif item is not None:
  68            res = res + (item,)
  69    return res
  70
  71try: _flatten = _tkinter._flatten
  72except AttributeError: pass
  73
  74def _cnfmerge(cnfs):
  75    """Internal function."""
  76    if type(cnfs) is DictionaryType:
  77        return cnfs
  78    elif type(cnfs) in (NoneType, StringType):
  79        return cnfs
  80    else:
  81        cnf = {}
  82        for c in _flatten(cnfs):
  83            try:
  84                cnf.update(c)
  85            except (AttributeError, TypeError), msg:
  86                print "_cnfmerge: fallback due to:", msg
  87                for k, v in c.items():
  88                    cnf[k] = v
  89        return cnf
  90
  91try: _cnfmerge = _tkinter._cnfmerge
  92except AttributeError: pass
  93
  94class Event:
  95    """Container for the properties of an event.
  96
  97    Instances of this type are generated if one of the following events occurs:
  98
  99    KeyPress, KeyRelease - for keyboard events
 100    ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
 101    Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
 102    Colormap, Gravity, Reparent, Property, Destroy, Activate,
 103    Deactivate - for window events.
 104
 105    If a callback function for one of these events is registered
 106    using bind, bind_all, bind_class, or tag_bind, the callback is
 107    called with an Event as first argument. It will have the
 108    following attributes (in braces are the event types for which
 109    the attribute is valid):
 110
 111        serial - serial number of event
 112    num - mouse button pressed (ButtonPress, ButtonRelease)
 113    focus - whether the window has the focus (Enter, Leave)
 114    height - height of the exposed window (Configure, Expose)
 115    width - width of the exposed window (Configure, Expose)
 116    keycode - keycode of the pressed key (KeyPress, KeyRelease)
 117    state - state of the event as a number (ButtonPress, ButtonRelease,
 118                            Enter, KeyPress, KeyRelease,
 119                            Leave, Motion)
 120    state - state as a string (Visibility)
 121    time - when the event occurred
 122    x - x-position of the mouse
 123    y - y-position of the mouse
 124    x_root - x-position of the mouse on the screen
 125             (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
 126    y_root - y-position of the mouse on the screen
 127             (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
 128    char - pressed character (KeyPress, KeyRelease)
 129    send_event - see X/Windows documentation
 130    keysym - keysym of the event as a string (KeyPress, KeyRelease)
 131    keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
 132    type - type of the event as a number
 133    widget - widget in which the event occurred
 134    delta - delta of wheel movement (MouseWheel)
 135    """
 136    pass
 137
 138_support_default_root = 1
 139_default_root = None
 140
 141def NoDefaultRoot():
 142    """Inhibit setting of default root window.
 143
 144    Call this function to inhibit that the first instance of
 145    Tk is used for windows without an explicit parent window.
 146    """
 147    global _support_default_root
 148    _support_default_root = 0
 149    global _default_root
 150    _default_root = None
 151    del _default_root
 152
 153def _tkerror(err):
 154    """Internal function."""
 155    pass
 156
 157def _exit(code='0'):
 158    """Internal function. Calling it will throw the exception SystemExit."""
 159    raise SystemExit, code
 160
 161_varnum = 0
 162class Variable:
 163    """Class to define value holders for e.g. buttons.
 164
 165    Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
 166    that constrain the type of the value returned from get()."""
 167    _default = ""
 168    def __init__(self, master=None, value=None, name=None):
 169        """Construct a variable
 170
 171        MASTER can be given as master widget.
 172        VALUE is an optional value (defaults to "")
 173        NAME is an optional Tcl name (defaults to PY_VARnum).
 174
 175        If NAME matches an existing variable and VALUE is omitted
 176        then the existing value is retained.
 177        """
 178        global _varnum
 179        if not master:
 180            master = _default_root
 181        self._master = master
 182        self._tk = master.tk
 183        if name:
 184            self._name = name
 185        else:
 186            self._name = 'PY_VAR' + repr(_varnum)
 187            _varnum += 1
 188        if value is not None:
 189            self.set(value)
 190        elif not self._tk.call("info", "exists", self._name):
 191            self.set(self._default)
 192    def __del__(self):
 193        """Unset the variable in Tcl."""
 194        self._tk.globalunsetvar(self._name)
 195    def __str__(self):
 196        """Return the name of the variable in Tcl."""
 197        return self._name
 198    def set(self, value):
 199        """Set the variable to VALUE."""
 200        return self._tk.globalsetvar(self._name, value)
 201    def get(self):
 202        """Return value of variable."""
 203        return self._tk.globalgetvar(self._name)
 204    def trace_variable(self, mode, callback):
 205        """Define a trace callback for the variable.
 206
 207        MODE is one of "r", "w", "u" for read, write, undefine.
 208        CALLBACK must be a function which is called when
 209        the variable is read, written or undefined.
 210
 211        Return the name of the callback.
 212        """
 213        cbname = self._master._register(callback)
 214        self._tk.call("trace", "variable", self._name, mode, cbname)
 215        return cbname
 216    trace = trace_variable
 217    def trace_vdelete(self, mode, cbname):
 218        """Delete the trace callback for a variable.
 219
 220        MODE is one of "r", "w", "u" for read, write, undefine.
 221        CBNAME is the name of the callback returned from trace_variable or trace.
 222        """
 223        self._tk.call("trace", "vdelete", self._name, mode, cbname)
 224        self._master.deletecommand(cbname)
 225    def trace_vinfo(self):
 226        """Return all trace callback information."""
 227        return map(self._tk.split, self._tk.splitlist(
 228            self._tk.call("trace", "vinfo", self._name)))
 229    def __eq__(self, other):
 230        """Comparison for equality (==).
 231
 232        Note: if the Variable's master matters to behavior
 233        also compare self._master == other._master
 234        """
 235        return self.__class__.__name__ == other.__class__.__name__ \
 236            and self._name == other._name
 237
 238class StringVar(Variable):
 239    """Value holder for strings variables."""
 240    _default = ""
 241    def __init__(self, master=None, value=None, name=None):
 242        """Construct a string variable.
 243
 244        MASTER can be given as master widget.
 245        VALUE is an optional value (defaults to "")
 246        NAME is an optional Tcl name (defaults to PY_VARnum).
 247
 248        If NAME matches an existing variable and VALUE is omitted
 249        then the existing value is retained.
 250        """
 251        Variable.__init__(self, master, value, name)
 252
 253    def get(self):
 254        """Return value of variable as string."""
 255        value = self._tk.globalgetvar(self._name)
 256        if isinstance(value, basestring):
 257            return value
 258        return str(value)
 259
 260class IntVar(Variable):
 261    """Value holder for integer variables."""
 262    _default = 0
 263    def __init__(self, master=None, value=None, name=None):
 264        """Construct an integer variable.
 265
 266        MASTER can be given as master widget.
 267        VALUE is an optional value (defaults to 0)
 268        NAME is an optional Tcl name (defaults to PY_VARnum).
 269
 270        If NAME matches an existing variable and VALUE is omitted
 271        then the existing value is retained.
 272        """
 273        Variable.__init__(self, master, value, name)
 274
 275    def set(self, value):
 276        """Set the variable to value, converting booleans to integers."""
 277        if isinstance(value, bool):
 278            value = int(value)
 279        return Variable.set(self, value)
 280
 281    def get(self):
 282        """Return the value of the variable as an integer."""
 283        return getint(self._tk.globalgetvar(self._name))
 284
 285class DoubleVar(Variable):
 286    """Value holder for float variables."""
 287    _default = 0.0
 288    def __init__(self, master=None, value=None, name=None):
 289        """Construct a float variable.
 290
 291        MASTER can be given as master widget.
 292        VALUE is an optional value (defaults to 0.0)
 293        NAME is an optional Tcl name (defaults to PY_VARnum).
 294
 295        If NAME matches an existing variable and VALUE is omitted
 296        then the existing value is retained.
 297        """
 298        Variable.__init__(self, master, value, name)
 299
 300    def get(self):
 301        """Return the value of the variable as a float."""
 302        return getdouble(self._tk.globalgetvar(self._name))
 303
 304class BooleanVar(Variable):
 305    """Value holder for boolean variables."""
 306    _default = False
 307    def __init__(self, master=None, value=None, name=None):
 308        """Construct a boolean variable.
 309
 310        MASTER can be given as master widget.
 311        VALUE is an optional value (defaults to False)
 312        NAME is an optional Tcl name (defaults to PY_VARnum).
 313
 314        If NAME matches an existing variable and VALUE is omitted
 315        then the existing value is retained.
 316        """
 317        Variable.__init__(self, master, value, name)
 318
 319    def get(self):
 320        """Return the value of the variable as a bool."""
 321        return self._tk.getboolean(self._tk.globalgetvar(self._name))
 322
 323def mainloop(n=0):
 324    """Run the main loop of Tcl."""
 325    _default_root.tk.mainloop(n)
 326
 327getint = int
 328
 329getdouble = float
 330
 331def getboolean(s):
 332    """Convert true and false to integer values 1 and 0."""
 333    return _default_root.tk.getboolean(s)
 334
 335# Methods defined on both toplevel and interior widgets
 336class Misc:
 337    """Internal class.
 338
 339    Base class which defines methods common for interior widgets."""
 340
 341    # XXX font command?
 342    _tclCommands = None
 343    def destroy(self):
 344        """Internal function.
 345
 346        Delete all Tcl commands created for
 347        this widget in the Tcl interpreter."""
 348        if self._tclCommands is not None:
 349            for name in self._tclCommands:
 350                #print '- Tkinter: deleted command', name
 351                self.tk.deletecommand(name)
 352            self._tclCommands = None
 353    def deletecommand(self, name):
 354        """Internal function.
 355
 356        Delete the Tcl command provided in NAME."""
 357        #print '- Tkinter: deleted command', name
 358        self.tk.deletecommand(name)
 359        try:
 360            self._tclCommands.remove(name)
 361        except ValueError:
 362            pass
 363    def tk_strictMotif(self, boolean=None):
 364        """Set Tcl internal variable, whether the look and feel
 365        should adhere to Motif.
 366
 367        A parameter of 1 means adhere to Motif (e.g. no color
 368        change if mouse passes over slider).
 369        Returns the set value."""
 370        return self.tk.getboolean(self.tk.call(
 371            'set', 'tk_strictMotif', boolean))
 372    def tk_bisque(self):
 373        """Change the color scheme to light brown as used in Tk 3.6 and before."""
 374        self.tk.call('tk_bisque')
 375    def tk_setPalette(self, *args, **kw):
 376        """Set a new color scheme for all widget elements.
 377
 378        A single color as argument will cause that all colors of Tk
 379        widget elements are derived from this.
 380        Alternatively several keyword parameters and its associated
 381        colors can be given. The following keywords are valid:
 382        activeBackground, foreground, selectColor,
 383        activeForeground, highlightBackground, selectBackground,
 384        background, highlightColor, selectForeground,
 385        disabledForeground, insertBackground, troughColor."""
 386        self.tk.call(('tk_setPalette',)
 387              + _flatten(args) + _flatten(kw.items()))
 388    def tk_menuBar(self, *args):
 389        """Do not use. Needed in Tk 3.6 and earlier."""
 390        pass # obsolete since Tk 4.0
 391    def wait_variable(self, name='PY_VAR'):
 392        """Wait until the variable is modified.
 393
 394        A parameter of type IntVar, StringVar, DoubleVar or
 395        BooleanVar must be given."""
 396        self.tk.call('tkwait', 'variable', name)
 397    waitvar = wait_variable # XXX b/w compat
 398    def wait_window(self, window=None):
 399        """Wait until a WIDGET is destroyed.
 400
 401        If no parameter is given self is used."""
 402        if window is None:
 403            window = self
 404        self.tk.call('tkwait', 'window', window._w)
 405    def wait_visibility(self, window=None):
 406        """Wait until the visibility of a WIDGET changes
 407        (e.g. it appears).
 408
 409        If no parameter is given self is used."""
 410        if window is None:
 411            window = self
 412        self.tk.call('tkwait', 'visibility', window._w)
 413    def setvar(self, name='PY_VAR', value='1'):
 414        """Set Tcl variable NAME to VALUE."""
 415        self.tk.setvar(name, value)
 416    def getvar(self, name='PY_VAR'):
 417        """Return value of Tcl variable NAME."""
 418        return self.tk.getvar(name)
 419    getint = int
 420    getdouble = float
 421    def getboolean(self, s):
 422        """Return a boolean value for Tcl boolean values true and false given as parameter."""
 423        return self.tk.getboolean(s)
 424    def focus_set(self):
 425        """Direct input focus to this widget.
 426
 427        If the application currently does not have the focus
 428        this widget will get the focus if the application gets
 429        the focus through the window manager."""
 430        self.tk.call('focus', self._w)
 431    focus = focus_set # XXX b/w compat?
 432    def focus_force(self):
 433        """Direct input focus to this widget even if the
 434        application does not have the focus. Use with
 435        caution!"""
 436        self.tk.call('focus', '-force', self._w)
 437    def focus_get(self):
 438        """Return the widget which has currently the focus in the
 439        application.
 440
 441        Use focus_displayof to allow working with several
 442        displays. Return None if application does not have
 443        the focus."""
 444        name = self.tk.call('focus')
 445        if name == 'none' or not name: return None
 446        return self._nametowidget(name)
 447    def focus_displayof(self):
 448        """Return the widget which has currently the focus on the
 449        display where this widget is located.
 450
 451        Return None if the application does not have the focus."""
 452        name = self.tk.call('focus', '-displayof', self._w)
 453        if name == 'none' or not name: return None
 454        return self._nametowidget(name)
 455    def focus_lastfor(self):
 456        """Return the widget which would have the focus if top level
 457        for this widget gets the focus from the window manager."""
 458        name = self.tk.call('focus', '-lastfor', self._w)
 459        if name == 'none' or not name: return None
 460        return self._nametowidget(name)
 461    def tk_focusFollowsMouse(self):
 462        """The widget under mouse will get automatically focus. Can not
 463        be disabled easily."""
 464        self.tk.call('tk_focusFollowsMouse')
 465    def tk_focusNext(self):
 466        """Return the next widget in the focus order which follows
 467        widget which has currently the focus.
 468
 469        The focus order first goes to the next child, then to
 470        the children of the child recursively and then to the
 471        next sibling which is higher in the stacking order.  A
 472        widget is omitted if it has the takefocus resource set
 473        to 0."""
 474        name = self.tk.call('tk_focusNext', self._w)
 475        if not name: return None
 476        return self._nametowidget(name)
 477    def tk_focusPrev(self):
 478        """Return previous widget in the focus order. See tk_focusNext for details."""
 479        name = self.tk.call('tk_focusPrev', self._w)
 480        if not name: return None
 481        return self._nametowidget(name)
 482    def after(self, ms, func=None, *args):
 483        """Call function once after given time.
 484
 485        MS specifies the time in milliseconds. FUNC gives the
 486        function which shall be called. Additional parameters
 487        are given as parameters to the function call.  Return
 488        identifier to cancel scheduling with after_cancel."""
 489        if not func:
 490            # I'd rather use time.sleep(ms*0.001)
 491            self.tk.call('after', ms)
 492        else:
 493            def callit():
 494                try:
 495                    func(*args)
 496                finally:
 497                    try:
 498                        self.deletecommand(name)
 499                    except TclError:
 500                        pass
 501            name = self._register(callit)
 502            return self.tk.call('after', ms, name)
 503    def after_idle(self, func, *args):
 504        """Call FUNC once if the Tcl main loop has no event to
 505        process.
 506
 507        Return an identifier to cancel the scheduling with
 508        after_cancel."""
 509        return self.after('idle', func, *args)
 510    def after_cancel(self, id):
 511        """Cancel scheduling of function identified with ID.
 512
 513        Identifier returned by after or after_idle must be
 514        given as first parameter."""
 515        try:
 516            data = self.tk.call('after', 'info', id)
 517            # In Tk 8.3, splitlist returns: (script, type)
 518            # In Tk 8.4, splitlist may return (script, type) or (script,)
 519            script = self.tk.splitlist(data)[0]
 520            self.deletecommand(script)
 521        except TclError:
 522            pass
 523        self.tk.call('after', 'cancel', id)
 524    def bell(self, displayof=0):
 525        """Ring a display's bell."""
 526        self.tk.call(('bell',) + self._displayof(displayof))
 527
 528    # Clipboard handling:
 529    def clipboard_get(self, **kw):
 530        """Retrieve data from the clipboard on window's display.
 531
 532        The window keyword defaults to the root window of the Tkinter
 533        application.
 534
 535        The type keyword specifies the form in which the data is
 536        to be returned and should be an atom name such as STRING
 537        or FILE_NAME.  Type defaults to STRING.
 538
 539        This command is equivalent to:
 540
 541        selection_get(CLIPBOARD)
 542        """
 543        return self.tk.call(('clipboard', 'get') + self._options(kw))
 544
 545    def clipboard_clear(self, **kw):
 546        """Clear the data in the Tk clipboard.
 547
 548        A widget specified for the optional displayof keyword
 549        argument specifies the target display."""
 550        if not kw.has_key('displayof'): kw['displayof'] = self._w
 551        self.tk.call(('clipboard', 'clear') + self._options(kw))
 552    def clipboard_append(self, string, **kw):
 553        """Append STRING to the Tk clipboard.
 554
 555        A widget specified at the optional displayof keyword
 556        argument specifies the target display. The clipboard
 557        can be retrieved with selection_get."""
 558        if not kw.has_key('displayof'): kw['displayof'] = self._w
 559        self.tk.call(('clipboard', 'append') + self._options(kw)
 560              + ('--', string))
 561    # XXX grab current w/o window argument
 562    def grab_current(self):
 563        """Return widget which has currently the grab in this application
 564        or None."""
 565        name = self.tk.call('grab', 'current', self._w)
 566        if not name: return None
 567        return self._nametowidget(name)
 568    def grab_release(self):
 569        """Release grab for this widget if currently set."""
 570        self.tk.call('grab', 'release', self._w)
 571    def grab_set(self):
 572        """Set grab for this widget.
 573
 574        A grab directs all events to this and descendant
 575        widgets in the application."""
 576        self.tk.call('grab', 'set', self._w)
 577    def grab_set_global(self):
 578        """Set global grab for this widget.
 579
 580        A global grab directs all events to this and
 581        descendant widgets on the display. Use with caution -
 582        other applications do not get events anymore."""
 583        self.tk.call('grab', 'set', '-global', self._w)
 584    def grab_status(self):
 585        """Return None, "local" or "global" if this widget has
 586        no, a local or a global grab."""
 587        status = self.tk.call('grab', 'status', self._w)
 588        if status == 'none': status = None
 589        return status
 590    def option_add(self, pattern, value, priority = None):
 591        """Set a VALUE (second parameter) for an option
 592        PATTERN (first parameter).
 593
 594        An optional third parameter gives the numeric priority
 595        (defaults to 80)."""
 596        self.tk.call('option', 'add', pattern, value, priority)
 597    def option_clear(self):
 598        """Clear the option database.
 599
 600        It will be reloaded if option_add is called."""
 601        self.tk.call('option', 'clear')
 602    def option_get(self, name, className):
 603        """Return the value for an option NAME for this widget
 604        with CLASSNAME.
 605
 606        Values with higher priority override lower values."""
 607        return self.tk.call('option', 'get', self._w, name, className)
 608    def option_readfile(self, fileName, priority = None):
 609        """Read file FILENAME into the option database.
 610
 611        An optional second parameter gives the numeric
 612        priority."""
 613        self.tk.call('option', 'readfile', fileName, priority)
 614    def selection_clear(self, **kw):
 615        """Clear the current X selection."""
 616        if not kw.has_key('displayof'): kw['displayof'] = self._w
 617        self.tk.call(('selection', 'clear') + self._options(kw))
 618    def selection_get(self, **kw):
 619        """Return the contents of the current X selection.
 620
 621        A keyword parameter selection specifies the name of
 622        the selection and defaults to PRIMARY.  A keyword
 623        parameter displayof specifies a widget on the display
 624        to use."""
 625        if not kw.has_key('displayof'): kw['displayof'] = self._w
 626        return self.tk.call(('selection', 'get') + self._options(kw))
 627    def selection_handle(self, command, **kw):
 628        """Specify a function COMMAND to call if the X
 629        selection owned by this widget is queried by another
 630        application.
 631
 632        This function must return the contents of the
 633        selection. The function will be called with the
 634        arguments OFFSET and LENGTH which allows the chunking
 635        of very long selections. The following keyword
 636        parameters can be provided:
 637        selection - name of the selection (default PRIMARY),
 638        type - type of the selection (e.g. STRING, FILE_NAME)."""
 639        name = self._register(command)
 640        self.tk.call(('selection', 'handle') + self._options(kw)
 641              + (self._w, name))
 642    def selection_own(self, **kw):
 643        """Become owner of X selection.
 644
 645        A keyword parameter selection specifies the name of
 646        the selection (default PRIMARY)."""
 647        self.tk.call(('selection', 'own') +
 648                 self._options(kw) + (self._w,))
 649    def selection_own_get(self, **kw):
 650        """Return owner of X selection.
 651
 652        The following keyword parameter can
 653        be provided:
 654        selection - name of the selection (default PRIMARY),
 655        type - type of the selection (e.g. STRING, FILE_NAME)."""
 656        if not kw.has_key('displayof'): kw['displayof'] = self._w
 657        name = self.tk.call(('selection', 'own') + self._options(kw))
 658        if not name: return None
 659        return self._nametowidget(name)
 660    def send(self, interp, cmd, *args):
 661        """Send Tcl command CMD to different interpreter INTERP to be executed."""
 662        return self.tk.call(('send', interp, cmd) + args)
 663    def lower(self, belowThis=None):
 664        """Lower this widget in the stacking order."""
 665        self.tk.call('lower', self._w, belowThis)
 666    def tkraise(self, aboveThis=None):
 667        """Raise this widget in the stacking order."""
 668        self.tk.call('raise', self._w, aboveThis)
 669    lift = tkraise
 670    def colormodel(self, value=None):
 671        """Useless. Not implemented in Tk."""
 672        return self.tk.call('tk', 'colormodel', self._w, value)
 673    def winfo_atom(self, name, displayof=0):
 674        """Return integer which represents atom NAME."""
 675        args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
 676        return getint(self.tk.call(args))
 677    def winfo_atomname(self, id, displayof=0):
 678        """Return name of atom with identifier ID."""
 679        args = ('winfo', 'atomname') \
 680               + self._displayof(displayof) + (id,)
 681        return self.tk.call(args)
 682    def winfo_cells(self):
 683        """Return number of cells in the colormap for this widget."""
 684        return getint(
 685            self.tk.call('winfo', 'cells', self._w))
 686    def winfo_children(self):
 687        """Return a list of all widgets which are children of this widget."""
 688        result = []
 689        for child in self.tk.splitlist(
 690            self.tk.call('winfo', 'children', self._w)):
 691            try:
 692                # Tcl sometimes returns extra windows, e.g. for
 693                # menus; those need to be skipped
 694                result.append(self._nametowidget(child))
 695            except KeyError:
 696                pass
 697        return result
 698
 699    def winfo_class(self):
 700        """Return window class name of this widget."""
 701        return self.tk.call('winfo', 'class', self._w)
 702    def winfo_colormapfull(self):
 703        """Return true if at the last color request the colormap was full."""
 704        return self.tk.getboolean(
 705            self.tk.call('winfo', 'colormapfull', self._w))
 706    def winfo_containing(self, rootX, rootY, displayof=0):
 707        """Return the widget which is at the root coordinates ROOTX, ROOTY."""
 708        args = ('winfo', 'containing') \
 709               + self._displayof(displayof) + (rootX, rootY)
 710        name = self.tk.call(args)
 711        if not name: return None
 712        return self._nametowidget(name)
 713    def winfo_depth(self):
 714        """Return the number of bits per pixel."""
 715        return getint(self.tk.call('winfo', 'depth', self._w))
 716    def winfo_exists(self):
 717        """Return true if this widget exists."""
 718        return getint(
 719            self.tk.call('winfo', 'exists', self._w))
 720    def winfo_fpixels(self, number):
 721        """Return the number of pixels for the given distance NUMBER
 722        (e.g. "3c") as float."""
 723        return getdouble(self.tk.call(
 724            'winfo', 'fpixels', self._w, number))
 725    def winfo_geometry(self):
 726        """Return geometry string for this widget in the form "widthxheight+X+Y"."""
 727        return self.tk.call('winfo', 'geometry', self._w)
 728    def winfo_height(self):
 729        """Return height of this widget."""
 730        return getint(
 731            self.tk.call('winfo', 'height', self._w))
 732    def winfo_id(self):
 733        """Return identifier ID for this widget."""
 734        return self.tk.getint(
 735            self.tk.call('winfo', 'id', self._w))
 736    def winfo_interps(self, displayof=0):
 737        """Return the name of all Tcl interpreters for this display."""
 738        args = ('winfo', 'interps') + self._displayof(displayof)
 739        return self.tk.splitlist(self.tk.call(args))
 740    def winfo_ismapped(self):
 741        """Return true if this widget is mapped."""
 742        return getint(
 743            self.tk.call('winfo', 'ismapped', self._w))
 744    def winfo_manager(self):
 745        """Return the window mananger name for this widget."""
 746        return self.tk.call('winfo', 'manager', self._w)
 747    def winfo_name(self):
 748        """Return the name of this widget."""
 749        return self.tk.call('winfo', 'name', self._w)
 750    def winfo_parent(self):
 751        """Return the name of the parent of this widget."""
 752        return self.tk.call('winfo', 'parent', self._w)
 753    def winfo_pathname(self, id, displayof=0):
 754        """Return the pathname of the widget given by ID."""
 755        args = ('winfo', 'pathname') \
 756               + self._displayof(displayof) + (id,)
 757        return self.tk.call(args)
 758    def winfo_pixels(self, number):
 759        """Rounded integer value of winfo_fpixels."""
 760        return getint(
 761            self.tk.call('winfo', 'pixels', self._w, number))
 762    def winfo_pointerx(self):
 763        """Return the x coordinate of the pointer on the root window."""
 764        return getint(
 765            self.tk.call('winfo', 'pointerx', self._w))
 766    def winfo_pointerxy(self):
 767        """Return a tuple of x and y coordinates of the pointer on the root window."""
 768        return self._getints(
 769            self.tk.call('winfo', 'pointerxy', self._w))
 770    def winfo_pointery(self):
 771        """Return the y coordinate of the pointer on the root window."""
 772        return getint(
 773            self.tk.call('winfo', 'pointery', self._w))
 774    def winfo_reqheight(self):
 775        """Return requested height of this widget."""
 776        return getint(
 777            self.tk.call('winfo', 'reqheight', self._w))
 778    def winfo_reqwidth(self):
 779        """Return requested width of this widget."""
 780        return getint(
 781            self.tk.call('winfo', 'reqwidth', self._w))
 782    def winfo_rgb(self, color):
 783        """Return tuple of decimal values for red, green, blue for
 784        COLOR in this widget."""
 785        return self._getints(
 786            self.tk.call('winfo', 'rgb', self._w, color))
 787    def winfo_rootx(self):
 788        """Return x coordinate of upper left corner of this widget on the
 789        root window."""
 790        return getint(
 791            self.tk.call('winfo', 'rootx', self._w))
 792    def winfo_rooty(self):
 793        """Return y coordinate of upper left corner of this widget on the
 794        root window."""
 795        return getint(
 796            self.tk.call('winfo', 'rooty', self._w))
 797    def winfo_screen(self):
 798        """Return the screen name of this widget."""
 799        return self.tk.call('winfo', 'screen', self._w)
 800    def winfo_screencells(self):
 801        """Return the number of the cells in the colormap of the screen
 802        of this widget."""
 803        return getint(
 804            self.tk.call('winfo', 'screencells', self._w))
 805    def winfo_screendepth(self):
 806        """Return the number of bits per pixel of the root window of the
 807        screen of this widget."""
 808        return getint(
 809            self.tk.call('winfo', 'screendepth', self._w))
 810    def winfo_screenheight(self):
 811        """Return the number of pixels of the height of the screen of this widget
 812        in pixel."""
 813        return getint(
 814            self.tk.call('winfo', 'screenheight', self._w))
 815    def winfo_screenmmheight(self):
 816        """Return the number of pixels of the height of the screen of
 817        this widget in mm."""
 818        return getint(
 819            self.tk.call('winfo', 'screenmmheight', self._w))
 820    def winfo_screenmmwidth(self):
 821        """Return the number of pixels of the width of the screen of
 822        this widget in mm."""
 823        return getint(
 824            self.tk.call('winfo', 'screenmmwidth', self._w))
 825    def winfo_screenvisual(self):
 826        """Return one of the strings directcolor, grayscale, pseudocolor,
 827        staticcolor, staticgray, or truecolor for the default
 828        colormodel of this screen."""
 829        return self.tk.call('winfo', 'screenvisual', self._w)
 830    def winfo_screenwidth(self):
 831        """Return the number of pixels of the width of the screen of
 832        this widget in pixel."""
 833        return getint(
 834            self.tk.call('winfo', 'screenwidth', self._w))
 835    def winfo_server(self):
 836        """Return information of the X-Server of the screen of this widget in
 837        the form "XmajorRminor vendor vendorVersion"."""
 838        return self.tk.call('winfo', 'server', self._w)
 839    def winfo_toplevel(self):
 840        """Return the toplevel widget of this widget."""
 841        return self._nametowidget(self.tk.call(
 842            'winfo', 'toplevel', self._w))
 843    def winfo_viewable(self):
 844        """Return true if the widget and all its higher ancestors are mapped."""
 845        return getint(
 846            self.tk.call('winfo', 'viewable', self._w))
 847    def winfo_visual(self):
 848        """Return one of the strings directcolor, grayscale, pseudocolor,
 849        staticcolor, staticgray, or truecolor for the
 850        colormodel of this widget."""
 851        return self.tk.call('winfo', 'visual', self._w)
 852    def winfo_visualid(self):
 853        """Return the X identifier for the visual for this widget."""
 854        return self.tk.call('winfo', 'visualid', self._w)
 855    def winfo_visualsavailable(self, includeids=0):
 856        """Return a list of all visuals available for the screen
 857        of this widget.
 858
 859        Each item in the list consists of a visual name (see winfo_visual), a
 860        depth and if INCLUDEIDS=1 is given also the X identifier."""
 861        data = self.tk.split(
 862            self.tk.call('winfo', 'visualsavailable', self._w,
 863                     includeids and 'includeids' or None))
 864        if type(data) is StringType:
 865            data = [self.tk.split(data)]
 866        return map(self.__winfo_parseitem, data)
 867    def __winfo_parseitem(self, t):
 868        """Internal function."""
 869        return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
 870    def __winfo_getint(self, x):
 871        """Internal function."""
 872        return int(x, 0)
 873    def winfo_vrootheight(self):
 874        """Return the height of the virtual root window associated with this
 875        widget in pixels. If there is no virtual root window return the
 876        height of the screen."""
 877        return getint(
 878            self.tk.call('winfo', 'vrootheight', self._w))
 879    def winfo_vrootwidth(self):
 880        """Return the width of the virtual root window associated with this
 881        widget in pixel. If there is no virtual root window return the
 882        width of the screen."""
 883        return getint(
 884            self.tk.call('winfo', 'vrootwidth', self._w))
 885    def winfo_vrootx(self):
 886        """Return the x offset of the virtual root relative to the root
 887        window of the screen of this widget."""
 888        return getint(
 889            self.tk.call('winfo', 'vrootx', self._w))
 890    def winfo_vrooty(self):
 891        """Return the y offset of the virtual root relative to the root
 892        window of the screen of this widget."""
 893        return getint(
 894            self.tk.call('winfo', 'vrooty', self._w))
 895    def winfo_width(self):
 896        """Return the width of this widget."""
 897        return getint(
 898            self.tk.call('winfo', 'width', self._w))
 899    def winfo_x(self):
 900        """Return the x coordinate of the upper left corner of this widget
 901        in the parent."""
 902        return getint(
 903            self.tk.call('winfo', 'x', self._w))
 904    def winfo_y(self):
 905        """Return the y coordinate of the upper left corner of this widget
 906        in the parent."""
 907        return getint(
 908            self.tk.call('winfo', 'y', self._w))
 909    def update(self):
 910        """Enter event loop until all pending events have been processed by Tcl."""
 911        self.tk.call('update')
 912    def update_idletasks(self):
 913        """Enter event loop until all idle callbacks have been called. This
 914        will update the display of windows but not process events caused by
 915        the user."""
 916        self.tk.call('update', 'idletasks')
 917    def bindtags(self, tagList=None):
 918        """Set or get the list of bindtags for this widget.
 919
 920        With no argument return the list of all bindtags associated with
 921        this widget. With a list of strings as argument the bindtags are
 922        set to this list. The bindtags determine in which order events are
 923        processed (see bind)."""
 924        if tagList is None:
 925            return self.tk.splitlist(
 926                self.tk.call('bindtags', self._w))
 927        else:
 928            self.tk.call('bindtags', self._w, tagList)
 929    def _bind(self, what, sequence, func, add, needcleanup=1):
 930        """Internal function."""
 931        if type(func) is StringType:
 932            self.tk.call(what + (sequence, func))
 933        elif func:
 934            funcid = self._register(func, self._substitute,
 935                        needcleanup)
 936            cmd = ('%sif {"[%s %s]" == "break"} break\n'
 937                   %
 938                   (add and '+' or '',
 939                funcid, self._subst_format_str))
 940            self.tk.call(what + (sequence, cmd))
 941            return funcid
 942        elif sequence:
 943            return self.tk.call(what + (sequence,))
 944        else:
 945            return self.tk.splitlist(self.tk.call(what))
 946    def bind(self, sequence=None, func=None, add=None):
 947        """Bind to this widget at event SEQUENCE a call to function FUNC.
 948
 949        SEQUENCE is a string of concatenated event
 950        patterns. An event pattern is of the form
 951        <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
 952        of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
 953        Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
 954        B3, Alt, Button4, B4, Double, Button5, B5 Triple,
 955        Mod1, M1. TYPE is one of Activate, Enter, Map,
 956        ButtonPress, Button, Expose, Motion, ButtonRelease
 957        FocusIn, MouseWheel, Circulate, FocusOut, Property,
 958        Colormap, Gravity Reparent, Configure, KeyPress, Key,
 959        Unmap, Deactivate, KeyRelease Visibility, Destroy,
 960        Leave and DETAIL is the button number for ButtonPress,
 961        ButtonRelease and DETAIL is the Keysym for KeyPress and
 962        KeyRelease. Examples are
 963        <Control-Button-1> for pressing Control and mouse button 1 or
 964        <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
 965        An event pattern can also be a virtual event of the form
 966        <<AString>> where AString can be arbitrary. This
 967        event can be generated by event_generate.
 968        If events are concatenated they must appear shortly
 969        after each other.
 970
 971        FUNC will be called if the event sequence occurs with an
 972        instance of Event as argument. If the return value of FUNC is
 973        "break" no further bound function is invoked.
 974
 975        An additional boolean parameter ADD specifies whether FUNC will
 976        be called additionally to the other bound function or whether
 977        it will replace the previous function.
 978
 979        Bind will return an identifier to allow deletion of the bound function with
 980        unbind without memory leak.
 981
 982        If FUNC or SEQUENCE is omitted the bound function or list
 983        of bound events are returned."""
 984
 985        return self._bind(('bind', self._w), sequence, func, add)
 986    def unbind(self, sequence, funcid=None):
 987        """Unbind for this widget for event SEQUENCE  the
 988        function identified with FUNCID."""
 989        self.tk.call('bind', self._w, sequence, '')
 990        if funcid:
 991            self.deletecommand(funcid)
 992    def bind_all(self, sequence=None, func=None, add=None):
 993        """Bind to all widgets at an event SEQUENCE a call to function FUNC.
 994        An additional boolean parameter ADD specifies whether FUNC will
 995        be called additionally to the other bound function or whether
 996        it will replace the previous function. See bind for the return value."""
 997        return self._bind(('bind', 'all'), sequence, func, add, 0)
 998    def unbind_all(self, sequence):
 999        """Unbind for all widgets for event SEQUENCE all functions."""
1000        self.tk.call('bind', 'all' , sequence, '')
1001    def bind_class(self, className, sequence=None, func=None, add=None):
1002
1003        """Bind to widgets with bindtag CLASSNAME at event
1004        SEQUENCE a call of function FUNC. An additional
1005        boolean parameter ADD specifies whether FUNC will be
1006        called additionally to the other bound function or
1007        whether it will replace the previous function. See bind for
1008        the return value."""
1009
1010        return self._bind(('bind', className), sequence, func, add, 0)
1011    def unbind_class(self, className, sequence):
1012        """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1013        all functions."""
1014        self.tk.call('bind', className , sequence, '')
1015    def mainloop(self, n=0):
1016        """Call the mainloop of Tk."""
1017        self.tk.mainloop(n)
1018    def quit(self):
1019        """Quit the Tcl interpreter. All widgets will be destroyed."""
1020        self.tk.quit()
1021    def _getints(self, string):
1022        """Internal function."""
1023        if string:
1024            return tuple(map(getint, self.tk.splitlist(string)))
1025    def _getdoubles(self, string):
1026        """Internal function."""
1027        if string:
1028            return tuple(map(getdouble, self.tk.splitlist(string)))
1029    def _getboolean(self, string):
1030        """Internal function."""
1031        if string:
1032            return self.tk.getboolean(string)
1033    def _displayof(self, displayof):
1034        """Internal function."""
1035        if displayof:
1036            return ('-displayof', displayof)
1037        if displayof is None:
1038            return ('-displayof', self._w)
1039        return ()
1040    def _options(self, cnf, kw = None):
1041        """Internal function."""
1042        if kw:
1043            cnf = _cnfmerge((cnf, kw))
1044        else:
1045            cnf = _cnfmerge(cnf)
1046        res = ()
1047        for k, v in cnf.items():
1048            if v is not None:
1049                if k[-1] == '_': k = k[:-1]
1050                if callable(v):
1051                    v = self._register(v)
1052                elif isinstance(v, (tuple, list)):
1053                    nv = []
1054                    for item in v:
1055                        if not isinstance(item, (basestring, int)):
1056                            break
1057                        elif isinstance(item, int):
1058                            nv.append('%d' % item)
1059                        else:
1060                            # format it to proper Tcl code if it contains space
1061                            nv.append(('{%s}' if ' ' in item else '%s') % item)
1062                    else:
1063                        v = ' '.join(nv)
1064                res = res + ('-'+k, v)
1065        return res
1066    def nametowidget(self, name):
1067        """Return the Tkinter instance of a widget identified by
1068        its Tcl name NAME."""
1069        name = str(name).split('.')
1070        w = self
1071
1072        if not name[0]:
1073            w = w._root()
1074            name = name[1:]
1075
1076        for n in name:
1077            if not n:
1078                break
1079            w = w.children[n]
1080
1081        return w
1082    _nametowidget = nametowidget
1083    def _register(self, func, subst=None, needcleanup=1):
1084        """Return a newly created Tcl function. If this
1085        function is called, the Python function FUNC will
1086        be executed. An optional function SUBST can
1087        be given which will be executed before FUNC."""
1088        f = CallWrapper(func, subst, self).__call__
1089        name = repr(id(f))
1090        try:
1091            func = func.im_func
1092        except AttributeError:
1093            pass
1094        try:
1095            name = name + func.__name__
1096        except AttributeError:
1097            pass
1098        self.tk.createcommand(name, f)
1099        if needcleanup:
1100            if self._tclCommands is None:
1101                self._tclCommands = []
1102            self._tclCommands.append(name)
1103        return name
1104    register = _register
1105    def _root(self):
1106        """Internal function."""
1107        w = self
1108        while w.master: w = w.master
1109        return w
1110    _subst_format = ('%#', '%b', '%f', '%h', '%k',
1111             '%s', '%t', '%w', '%x', '%y',
1112             '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1113    _subst_format_str = " ".join(_subst_format)
1114    def _substitute(self, *args):
1115        """Internal function."""
1116        if len(args) != len(self._subst_format): return args
1117        getboolean = self.tk.getboolean
1118
1119        getint = int
1120        def getint_event(s):
1121            """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1122            try:
1123                return int(s)
1124            except ValueError:
1125                return s
1126
1127        nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1128        # Missing: (a, c, d, m, o, v, B, R)
1129        e = Event()
1130        # serial field: valid vor all events
1131        # number of button: ButtonPress and ButtonRelease events only
1132        # height field: Configure, ConfigureRequest, Create,
1133        # ResizeRequest, and Expose events only
1134        # keycode field: KeyPress and KeyRelease events only
1135        # time field: "valid for events that contain a time field"
1136        # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1137        # and Expose events only
1138        # x field: "valid for events that contain a x field"
1139        # y field: "valid for events that contain a y field"
1140        # keysym as decimal: KeyPress and KeyRelease events only
1141        # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1142        # KeyRelease,and Motion events
1143        e.serial = getint(nsign)
1144        e.num = getint_event(b)
1145        try: e.focus = getboolean(f)
1146        except TclError: pass
1147        e.height = getint_event(h)
1148        e.keycode = getint_event(k)
1149        e.state = getint_event(s)
1150        e.time = getint_event(t)
1151        e.width = getint_event(w)
1152        e.x = getint_event(x)
1153        e.y = getint_event(y)
1154        e.char = A
1155        try: e.send_event = getboolean(E)
1156        except TclError: pass
1157        e.keysym = K
1158        e.keysym_num = getint_event(N)
1159        e.type = T
1160        try:
1161            e.widget = self._nametowidget(W)
1162        except KeyError:
1163            e.widget = W
1164        e.x_root = getint_event(X)
1165        e.y_root = getint_event(Y)
1166        try:
1167            e.delta = getint(D)
1168        except ValueError:
1169            e.delta = 0
1170        return (e,)
1171    def _report_exception(self):
1172        """Internal function."""
1173        import sys
1174        exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1175        root = self._root()
1176        root.report_callback_exception(exc, val, tb)
1177    def _configure(self, cmd, cnf, kw):
1178        """Internal function."""
1179        if kw:
1180            cnf = _cnfmerge((cnf, kw))
1181        elif cnf:
1182            cnf = _cnfmerge(cnf)
1183        if cnf is None:
1184            cnf = {}
1185            for x in self.tk.split(
1186                    self.tk.call(_flatten((self._w, cmd)))):
1187                cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1188            return cnf
1189        if type(cnf) is StringType:
1190            x = self.tk.split(
1191                    self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1192            return (x[0][1:],) + x[1:]
1193        self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1194    # These used to be defined in Widget:
1195    def configure(self, cnf=None, **kw):
1196        """Configure resources of a widget.
1197
1198        The values for resources are specified as keyword
1199        arguments. To get an overview about
1200        the allowed keyword arguments call the method keys.
1201        """
1202        return self._configure('configure', cnf, kw)
1203    config = configure
1204    def cget(self, key):
1205        """Return the resource value for a KEY given as string."""
1206        return self.tk.call(self._w, 'cget', '-' + key)
1207    __getitem__ = cget
1208    def __setitem__(self, key, value):
1209        self.configure({key: value})
1210    def __contains__(self, key):
1211        raise TypeError("Tkinter objects don't support 'in' tests.")
1212    def keys(self):
1213        """Return a list of all resource names of this widget."""
1214        return map(lambda x: x[0][1:],
1215               self.tk.split(self.tk.call(self._w, 'configure')))
1216    def __str__(self):
1217        """Return the window path name of this widget."""
1218        return self._w
1219    # Pack methods that apply to the master
1220    _noarg_ = ['_noarg_']
1221    def pack_propagate(self, flag=_noarg_):
1222        """Set or get the status for propagation of geometry information.
1223
1224        A boolean argument specifies whether the geometry information
1225        of the slaves will determine the size of this widget. If no argument
1226        is given the current setting will be returned.
1227        """
1228        if flag is Misc._noarg_:
1229            return self._getboolean(self.tk.call(
1230                'pack', 'propagate', self._w))
1231        else:
1232            self.tk.call('pack', 'propagate', self._w, flag)
1233    propagate = pack_propagate
1234    def pack_slaves(self):
1235        """Return a list of all slaves of this widget
1236        in its packing order."""
1237        return map(self._nametowidget,
1238               self.tk.splitlist(
1239                   self.tk.call('pack', 'slaves', self._w)))
1240    slaves = pack_slaves
1241    # Place method that applies to the master
1242    def place_slaves(self):
1243        """Return a list of all slaves of this widget
1244        in its packing order."""
1245        return map(self._nametowidget,
1246               self.tk.splitlist(
1247                   self.tk.call(
1248                       'place', 'slaves', self._w)))
1249    # Grid methods that apply to the master
1250    def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1251        """Return a tuple of integer coordinates for the bounding
1252        box of…

Large files files are truncated, but you can click here to view the full file