3759 lines · 154.2 KB · Python
RawDownload
"""Wrapper functions for Tcl/Tk. Tkinter provides classes which allow the display, positioning andcontrol of widgets. Toplevel widgets are Tk and Toplevel. Otherwidgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, SpinboxLabelFrame and PanedWindow. Properties of the widgets are specified with keyword arguments.Keyword arguments have the same name as the corresponding resourceunder Tk. Widgets are positioned with one of the geometry managers Place, Packor Grid. These managers can be called with methods place, pack, gridavailable in every Widget. Actions are bound to events by resources (e.g. keyword argumentcommand) or with the method bind. Example (Hello, World):import Tkinterfrom Tkconstants import *tk = Tkinter.Tk()frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)frame.pack(fill=BOTH,expand=1)label = Tkinter.Label(frame, text="Hello, World")label.pack(fill=X, expand=1)button = Tkinter.Button(frame,text="Exit",command=tk.destroy)button.pack(side=BOTTOM)tk.mainloop()""" __version__ = "$Revision: 50704 $" import sysif sys.platform == "win32":    import FixTk # Attempt to configure Tcl/Tk without requiring PATHimport _tkinter # If this fails your Python may not be configured for Tktkinter = _tkinter # b/w compat for exportTclError = _tkinter.TclErrorfrom types import *from Tkconstants import *try:    import MacOS; _MacOS = MacOS; del MacOSexcept ImportError:    _MacOS = None wantobjects = 1 TkVersion = float(_tkinter.TK_VERSION)TclVersion = float(_tkinter.TCL_VERSION) READABLE = _tkinter.READABLEWRITABLE = _tkinter.WRITABLEEXCEPTION = _tkinter.EXCEPTION # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(try: _tkinter.createfilehandlerexcept AttributeError: _tkinter.createfilehandler = Nonetry: _tkinter.deletefilehandlerexcept AttributeError: _tkinter.deletefilehandler = None  def _flatten(tuple):    """Internal function."""    res = ()    for item in tuple:        if type(item) in (TupleType, ListType):            res = res + _flatten(item)        elif item is not None:            res = res + (item,)    return res try: _flatten = _tkinter._flattenexcept AttributeError: pass def _cnfmerge(cnfs):    """Internal function."""    if type(cnfs) is DictionaryType:        return cnfs    elif type(cnfs) in (NoneType, StringType):        return cnfs    else:        cnf = {}        for c in _flatten(cnfs):            try:                cnf.update(c)            except (AttributeError, TypeError), msg:                print "_cnfmerge: fallback due to:", msg                for k, v in c.items():                    cnf[k] = v        return cnf try: _cnfmerge = _tkinter._cnfmergeexcept AttributeError: pass class Event:    """Container for the properties of an event.     Instances of this type are generated if one of the following events occurs:     KeyPress, KeyRelease - for keyboard events    ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events    Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,    Colormap, Gravity, Reparent, Property, Destroy, Activate,    Deactivate - for window events.     If a callback function for one of these events is registered    using bind, bind_all, bind_class, or tag_bind, the callback is    called with an Event as first argument. It will have the    following attributes (in braces are the event types for which    the attribute is valid):         serial - serial number of event    num - mouse button pressed (ButtonPress, ButtonRelease)    focus - whether the window has the focus (Enter, Leave)    height - height of the exposed window (Configure, Expose)    width - width of the exposed window (Configure, Expose)    keycode - keycode of the pressed key (KeyPress, KeyRelease)    state - state of the event as a number (ButtonPress, ButtonRelease,                            Enter, KeyPress, KeyRelease,                            Leave, Motion)    state - state as a string (Visibility)    time - when the event occurred    x - x-position of the mouse    y - y-position of the mouse    x_root - x-position of the mouse on the screen             (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)    y_root - y-position of the mouse on the screen             (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)    char - pressed character (KeyPress, KeyRelease)    send_event - see X/Windows documentation    keysym - keysym of the event as a string (KeyPress, KeyRelease)    keysym_num - keysym of the event as a number (KeyPress, KeyRelease)    type - type of the event as a number    widget - widget in which the event occurred    delta - delta of wheel movement (MouseWheel)    """    pass _support_default_root = 1_default_root = None def NoDefaultRoot():    """Inhibit setting of default root window.     Call this function to inhibit that the first instance of    Tk is used for windows without an explicit parent window.    """    global _support_default_root    _support_default_root = 0    global _default_root    _default_root = None    del _default_root def _tkerror(err):    """Internal function."""    pass def _exit(code='0'):    """Internal function. Calling it will throw the exception SystemExit."""    raise SystemExit, code _varnum = 0class Variable:    """Class to define value holders for e.g. buttons.     Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations    that constrain the type of the value returned from get()."""    _default = ""    def __init__(self, master=None, value=None, name=None):        """Construct a variable         MASTER can be given as master widget.        VALUE is an optional value (defaults to "")        NAME is an optional Tcl name (defaults to PY_VARnum).         If NAME matches an existing variable and VALUE is omitted        then the existing value is retained.        """        global _varnum        if not master:            master = _default_root        self._master = master        self._tk = master.tk        if name:            self._name = name        else:            self._name = 'PY_VAR' + repr(_varnum)            _varnum += 1        if value != None:            self.set(value)        elif not self._tk.call("info", "exists", self._name):            self.set(self._default)    def __del__(self):        """Unset the variable in Tcl."""        self._tk.globalunsetvar(self._name)    def __str__(self):        """Return the name of the variable in Tcl."""        return self._name    def set(self, value):        """Set the variable to VALUE."""        return self._tk.globalsetvar(self._name, value)    def get(self):        """Return value of variable."""        return self._tk.globalgetvar(self._name)    def trace_variable(self, mode, callback):        """Define a trace callback for the variable.         MODE is one of "r", "w", "u" for read, write, undefine.        CALLBACK must be a function which is called when        the variable is read, written or undefined.         Return the name of the callback.        """        cbname = self._master._register(callback)        self._tk.call("trace", "variable", self._name, mode, cbname)        return cbname    trace = trace_variable    def trace_vdelete(self, mode, cbname):        """Delete the trace callback for a variable.         MODE is one of "r", "w", "u" for read, write, undefine.        CBNAME is the name of the callback returned from trace_variable or trace.        """        self._tk.call("trace", "vdelete", self._name, mode, cbname)        self._master.deletecommand(cbname)    def trace_vinfo(self):        """Return all trace callback information."""        return map(self._tk.split, self._tk.splitlist(            self._tk.call("trace", "vinfo", self._name)))    def __eq__(self, other):        """Comparison for equality (==).         Note: if the Variable's master matters to behavior        also compare self._master == other._master        """        return self.__class__.__name__ == other.__class__.__name__ \            and self._name == other._name class StringVar(Variable):    """Value holder for strings variables."""    _default = ""    def __init__(self, master=None, value=None, name=None):        """Construct a string variable.         MASTER can be given as master widget.        VALUE is an optional value (defaults to "")        NAME is an optional Tcl name (defaults to PY_VARnum).         If NAME matches an existing variable and VALUE is omitted        then the existing value is retained.        """        Variable.__init__(self, master, value, name)     def get(self):        """Return value of variable as string."""        value = self._tk.globalgetvar(self._name)        if isinstance(value, basestring):            return value        return str(value) class IntVar(Variable):    """Value holder for integer variables."""    _default = 0    def __init__(self, master=None, value=None, name=None):        """Construct an integer variable.         MASTER can be given as master widget.        VALUE is an optional value (defaults to 0)        NAME is an optional Tcl name (defaults to PY_VARnum).         If NAME matches an existing variable and VALUE is omitted        then the existing value is retained.        """        Variable.__init__(self, master, value, name)     def set(self, value):        """Set the variable to value, converting booleans to integers."""        if isinstance(value, bool):            value = int(value)        return Variable.set(self, value)     def get(self):        """Return the value of the variable as an integer."""        return getint(self._tk.globalgetvar(self._name)) class DoubleVar(Variable):    """Value holder for float variables."""    _default = 0.0    def __init__(self, master=None, value=None, name=None):        """Construct a float variable.         MASTER can be given as master widget.        VALUE is an optional value (defaults to 0.0)        NAME is an optional Tcl name (defaults to PY_VARnum).         If NAME matches an existing variable and VALUE is omitted        then the existing value is retained.        """        Variable.__init__(self, master, value, name)     def get(self):        """Return the value of the variable as a float."""        return getdouble(self._tk.globalgetvar(self._name)) class BooleanVar(Variable):    """Value holder for boolean variables."""    _default = False    def __init__(self, master=None, value=None, name=None):        """Construct a boolean variable.         MASTER can be given as master widget.        VALUE is an optional value (defaults to False)        NAME is an optional Tcl name (defaults to PY_VARnum).         If NAME matches an existing variable and VALUE is omitted        then the existing value is retained.        """        Variable.__init__(self, master, value, name)     def get(self):        """Return the value of the variable as a bool."""        return self._tk.getboolean(self._tk.globalgetvar(self._name)) def mainloop(n=0):    """Run the main loop of Tcl."""    _default_root.tk.mainloop(n) getint = int getdouble = float def getboolean(s):    """Convert true and false to integer values 1 and 0."""    return _default_root.tk.getboolean(s) # Methods defined on both toplevel and interior widgetsclass Misc:    """Internal class.     Base class which defines methods common for interior widgets."""     # XXX font command?    _tclCommands = None    def destroy(self):        """Internal function.         Delete all Tcl commands created for        this widget in the Tcl interpreter."""        if self._tclCommands is not None:            for name in self._tclCommands:                #print '- Tkinter: deleted command', name                self.tk.deletecommand(name)            self._tclCommands = None    def deletecommand(self, name):        """Internal function.         Delete the Tcl command provided in NAME."""        #print '- Tkinter: deleted command', name        self.tk.deletecommand(name)        try:            self._tclCommands.remove(name)        except ValueError:            pass    def tk_strictMotif(self, boolean=None):        """Set Tcl internal variable, whether the look and feel        should adhere to Motif.         A parameter of 1 means adhere to Motif (e.g. no color        change if mouse passes over slider).        Returns the set value."""        return self.tk.getboolean(self.tk.call(            'set', 'tk_strictMotif', boolean))    def tk_bisque(self):        """Change the color scheme to light brown as used in Tk 3.6 and before."""        self.tk.call('tk_bisque')    def tk_setPalette(self, *args, **kw):        """Set a new color scheme for all widget elements.         A single color as argument will cause that all colors of Tk        widget elements are derived from this.        Alternatively several keyword parameters and its associated        colors can be given. The following keywords are valid:        activeBackground, foreground, selectColor,        activeForeground, highlightBackground, selectBackground,        background, highlightColor, selectForeground,        disabledForeground, insertBackground, troughColor."""        self.tk.call(('tk_setPalette',)              + _flatten(args) + _flatten(kw.items()))    def tk_menuBar(self, *args):        """Do not use. Needed in Tk 3.6 and earlier."""        pass # obsolete since Tk 4.0    def wait_variable(self, name='PY_VAR'):        """Wait until the variable is modified.         A parameter of type IntVar, StringVar, DoubleVar or        BooleanVar must be given."""        self.tk.call('tkwait', 'variable', name)    waitvar = wait_variable # XXX b/w compat    def wait_window(self, window=None):        """Wait until a WIDGET is destroyed.         If no parameter is given self is used."""        if window is None:            window = self        self.tk.call('tkwait', 'window', window._w)    def wait_visibility(self, window=None):        """Wait until the visibility of a WIDGET changes        (e.g. it appears).         If no parameter is given self is used."""        if window is None:            window = self        self.tk.call('tkwait', 'visibility', window._w)    def setvar(self, name='PY_VAR', value='1'):        """Set Tcl variable NAME to VALUE."""        self.tk.setvar(name, value)    def getvar(self, name='PY_VAR'):        """Return value of Tcl variable NAME."""        return self.tk.getvar(name)    getint = int    getdouble = float    def getboolean(self, s):        """Return a boolean value for Tcl boolean values true and false given as parameter."""        return self.tk.getboolean(s)    def focus_set(self):        """Direct input focus to this widget.         If the application currently does not have the focus        this widget will get the focus if the application gets        the focus through the window manager."""        self.tk.call('focus', self._w)    focus = focus_set # XXX b/w compat?    def focus_force(self):        """Direct input focus to this widget even if the        application does not have the focus. Use with        caution!"""        self.tk.call('focus', '-force', self._w)    def focus_get(self):        """Return the widget which has currently the focus in the        application.         Use focus_displayof to allow working with several        displays. Return None if application does not have        the focus."""        name = self.tk.call('focus')        if name == 'none' or not name: return None        return self._nametowidget(name)    def focus_displayof(self):        """Return the widget which has currently the focus on the        display where this widget is located.         Return None if the application does not have the focus."""        name = self.tk.call('focus', '-displayof', self._w)        if name == 'none' or not name: return None        return self._nametowidget(name)    def focus_lastfor(self):        """Return the widget which would have the focus if top level        for this widget gets the focus from the window manager."""        name = self.tk.call('focus', '-lastfor', self._w)        if name == 'none' or not name: return None        return self._nametowidget(name)    def tk_focusFollowsMouse(self):        """The widget under mouse will get automatically focus. Can not        be disabled easily."""        self.tk.call('tk_focusFollowsMouse')    def tk_focusNext(self):        """Return the next widget in the focus order which follows        widget which has currently the focus.         The focus order first goes to the next child, then to        the children of the child recursively and then to the        next sibling which is higher in the stacking order.  A        widget is omitted if it has the takefocus resource set        to 0."""        name = self.tk.call('tk_focusNext', self._w)        if not name: return None        return self._nametowidget(name)    def tk_focusPrev(self):        """Return previous widget in the focus order. See tk_focusNext for details."""        name = self.tk.call('tk_focusPrev', self._w)        if not name: return None        return self._nametowidget(name)    def after(self, ms, func=None, *args):        """Call function once after given time.         MS specifies the time in milliseconds. FUNC gives the        function which shall be called. Additional parameters        are given as parameters to the function call.  Return        identifier to cancel scheduling with after_cancel."""        if not func:            # I'd rather use time.sleep(ms*0.001)            self.tk.call('after', ms)        else:            def callit():                try:                    func(*args)                finally:                    try:

Lines 1–500 of 3759.