/Lib/lib-tk/Tkinter.py
http://unladen-swallow.googlecode.com/ · Python · 3774 lines · 3086 code · 86 blank · 602 comment · 199 complexity · 77f6245e4d47ba42fe974c0a4dbee464 MD5 · raw file
Large files are truncated click here to view the full file
- """Wrapper functions for Tcl/Tk.
- Tkinter provides classes which allow the display, positioning and
- control of widgets. Toplevel widgets are Tk and Toplevel. Other
- widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
- Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
- LabelFrame and PanedWindow.
- Properties of the widgets are specified with keyword arguments.
- Keyword arguments have the same name as the corresponding resource
- under Tk.
- Widgets are positioned with one of the geometry managers Place, Pack
- or Grid. These managers can be called with methods place, pack, grid
- available in every Widget.
- Actions are bound to events by resources (e.g. keyword argument
- command) or with the method bind.
- Example (Hello, World):
- import Tkinter
- from 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: 73770 $"
- import sys
- if sys.platform == "win32":
- # Attempt to configure Tcl/Tk without requiring PATH
- import FixTk
- import _tkinter # If this fails your Python may not be configured for Tk
- tkinter = _tkinter # b/w compat for export
- TclError = _tkinter.TclError
- from types import *
- from Tkconstants import *
- wantobjects = 1
- TkVersion = float(_tkinter.TK_VERSION)
- TclVersion = float(_tkinter.TCL_VERSION)
- READABLE = _tkinter.READABLE
- WRITABLE = _tkinter.WRITABLE
- EXCEPTION = _tkinter.EXCEPTION
- # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
- try: _tkinter.createfilehandler
- except AttributeError: _tkinter.createfilehandler = None
- try: _tkinter.deletefilehandler
- except 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._flatten
- except 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._cnfmerge
- except 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 = 0
- class 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 is not 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 widgets
- class 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:
- self.deletecommand(name)
- except TclError:
- pass
- name = self._register(callit)
- return self.tk.call('after', ms, name)
- def after_idle(self, func, *args):
- """Call FUNC once if the Tcl main loop has no event to
- process.
- Return an identifier to cancel the scheduling with
- after_cancel."""
- return self.after('idle', func, *args)
- def after_cancel(self, id):
- """Cancel scheduling of function identified with ID.
- Identifier returned by after or after_idle must be
- given as first parameter."""
- try:
- data = self.tk.call('after', 'info', id)
- # In Tk 8.3, splitlist returns: (script, type)
- # In Tk 8.4, splitlist may return (script, type) or (script,)
- script = self.tk.splitlist(data)[0]
- self.deletecommand(script)
- except TclError:
- pass
- self.tk.call('after', 'cancel', id)
- def bell(self, displayof=0):
- """Ring a display's bell."""
- self.tk.call(('bell',) + self._displayof(displayof))
- # Clipboard handling:
- def clipboard_get(self, **kw):
- """Retrieve data from the clipboard on window's display.
- The window keyword defaults to the root window of the Tkinter
- application.
- The type keyword specifies the form in which the data is
- to be returned and should be an atom name such as STRING
- or FILE_NAME. Type defaults to STRING.
- This command is equivalent to:
- selection_get(CLIPBOARD)
- """
- return self.tk.call(('clipboard', 'get') + self._options(kw))
- def clipboard_clear(self, **kw):
- """Clear the data in the Tk clipboard.
- A widget specified for the optional displayof keyword
- argument specifies the target display."""
- if not kw.has_key('displayof'): kw['displayof'] = self._w
- self.tk.call(('clipboard', 'clear') + self._options(kw))
- def clipboard_append(self, string, **kw):
- """Append STRING to the Tk clipboard.
- A widget specified at the optional displayof keyword
- argument specifies the target display. The clipboard
- can be retrieved with selection_get."""
- if not kw.has_key('displayof'): kw['displayof'] = self._w
- self.tk.call(('clipboard', 'append') + self._options(kw)
- + ('--', string))
- # XXX grab current w/o window argument
- def grab_current(self):
- """Return widget which has currently the grab in this application
- or None."""
- name = self.tk.call('grab', 'current', self._w)
- if not name: return None
- return self._nametowidget(name)
- def grab_release(self):
- """Release grab for this widget if currently set."""
- self.tk.call('grab', 'release', self._w)
- def grab_set(self):
- """Set grab for this widget.
- A grab directs all events to this and descendant
- widgets in the application."""
- self.tk.call('grab', 'set', self._w)
- def grab_set_global(self):
- """Set global grab for this widget.
- A global grab directs all events to this and
- descendant widgets on the display. Use with caution -
- other applications do not get events anymore."""
- self.tk.call('grab', 'set', '-global', self._w)
- def grab_status(self):
- """Return None, "local" or "global" if this widget has
- no, a local or a global grab."""
- status = self.tk.call('grab', 'status', self._w)
- if status == 'none': status = None
- return status
- def option_add(self, pattern, value, priority = None):
- """Set a VALUE (second parameter) for an option
- PATTERN (first parameter).
- An optional third parameter gives the numeric priority
- (defaults to 80)."""
- self.tk.call('option', 'add', pattern, value, priority)
- def option_clear(self):
- """Clear the option database.
- It will be reloaded if option_add is called."""
- self.tk.call('option', 'clear')
- def option_get(self, name, className):
- """Return the value for an option NAME for this widget
- with CLASSNAME.
- Values with higher priority override lower values."""
- return self.tk.call('option', 'get', self._w, name, className)
- def option_readfile(self, fileName, priority = None):
- """Read file FILENAME into the option database.
- An optional second parameter gives the numeric
- priority."""
- self.tk.call('option', 'readfile', fileName, priority)
- def selection_clear(self, **kw):
- """Clear the current X selection."""
- if not kw.has_key('displayof'): kw['displayof'] = self._w
- self.tk.call(('selection', 'clear') + self._options(kw))
- def selection_get(self, **kw):
- """Return the contents of the current X selection.
- A keyword parameter selection specifies the name of
- the selection and defaults to PRIMARY. A keyword
- parameter displayof specifies a widget on the display
- to use."""
- if not kw.has_key('displayof'): kw['displayof'] = self._w
- return self.tk.call(('selection', 'get') + self._options(kw))
- def selection_handle(self, command, **kw):
- """Specify a function COMMAND to call if the X
- selection owned by this widget is queried by another
- application.
- This function must return the contents of the
- selection. The function will be called with the
- arguments OFFSET and LENGTH which allows the chunking
- of very long selections. The following keyword
- parameters can be provided:
- selection - name of the selection (default PRIMARY),
- type - type of the selection (e.g. STRING, FILE_NAME)."""
- name = self._register(command)
- self.tk.call(('selection', 'handle') + self._options(kw)
- + (self._w, name))
- def selection_own(self, **kw):
- """Become owner of X selection.
- A keyword parameter selection specifies the name of
- the selection (default PRIMARY)."""
- self.tk.call(('selection', 'own') +
- self._options(kw) + (self._w,))
- def selection_own_get(self, **kw):
- """Return owner of X selection.
- The following keyword parameter can
- be provided:
- selection - name of the selection (default PRIMARY),
- type - type of the selection (e.g. STRING, FILE_NAME)."""
- if not kw.has_key('displayof'): kw['displayof'] = self._w
- name = self.tk.call(('selection', 'own') + self._options(kw))
- if not name: return None
- return self._nametowidget(name)
- def send(self, interp, cmd, *args):
- """Send Tcl command CMD to different interpreter INTERP to be executed."""
- return self.tk.call(('send', interp, cmd) + args)
- def lower(self, belowThis=None):
- """Lower this widget in the stacking order."""
- self.tk.call('lower', self._w, belowThis)
- def tkraise(self, aboveThis=None):
- """Raise this widget in the stacking order."""
- self.tk.call('raise', self._w, aboveThis)
- lift = tkraise
- def colormodel(self, value=None):
- """Useless. Not implemented in Tk."""
- return self.tk.call('tk', 'colormodel', self._w, value)
- def winfo_atom(self, name, displayof=0):
- """Return integer which represents atom NAME."""
- args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
- return getint(self.tk.call(args))
- def winfo_atomname(self, id, displayof=0):
- """Return name of atom with identifier ID."""
- args = ('winfo', 'atomname') \
- + self._displayof(displayof) + (id,)
- return self.tk.call(args)
- def winfo_cells(self):
- """Return number of cells in the colormap for this widget."""
- return getint(
- self.tk.call('winfo', 'cells', self._w))
- def winfo_children(self):
- """Return a list of all widgets which are children of this widget."""
- result = []
- for child in self.tk.splitlist(
- self.tk.call('winfo', 'children', self._w)):
- try:
- # Tcl sometimes returns extra windows, e.g. for
- # menus; those need to be skipped
- result.append(self._nametowidget(child))
- except KeyError:
- pass
- return result
- def winfo_class(self):
- """Return window class name of this widget."""
- return self.tk.call('winfo', 'class', self._w)
- def winfo_colormapfull(self):
- """Return true if at the last color request the colormap was full."""
- return self.tk.getboolean(
- self.tk.call('winfo', 'colormapfull', self._w))
- def winfo_containing(self, rootX, rootY, displayof=0):
- """Return the widget which is at the root coordinates ROOTX, ROOTY."""
- args = ('winfo', 'containing') \
- + self._displayof(displayof) + (rootX, rootY)
- name = self.tk.call(args)
- if not name: return None
- return self._nametowidget(name)
- def winfo_depth(self):
- """Return the number of bits per pixel."""
- return getint(self.tk.call('winfo', 'depth', self._w))
- def winfo_exists(self):
- """Return true if this widget exists."""
- return getint(
- self.tk.call('winfo', 'exists', self._w))
- def winfo_fpixels(self, number):
- """Return the number of pixels for the given distance NUMBER
- (e.g. "3c") as float."""
- return getdouble(self.tk.call(
- 'winfo', 'fpixels', self._w, number))
- def winfo_geometry(self):
- """Return geometry string for this widget in the form "widthxheight+X+Y"."""
- return self.tk.call('winfo', 'geometry', self._w)
- def winfo_height(self):
- """Return height of this widget."""
- return getint(
- self.tk.call('winfo', 'height', self._w))
- def winfo_id(self):
- """Return identifier ID for this widget."""
- return self.tk.getint(
- self.tk.call('winfo', 'id', self._w))
- def winfo_interps(self, displayof=0):
- """Return the name of all Tcl interpreters for this display."""
- args = ('winfo', 'interps') + self._displayof(displayof)
- return self.tk.splitlist(self.tk.call(args))
- def winfo_ismapped(self):
- """Return true if this widget is mapped."""
- return getint(
- self.tk.call('winfo', 'ismapped', self._w))
- def winfo_manager(self):
- """Return the window mananger name for this widget."""
- return self.tk.call('winfo', 'manager', self._w)
- def winfo_name(self):
- """Return the name of this widget."""
- return self.tk.call('winfo', 'name', self._w)
- def winfo_parent(self):
- """Return the name of the parent of this widget."""
- return self.tk.call('winfo', 'parent', self._w)
- def winfo_pathname(self, id, displayof=0):
- """Return the pathname of the widget given by ID."""
- args = ('winfo', 'pathname') \
- + self._displayof(displayof) + (id,)
- return self.tk.call(args)
- def winfo_pixels(self, number):
- """Rounded integer value of winfo_fpixels."""
- return getint(
- self.tk.call('winfo', 'pixels', self._w, number))
- def winfo_pointerx(self):
- """Return the x coordinate of the pointer on the root window."""
- return getint(
- self.tk.call('winfo', 'pointerx', self._w))
- def winfo_pointerxy(self):
- """Return a tuple of x and y coordinates of the pointer on the root window."""
- return self._getints(
- self.tk.call('winfo', 'pointerxy', self._w))
- def winfo_pointery(self):
- """Return the y coordinate of the pointer on the root window."""
- return getint(
- self.tk.call('winfo', 'pointery', self._w))
- def winfo_reqheight(self):
- """Return requested height of this widget."""
- return getint(
- self.tk.call('winfo', 'reqheight', self._w))
- def winfo_reqwidth(self):
- """Return requested width of this widget."""
- return getint(
- self.tk.call('winfo', 'reqwidth', self._w))
- def winfo_rgb(self, color):
- """Return tuple of decimal values for red, green, blue for
- COLOR in this widget."""
- return self._getints(
- self.tk.call('winfo', 'rgb', self._w, color))
- def winfo_rootx(self):
- """Return x coordinate of upper left corner of this widget on the
- root window."""
- return getint(
- self.tk.call('winfo', 'rootx', self._w))
- def winfo_rooty(self):
- """Return y coordinate of upper left corner of this widget on the
- root window."""
- return getint(
- self.tk.call('winfo', 'rooty', self._w))
- def winfo_screen(self):
- """Return the screen name of this widget."""
- return self.tk.call('winfo', 'screen', self._w)
- def winfo_screencells(self):
- """Return the number of the cells in the colormap of the screen
- of this widget."""
- return getint(
- self.tk.call('winfo', 'screencells', self._w))
- def winfo_screendepth(self):
- """Return the number of bits per pixel of the root window of the
- screen of this widget."""
- return getint(
- self.tk.call('winfo', 'screendepth', self._w))
- def winfo_screenheight(self):
- """Return the number of pixels of the height of the screen of this widget
- in pixel."""
- return getint(
- self.tk.call('winfo', 'screenheight', self._w))
- def winfo_screenmmheight(self):
- """Return the number of pixels of the height of the screen of
- this widget in mm."""
- return getint(
- self.tk.call('winfo', 'screenmmheight', self._w))
- def winfo_screenmmwidth(self):
- """Return the number of pixels of the width of the screen of
- this widget in mm."""
- return getint(
- self.tk.call('winfo', 'screenmmwidth', self._w))
- def winfo_screenvisual(self):
- """Return one of the strings directcolor, grayscale, pseudocolor,
- staticcolor, staticgray, or truecolor for the default
- colormodel of this screen."""
- return self.tk.call('winfo', 'screenvisual', self._w)
- def winfo_screenwidth(self):
- """Return the number of pixels of the width of the screen of
- this widget in pixel."""
- return getint(
- self.tk.call('winfo', 'screenwidth', self._w))
- def winfo_server(self):
- """Return information of the X-Server of the screen of this widget in
- the form "XmajorRminor vendor vendorVersion"."""
- return self.tk.call('winfo', 'server', self._w)
- def winfo_toplevel(self):
- """Return the toplevel widget of this widget."""
- return self._nametowidget(self.tk.call(
- 'winfo', 'toplevel', self._w))
- def winfo_viewable(self):
- """Return true if the widget and all its higher ancestors are mapped."""
- return getint(
- self.tk.call('winfo', 'viewable', self._w))
- def winfo_visual(self):
- """Return one of the strings directcolor, grayscale, pseudocolor,
- staticcolor, staticgray, or truecolor for the
- colormodel of this widget."""
- return self.tk.call('winfo', 'visual', self._w)
- def winfo_visualid(self):
- """Return the X identifier for the visual for this widget."""
- return self.tk.call('winfo', 'visualid', self._w)
- def winfo_visualsavailable(self, includeids=0):
- """Return a list of all visuals available for the screen
- of this widget.
- Each item in the list consists of a visual name (see winfo_visual), a
- depth and if INCLUDEIDS=1 is given also the X identifier."""
- data = self.tk.split(
- self.tk.call('winfo', 'visualsavailable', self._w,
- includeids and 'includeids' or None))
- if type(data) is StringType:
- data = [self.tk.split(data)]
- return map(self.__winfo_parseitem, data)
- def __winfo_parseitem(self, t):
- """Internal function."""
- return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
- def __winfo_getint(self, x):
- """Internal function."""
- return int(x, 0)
- def winfo_vrootheight(self):
- """Return the height of the virtual root window associated with this
- widget in pixels. If there is no virtual root window return the
- height of the screen."""
- return getint(
- self.tk.call('winfo', 'vrootheight', self._w))
- def winfo_vrootwidth(self):
- """Return the width of the virtual root window associated with this
- widget in pixel. If there is no virtual root window return the
- width of the screen."""
- return getint(
- self.tk.call('winfo', 'vrootwidth', self._w))
- def winfo_vrootx(self):
- """Return the x offset of the virtual root relative to the root
- window of the screen of this widget."""
- return getint(
- self.tk.call('winfo', 'vrootx', self._w))
- def winfo_vrooty(self):
- """Return the y offset of the virtual root relative to the root
- window of the screen of this widget."""
- return getint(
- self.tk.call('winfo', 'vrooty', self._w))
- def winfo_width(self):
- """Return the width of this widget."""
- return getint(
- self.tk.call('winfo', 'width', self._w))
- def winfo_x(self):
- """Return the x coordinate of the upper left corner of this widget
- in the parent."""
- return getint(
- self.tk.call('winfo', 'x', self._w))
- def winfo_y(self):
- """Return the y coordinate of the upper left corner of this widget
- in the parent."""
- return getint(
- self.tk.call('winfo', 'y', self._w))
- def update(self):
- """Enter event loop until all pending events have been processed by Tcl."""
- self.tk.call('update')
- def update_idletasks(self):
- """Enter event loop until all idle callbacks have been called. This
- will update the display of windows but not process events caused by
- the user."""
- self.tk.call('update', 'idletasks')
- def bindtags(self, tagList=None):
- """Set or get the list of bindtags for this widget.
- With no argument return the list of all bindtags associated with
- this widget. With a list of strings as argument the bindtags are
- set to this list. The bindtags determine in which order events are
- processed (see bind)."""
- if tagList is None:
- return self.tk.splitlist(
- self.tk.call('bindtags', self._w))
- else:
- self.tk.call('bindtags', self._w, tagList)
- def _bind(self, what, sequence, func, add, needcleanup=1):
- """Internal function."""
- if type(func) is StringType:
- self.tk.call(what + (sequence, func))
- elif func:
- funcid = self._register(func, self._substitute,
- needcleanup)
- cmd = ('%sif {"[%s %s]" == "break"} break\n'
- %
- (add and '+' or '',
- funcid, self._subst_format_str))
- self.tk.call(what + (sequence, cmd))
- return funcid
- elif sequence:
- return self.tk.call(what + (sequence,))
- else:
- return self.tk.splitlist(self.tk.call(what))
- def bind(self, sequence=None, func=None, add=None):
- """Bind to this widget at event SEQUENCE a call to function FUNC.
- SEQUENCE is a string of concatenated event
- patterns. An event pattern is of the form
- <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
- of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
- Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
- B3, Alt, Button4, B4, Double, Button5, B5 Triple,
- Mod1, M1. TYPE is one of Activate, Enter, Map,
- ButtonPress, Button, Expose, Motion, ButtonRelease
- FocusIn, MouseWheel, Circulate, FocusOut, Property,
- Colormap, Gravity Reparent, Configure, KeyPress, Key,
- Unmap, Deactivate, KeyRelease Visibility, Destroy,
- Leave and DETAIL is the button number for ButtonPress,
- ButtonRelease and DETAIL is the Keysym for KeyPress and
- KeyRelease. Examples are
- <Control-Button-1> for pressing Control and mouse button 1 or
- <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
- An event pattern can also be a virtual event of the form
- <<AString>> where AString can be arbitrary. This
- event can be generated by event_generate.
- If events are concatenated they must appear shortly
- after each other.
- FUNC will be called if the event sequence occurs with an
- instance of Event as argument. If the return value of FUNC is
- "break" no further bound function is invoked.
- An additional boolean parameter ADD specifies whether FUNC will
- be called additionally to the other bound function or whether
- it will replace the previous function.
- Bind will return an identifier to allow deletion of the bound function with
- unbind without memory leak.
- If FUNC or SEQUENCE is omitted the bound function or list
- of bound events are returned."""
- return self._bind(('bind', self._w), sequence, func, add)
- def unbind(self, sequence, funcid=None):
- """Unbind for this widget for event SEQUENCE the
- function identified with FUNCID."""
- self.tk.call('bind', self._w, sequence, '')
- if funcid:
- self.deletecommand(funcid)
- def bind_all(self, sequence=None, func=None, add=None):
- """Bind to all widgets at an event SEQUENCE a call to function FUNC.
- An additional boolean parameter ADD specifies whether FUNC will
- be called additionally to the other bound function or whether
- it will replace the previous function. See bind for the return value."""
- return self._bind(('bind', 'all'), sequence, func, add, 0)
- def unbind_all(self, sequence):
- """Unbind for all widgets for event SEQUENCE all functions."""
- self.tk.call('bind', 'all' , sequence, '')
- def bind_class(self, className, sequence=None, func=None, add=None):
- """Bind to widgets with bindtag CLASSNAME at event
- SEQUENCE a call of function FUNC. An additional
- boolean parameter ADD specifies whether FUNC will be
- called additionally to the other bound function or
- whether it will replace the previous function. See bind for
- the return value."""
- return self._bind(('bind', className), sequence, func, add, 0)
- def unbind_class(self, className, sequence):
- """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
- all functions."""
- self.tk.call('bind', className , sequence, '')
- def mainloop(self, n=0):
- """Call the mainloop of Tk."""
- self.tk.mainloop(n)
- def quit(self):
- """Quit the Tcl interpreter. All widgets will be destroyed."""
- self.tk.quit()
- def _getints(self, string):
- """Internal function."""
- if string:
- return tuple(map(getint, self.tk.splitlist(string)))
- def _getdoubles(self, string):
- """Internal function."""
- if string:
- return tuple(map(getdouble, self.tk.splitlist(string)))
- def _getboolean(self, string):
- """Internal function."""
- if string:
- return self.tk.getboolean(string)
- def _displayof(self, displayof):
- """Internal function."""
- if displayof:
- return ('-displayof', displayof)
- if displayof is None:
- return ('-displayof', self._w)
- return ()
- def _options(self, cnf, kw = None):
- """Internal function."""
- if kw:
- cnf = _cnfmerge((cnf, kw))
- else:
- cnf = _cnfmerge(cnf)
- res = ()
- for k, v in cnf.items():
- if v is not None:
- if k[-1] == '_': k = k[:-1]
- if callable(v):
- v = self._register(v)
- elif isinstance(v, (tuple, list)):
- nv = []
- for item in v:
- if not isinstance(item, (basestring, int)):
- break
- elif isinstance(item, int):
- nv.append('%d' % item)
- else:
- # format it to proper Tcl code if it contains space
- nv.append(('{%s}' if ' ' in item else '%s') % item)
- else:
- v = ' '.join(nv)
- res = res + ('-'+k, v)
- return res
- def nametowidget(self, name):
- """Return the Tkinter instance of a widget identified by
- its Tcl name NAME."""
- name = str(name).split('.')
- w = self
- if not name[0]:
- w = w._root()
- name = name[1:]
- for n in name:
- if not n:
- break
- w = w.children[n]
- return w
- _nametowidget = nametowidget
- def _register(self, func, subst=None, needcleanup=1):
- """Return a newly created Tcl function. If this
- function is called, the Python function FUNC will
- be executed. An optional function SUBST can
- be given which will be executed before FUNC."""
- f = CallWrapper(func, subst, self).__call__
- name = repr(id(f))
- try:
- func = func.im_func
- except AttributeError:
- pass
- try:
- name = name + func.__name__
- except AttributeError:
- pass
- self.tk.createcommand(name, f)
- if needcleanup:
- if self._tclCommands is None:
- self._tclCommands = []
- self._tclCommands.append(name)
- return name
- register = _register
- def _root(self):
- """Internal function."""
- w = self
- while w.master: w = w.master
- return w
- _subst_format = ('%#', '%b', '%f', '%h', '%k',
- '%s', '%t', '%w', '%x', '%y',
- '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
- _subst_format_str = " ".join(_subst_format)
- def _substitute(self, *args):
- """Internal function."""
- if len(args) != len(self._subst_format): return args
- getboolean = self.tk.getboolean
- getint = int
- def getint_event(s):
- """Tk changed behavior in 8.4.2, returning "??" rather more often."""
- try:
- return int(s)
- except ValueError:
- return s
- nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
- # Missing: (a, c, d, m, o, v, B, R)
- e = Event()
- # serial field: valid vor all events
- # number of button: ButtonPress and ButtonRelease events only
- # height field: Configure, ConfigureRequest, Create,
- # ResizeRequest, and Expose events only
- # keycode field: KeyPress and KeyRelease events only
- # time field: "valid for events that contain a time field"
- # width field: Configure, ConfigureRequest, Create, ResizeRequest,
- # and Expose events only
- # x field: "valid for events that contain a x field"
- # y field: "valid for events that contain a y field"
- # keysym as decimal: KeyPress and KeyRelease events only
- # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
- # KeyRelease,and Motion events
- e.serial = getint(nsign)
- e.num = getint_event(b)
- try: e.focus = getboolean(f)
- except TclError: pass
- e.height = getint_event(h)
- e.keycode = getint_event(k)
- e.state = getint_event(s)
- e.time = getint_event(t)
- e.width = getint_event(w)
- e.x = getint_event(x)
- e.y = getint_event(y)
- e.char = A
- try: e.send_event = getboolean(E)
- except TclError: pass
- e.keysym = K
- e.keysym_num = getint_event(N)
- e.type = T
- try:
- e.widget = self._nametowidget(W)
- except KeyError:
- e.widget = W
- e.x_root = getint_event(X)
- e.y_root = getint_event(Y)
- try:
- e.delta = getint(D)
- except ValueError:
- e.delta = 0
- return (e,)
- def _report_exception(self):
- """Internal function."""
- import sys
- exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
- root = self._root()
- root.report_callback_exception(exc, val, tb)
- def _configure(self, cmd, cnf, kw):
- """Internal function."""
- if kw:
- cnf = _cnfmerge((cnf, kw))
- elif cnf:
- cnf = _cnfmerge(cnf)
- if cnf is None:
- cnf = {}
- for x in self.tk.split(
- self.tk.call(_flatten((self._w, cmd)))):
- cnf[x[0][1:]] = (x[0][1:],) + x[1:]
- return cnf
- if type(cnf) is StringType:
- x = self.tk.split(
- self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
- return (x[0][1:],) + x[1:]
- self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
- # These used to be defined in Widget:
- def configure(self, cnf=None, **kw):
- """Configure resources of a widget.
- The values for resources are specified as keyword
- arguments. To get an overview about
- the allowed keyword arguments call the method keys.
- """
- return self._configure('configure', cnf, kw)
- config = configure
- def cget(self, key):
- """Return the resource value for a KEY given as string."""
- return self.tk.call(self._w, 'cget', '-' + key)
- __getitem__ = cget
- def __setitem__(self, key, value):
- self.configure({key: value})
- def __contains__(self, key):
- raise TypeError("Tkinter objects don't support 'in' tests.")
- def keys(self):
- """Return a list of all resource names of this widget."""
- return map(lambda x: x[0][1:],
- self.tk.split(self.tk.call(self._w, 'configure')))
- def __str__(self):
- """Return the window path name of this widget."""
- return self._w
- # Pack methods that apply to the master
- _noarg_ = ['_noarg_']
- def pack_propagate(self, flag=_noarg_):
- """Set or get the status for propagation of geometry information.
- A boolean argument specifies whether the geometry information
- of the slaves will determine the size of this widget. If no argument
- is given the current setting will be returned.
- """
- if flag is Misc._noarg_:
- return self._getboolean(self.tk.call(
- 'pack', 'propagate', self._w))
- else:
- self.tk.call('pack', 'propagate', self._w, flag)
- propagate = pack_propagate
- def pack_slaves(self):
- """Return a list of all slaves of this widget
- in its packing order."""
- return map(self._nametowidget,
- self.tk.splitlist(
- self.tk.call('pack', 'slaves', self._w)))
- slaves = pack_slaves
- # Place method that applies to the master
- def place_slaves(self):
- """Return a list of all slaves of this widget
- in its packing order."""
- return map(self._nametowidget,
- self.tk.splitlist(
- self.tk.call(
- 'place', 'slaves', self._w)))
- # Grid methods that apply to the master
- def grid_bbox(self, column=None, row=None, col2=None, row2=None):
- """Return a tuple of integer coordinates for the bounding
- box of…