0001 """Wrapper functions for Tcl/Tk. 0002 0003 Tkinter provides classes which allow the display, positioning and 0004 control of widgets. Toplevel widgets are Tk and Toplevel. Other 0005 widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, 0006 Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox 0007 LabelFrame and PanedWindow. 0008 0009 Properties of the widgets are specified with keyword arguments. 0010 Keyword arguments have the same name as the corresponding resource 0011 under Tk. 0012 0013 Widgets are positioned with one of the geometry managers Place, Pack 0014 or Grid. These managers can be called with methods place, pack, grid 0015 available in every Widget. 0016 0017 Actions are bound to events by resources (e.g. keyword argument 0018 command) or with the method bind. 0019 0020 Example (Hello, World): 0021 import Tkinter 0022 from Tkconstants import * 0023 tk = Tkinter.Tk() 0024 frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2) 0025 frame.pack(fill=BOTH,expand=1) 0026 label = Tkinter.Label(frame, text="Hello, World") 0027 label.pack(fill=X, expand=1) 0028 button = Tkinter.Button(frame,text="Exit",command=tk.destroy) 0029 button.pack(side=BOTTOM) 0030 tk.mainloop() 0031 """ 0032 0033 __version__ = "$Revision: 1.181 $" 0034 0035 import sys 0036 if sys.platform == "win32": 0037 import FixTk # Attempt to configure Tcl/Tk without requiring PATH 0038 import _tkinter # If this fails your Python may not be configured for Tk 0039 tkinter = _tkinter # b/w compat for export 0040 TclError = _tkinter.TclError 0041 from types import * 0042 from Tkconstants import * 0043 try: 0044 import MacOS; _MacOS = MacOS; del MacOS 0045 except ImportError: 0046 _MacOS = None 0047 0048 wantobjects = 1 0049 0050 TkVersion = float(_tkinter.TK_VERSION) 0051 TclVersion = float(_tkinter.TCL_VERSION) 0052 0053 READABLE = _tkinter.READABLE 0054 WRITABLE = _tkinter.WRITABLE 0055 EXCEPTION = _tkinter.EXCEPTION 0056 0057 # These are not always defined, e.g. not on Win32 with Tk 8.0 :-( 0058 try: _tkinter.createfilehandler 0059 except AttributeError: _tkinter.createfilehandler = None 0060 try: _tkinter.deletefilehandler 0061 except AttributeError: _tkinter.deletefilehandler = None 0062 0063 0064 def _flatten(tuple): 0065 """Internal function.""" 0066 res = () 0067 for item in tuple: 0068 if type(item) in (TupleType, ListType): 0069 res = res + _flatten(item) 0070 elif item is not None: 0071 res = res + (item,) 0072 return res 0073 0074 try: _flatten = _tkinter._flatten 0075 except AttributeError: pass 0076 0077 def _cnfmerge(cnfs): 0078 """Internal function.""" 0079 if type(cnfs) is DictionaryType: 0080 return cnfs 0081 elif type(cnfs) in (NoneType, StringType): 0082 return cnfs 0083 else: 0084 cnf = {} 0085 for c in _flatten(cnfs): 0086 try: 0087 cnf.update(c) 0088 except (AttributeError, TypeError), msg: 0089 print "_cnfmerge: fallback due to:", msg 0090 for k, v in c.items(): 0091 cnf[k] = v 0092 return cnf 0093 0094 try: _cnfmerge = _tkinter._cnfmerge 0095 except AttributeError: pass 0096 0097 class Event: 0098 """Container for the properties of an event. 0099 0100 Instances of this type are generated if one of the following events occurs: 0101 0102 KeyPress, KeyRelease - for keyboard events 0103 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events 0104 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate, 0105 Colormap, Gravity, Reparent, Property, Destroy, Activate, 0106 Deactivate - for window events. 0107 0108 If a callback function for one of these events is registered 0109 using bind, bind_all, bind_class, or tag_bind, the callback is 0110 called with an Event as first argument. It will have the 0111 following attributes (in braces are the event types for which 0112 the attribute is valid): 0113 0114 serial - serial number of event 0115 num - mouse button pressed (ButtonPress, ButtonRelease) 0116 focus - whether the window has the focus (Enter, Leave) 0117 height - height of the exposed window (Configure, Expose) 0118 width - width of the exposed window (Configure, Expose) 0119 keycode - keycode of the pressed key (KeyPress, KeyRelease) 0120 state - state of the event as a number (ButtonPress, ButtonRelease, 0121 Enter, KeyPress, KeyRelease, 0122 Leave, Motion) 0123 state - state as a string (Visibility) 0124 time - when the event occurred 0125 x - x-position of the mouse 0126 y - y-position of the mouse 0127 x_root - x-position of the mouse on the screen 0128 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) 0129 y_root - y-position of the mouse on the screen 0130 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) 0131 char - pressed character (KeyPress, KeyRelease) 0132 send_event - see X/Windows documentation 0133 keysym - keysym of the the event as a string (KeyPress, KeyRelease) 0134 keysym_num - keysym of the event as a number (KeyPress, KeyRelease) 0135 type - type of the event as a number 0136 widget - widget in which the event occurred 0137 delta - delta of wheel movement (MouseWheel) 0138 """ 0139 pass 0140 0141 _support_default_root = 1 0142 _default_root = None 0143 0144 def NoDefaultRoot(): 0145 """Inhibit setting of default root window. 0146 0147 Call this function to inhibit that the first instance of 0148 Tk is used for windows without an explicit parent window. 0149 """ 0150 global _support_default_root 0151 _support_default_root = 0 0152 global _default_root 0153 _default_root = None 0154 del _default_root 0155 0156 def _tkerror(err): 0157 """Internal function.""" 0158 pass 0159 0160 def _exit(code='0'): 0161 """Internal function. Calling it will throw the exception SystemExit.""" 0162 raise SystemExit, code 0163 0164 _varnum = 0 0165 class Variable: 0166 """Class to define value holders for e.g. buttons. 0167 0168 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations 0169 that constrain the type of the value returned from get().""" 0170 _default = "" 0171 def __init__(self, master=None): 0172 """Construct a variable with an optional MASTER as master widget. 0173 The variable is named PY_VAR_number in Tcl. 0174 """ 0175 global _varnum 0176 if not master: 0177 master = _default_root 0178 self._master = master 0179 self._tk = master.tk 0180 self._name = 'PY_VAR' + repr(_varnum) 0181 _varnum = _varnum + 1 0182 self.set(self._default) 0183 def __del__(self): 0184 """Unset the variable in Tcl.""" 0185 self._tk.globalunsetvar(self._name) 0186 def __str__(self): 0187 """Return the name of the variable in Tcl.""" 0188 return self._name 0189 def set(self, value): 0190 """Set the variable to VALUE.""" 0191 return self._tk.globalsetvar(self._name, value) 0192 def get(self): 0193 """Return value of variable.""" 0194 return self._tk.globalgetvar(self._name) 0195 def trace_variable(self, mode, callback): 0196 """Define a trace callback for the variable. 0197 0198 MODE is one of "r", "w", "u" for read, write, undefine. 0199 CALLBACK must be a function which is called when 0200 the variable is read, written or undefined. 0201 0202 Return the name of the callback. 0203 """ 0204 cbname = self._master._register(callback) 0205 self._tk.call("trace", "variable", self._name, mode, cbname) 0206 return cbname 0207 trace = trace_variable 0208 def trace_vdelete(self, mode, cbname): 0209 """Delete the trace callback for a variable. 0210 0211 MODE is one of "r", "w", "u" for read, write, undefine. 0212 CBNAME is the name of the callback returned from trace_variable or trace. 0213 """ 0214 self._tk.call("trace", "vdelete", self._name, mode, cbname) 0215 self._master.deletecommand(cbname) 0216 def trace_vinfo(self): 0217 """Return all trace callback information.""" 0218 return map(self._tk.split, self._tk.splitlist( 0219 self._tk.call("trace", "vinfo", self._name))) 0220 0221 class StringVar(Variable): 0222 """Value holder for strings variables.""" 0223 _default = "" 0224 def __init__(self, master=None): 0225 """Construct a string variable. 0226 0227 MASTER can be given as master widget.""" 0228 Variable.__init__(self, master) 0229 0230 def get(self): 0231 """Return value of variable as string.""" 0232 value = self._tk.globalgetvar(self._name) 0233 if isinstance(value, basestring): 0234 return value 0235 return str(value) 0236 0237 class IntVar(Variable): 0238 """Value holder for integer variables.""" 0239 _default = 0 0240 def __init__(self, master=None): 0241 """Construct an integer variable. 0242 0243 MASTER can be given as master widget.""" 0244 Variable.__init__(self, master) 0245 0246 def set(self, value): 0247 """Set the variable to value, converting booleans to integers.""" 0248 if isinstance(value, bool): 0249 value = int(value) 0250 return Variable.set(self, value) 0251 0252 def get(self): 0253 """Return the value of the variable as an integer.""" 0254 return getint(self._tk.globalgetvar(self._name)) 0255 0256 class DoubleVar(Variable): 0257 """Value holder for float variables.""" 0258 _default = 0.0 0259 def __init__(self, master=None): 0260 """Construct a float variable. 0261 0262 MASTER can be given as a master widget.""" 0263 Variable.__init__(self, master) 0264 0265 def get(self): 0266 """Return the value of the variable as a float.""" 0267 return getdouble(self._tk.globalgetvar(self._name)) 0268 0269 class BooleanVar(Variable): 0270 """Value holder for boolean variables.""" 0271 _default = "false" 0272 def __init__(self, master=None): 0273 """Construct a boolean variable. 0274 0275 MASTER can be given as a master widget.""" 0276 Variable.__init__(self, master) 0277 0278 def get(self): 0279 """Return the value of the variable as a bool.""" 0280 return self._tk.getboolean(self._tk.globalgetvar(self._name)) 0281 0282 def mainloop(n=0): 0283 """Run the main loop of Tcl.""" 0284 _default_root.tk.mainloop(n) 0285 0286 getint = int 0287 0288 getdouble = float 0289 0290 def getboolean(s): 0291 """Convert true and false to integer values 1 and 0.""" 0292 return _default_root.tk.getboolean(s) 0293 0294 # Methods defined on both toplevel and interior widgets 0295 class Misc: 0296 """Internal class. 0297 0298 Base class which defines methods common for interior widgets.""" 0299 0300 # XXX font command? 0301 _tclCommands = None 0302 def destroy(self): 0303 """Internal function. 0304 0305 Delete all Tcl commands created for 0306 this widget in the Tcl interpreter.""" 0307 if self._tclCommands is not None: 0308 for name in self._tclCommands: 0309 #print '- Tkinter: deleted command', name 0310 self.tk.deletecommand(name) 0311 self._tclCommands = None 0312 def deletecommand(self, name): 0313 """Internal function. 0314 0315 Delete the Tcl command provided in NAME.""" 0316 #print '- Tkinter: deleted command', name 0317 self.tk.deletecommand(name) 0318 try: 0319 self._tclCommands.remove(name) 0320 except ValueError: 0321 pass 0322 def tk_strictMotif(self, boolean=None): 0323 """Set Tcl internal variable, whether the look and feel 0324 should adhere to Motif. 0325 0326 A parameter of 1 means adhere to Motif (e.g. no color 0327 change if mouse passes over slider). 0328 Returns the set value.""" 0329 return self.tk.getboolean(self.tk.call( 0330 'set', 'tk_strictMotif', boolean)) 0331 def tk_bisque(self): 0332 """Change the color scheme to light brown as used in Tk 3.6 and before.""" 0333 self.tk.call('tk_bisque') 0334 def tk_setPalette(self, *args, **kw): 0335 """Set a new color scheme for all widget elements. 0336 0337 A single color as argument will cause that all colors of Tk 0338 widget elements are derived from this. 0339 Alternatively several keyword parameters and its associated 0340 colors can be given. The following keywords are valid: 0341 activeBackground, foreground, selectColor, 0342 activeForeground, highlightBackground, selectBackground, 0343 background, highlightColor, selectForeground, 0344 disabledForeground, insertBackground, troughColor.""" 0345 self.tk.call(('tk_setPalette',) 0346 + _flatten(args) + _flatten(kw.items())) 0347 def tk_menuBar(self, *args): 0348 """Do not use. Needed in Tk 3.6 and earlier.""" 0349 pass # obsolete since Tk 4.0 0350 def wait_variable(self, name='PY_VAR'): 0351 """Wait until the variable is modified. 0352 0353 A parameter of type IntVar, StringVar, DoubleVar or 0354 BooleanVar must be given.""" 0355 self.tk.call('tkwait', 'variable', name) 0356 waitvar = wait_variable # XXX b/w compat 0357 def wait_window(self, window=None): 0358 """Wait until a WIDGET is destroyed. 0359 0360 If no parameter is given self is used.""" 0361 if window is None: 0362 window = self 0363 self.tk.call('tkwait', 'window', window._w) 0364 def wait_visibility(self, window=None): 0365 """Wait until the visibility of a WIDGET changes 0366 (e.g. it appears). 0367 0368 If no parameter is given self is used.""" 0369 if window is None: 0370 window = self 0371 self.tk.call('tkwait', 'visibility', window._w) 0372 def setvar(self, name='PY_VAR', value='1'): 0373 """Set Tcl variable NAME to VALUE.""" 0374 self.tk.setvar(name, value) 0375 def getvar(self, name='PY_VAR'): 0376 """Return value of Tcl variable NAME.""" 0377 return self.tk.getvar(name) 0378 getint = int 0379 getdouble = float 0380 def getboolean(self, s): 0381 """Return a boolean value for Tcl boolean values true and false given as parameter.""" 0382 return self.tk.getboolean(s) 0383 def focus_set(self): 0384 """Direct input focus to this widget. 0385 0386 If the application currently does not have the focus 0387 this widget will get the focus if the application gets 0388 the focus through the window manager.""" 0389 self.tk.call('focus', self._w) 0390 focus = focus_set # XXX b/w compat? 0391 def focus_force(self): 0392 """Direct input focus to this widget even if the 0393 application does not have the focus. Use with 0394 caution!""" 0395 self.tk.call('focus', '-force', self._w) 0396 def focus_get(self): 0397 """Return the widget which has currently the focus in the 0398 application. 0399 0400 Use focus_displayof to allow working with several 0401 displays. Return None if application does not have 0402 the focus.""" 0403 name = self.tk.call('focus') 0404 if name == 'none' or not name: return None 0405 return self._nametowidget(name) 0406 def focus_displayof(self): 0407 """Return the widget which has currently the focus on the 0408 display where this widget is located. 0409 0410 Return None if the application does not have the focus.""" 0411 name = self.tk.call('focus', '-displayof', self._w) 0412 if name == 'none' or not name: return None 0413 return self._nametowidget(name) 0414 def focus_lastfor(self): 0415 """Return the widget which would have the focus if top level 0416 for this widget gets the focus from the window manager.""" 0417 name = self.tk.call('focus', '-lastfor', self._w) 0418 if name == 'none' or not name: return None 0419 return self._nametowidget(name) 0420 def tk_focusFollowsMouse(self): 0421 """The widget under mouse will get automatically focus. Can not 0422 be disabled easily.""" 0423 self.tk.call('tk_focusFollowsMouse') 0424 def tk_focusNext(self): 0425 """Return the next widget in the focus order which follows 0426 widget which has currently the focus. 0427 0428 The focus order first goes to the next child, then to 0429 the children of the child recursively and then to the 0430 next sibling which is higher in the stacking order. A 0431 widget is omitted if it has the takefocus resource set 0432 to 0.""" 0433 name = self.tk.call('tk_focusNext', self._w) 0434 if not name: return None 0435 return self._nametowidget(name) 0436 def tk_focusPrev(self): 0437 """Return previous widget in the focus order. See tk_focusNext for details.""" 0438 name = self.tk.call('tk_focusPrev', self._w) 0439 if not name: return None 0440 return self._nametowidget(name) 0441 def after(self, ms, func=None, *args): 0442 """Call function once after given time. 0443 0444 MS specifies the time in milliseconds. FUNC gives the 0445 function which shall be called. Additional parameters 0446 are given as parameters to the function call. Return 0447 identifier to cancel scheduling with after_cancel.""" 0448 if not func: 0449 # I'd rather use time.sleep(ms*0.001) 0450 self.tk.call('after', ms) 0451 else: 0452 # XXX Disgusting hack to clean up after calling func 0453 tmp = [] 0454 def callit(func=func, args=args, self=self, tmp=tmp): 0455 try: 0456 func(*args) 0457 finally: 0458 try: 0459 self.deletecommand(tmp[0]) 0460 except TclError: 0461 pass 0462 name = self._register(callit) 0463 tmp.append(name) 0464 return self.tk.call('after', ms, name) 0465 def after_idle(self, func, *args): 0466 """Call FUNC once if the Tcl main loop has no event to 0467 process. 0468 0469 Return an identifier to cancel the scheduling with 0470 after_cancel.""" 0471 return self.after('idle', func, *args) 0472 def after_cancel(self, id): 0473 """Cancel scheduling of function identified with ID. 0474 0475 Identifier returned by after or after_idle must be 0476 given as first parameter.""" 0477 try: 0478 data = self.tk.call('after', 'info', id) 0479 # In Tk 8.3, splitlist returns: (script, type) 0480 # In Tk 8.4, splitlist may return (script, type) or (script,) 0481 script = self.tk.splitlist(data)[0] 0482 self.deletecommand(script) 0483 except TclError: 0484 pass 0485 self.tk.call('after', 'cancel', id) 0486 def bell(self, displayof=0): 0487 """Ring a display's bell.""" 0488 self.tk.call(('bell',) + self._displayof(displayof)) 0489 # Clipboard handling: 0490 def clipboard_clear(self, **kw): 0491 """Clear the data in the Tk clipboard. 0492 0493 A widget specified for the optional displayof keyword 0494 argument specifies the target display.""" 0495 if not kw.has_key('displayof'): kw['displayof'] = self._w 0496 self.tk.call(('clipboard', 'clear') + self._options(kw)) 0497 def clipboard_append(self, string, **kw): 0498 """Append STRING to the Tk clipboard. 0499 0500 A widget specified at the optional displayof keyword 0501 argument specifies the target display. The clipboard 0502 can be retrieved with selection_get.""" 0503 if not kw.has_key('displayof'): kw['displayof'] = self._w 0504 self.tk.call(('clipboard', 'append') + self._options(kw) 0505 + ('--', string)) 0506 # XXX grab current w/o window argument 0507 def grab_current(self): 0508 """Return widget which has currently the grab in this application 0509 or None.""" 0510 name = self.tk.call('grab', 'current', self._w) 0511 if not name: return None 0512 return self._nametowidget(name) 0513 def grab_release(self): 0514 """Release grab for this widget if currently set.""" 0515 self.tk.call('grab', 'release', self._w) 0516 def grab_set(self): 0517 """Set grab for this widget. 0518 0519 A grab directs all events to this and descendant 0520 widgets in the application.""" 0521 self.tk.call('grab', 'set', self._w) 0522 def grab_set_global(self): 0523 """Set global grab for this widget. 0524 0525 A global grab directs all events to this and 0526 descendant widgets on the display. Use with caution - 0527 other applications do not get events anymore.""" 0528 self.tk.call('grab', 'set', '-global', self._w) 0529 def grab_status(self): 0530 """Return None, "local" or "global" if this widget has 0531 no, a local or a global grab.""" 0532 status = self.tk.call('grab', 'status', self._w) 0533 if status == 'none': status = None 0534 return status 0535 def lower(self, belowThis=None): 0536 """Lower this widget in the stacking order.""" 0537 self.tk.call('lower', self._w, belowThis) 0538 def option_add(self, pattern, value, priority = None): 0539 """Set a VALUE (second parameter) for an option 0540 PATTERN (first parameter). 0541 0542 An optional third parameter gives the numeric priority 0543 (defaults to 80).""" 0544 self.tk.call('option', 'add', pattern, value, priority) 0545 def option_clear(self): 0546 """Clear the option database. 0547 0548 It will be reloaded if option_add is called.""" 0549 self.tk.call('option', 'clear') 0550 def option_get(self, name, className): 0551 """Return the value for an option NAME for this widget 0552 with CLASSNAME. 0553 0554 Values with higher priority override lower values.""" 0555 return self.tk.call('option', 'get', self._w, name, className) 0556 def option_readfile(self, fileName, priority = None): 0557 """Read file FILENAME into the option database. 0558 0559 An optional second parameter gives the numeric 0560 priority.""" 0561 self.tk.call('option', 'readfile', fileName, priority) 0562 def selection_clear(self, **kw): 0563 """Clear the current X selection.""" 0564 if not kw.has_key('displayof'): kw['displayof'] = self._w 0565 self.tk.call(('selection', 'clear') + self._options(kw)) 0566 def selection_get(self, **kw): 0567 """Return the contents of the current X selection. 0568 0569 A keyword parameter selection specifies the name of 0570 the selection and defaults to PRIMARY. A keyword 0571 parameter displayof specifies a widget on the display 0572 to use.""" 0573 if not kw.has_key('displayof'): kw['displayof'] = self._w 0574 return self.tk.call(('selection', 'get') + self._options(kw)) 0575 def selection_handle(self, command, **kw): 0576 """Specify a function COMMAND to call if the X 0577 selection owned by this widget is queried by another 0578 application. 0579 0580 This function must return the contents of the 0581 selection. The function will be called with the 0582 arguments OFFSET and LENGTH which allows the chunking 0583 of very long selections. The following keyword 0584 parameters can be provided: 0585 selection - name of the selection (default PRIMARY), 0586 type - type of the selection (e.g. STRING, FILE_NAME).""" 0587 name = self._register(command) 0588 self.tk.call(('selection', 'handle') + self._options(kw) 0589 + (self._w, name)) 0590 def selection_own(self, **kw): 0591 """Become owner of X selection. 0592 0593 A keyword parameter selection specifies the name of 0594 the selection (default PRIMARY).""" 0595 self.tk.call(('selection', 'own') + 0596 self._options(kw) + (self._w,)) 0597 def selection_own_get(self, **kw): 0598 """Return owner of X selection. 0599 0600 The following keyword parameter can 0601 be provided: 0602 selection - name of the selection (default PRIMARY), 0603 type - type of the selection (e.g. STRING, FILE_NAME).""" 0604 if not kw.has_key('displayof'): kw['displayof'] = self._w 0605 name = self.tk.call(('selection', 'own') + self._options(kw)) 0606 if not name: return None 0607 return self._nametowidget(name) 0608 def send(self, interp, cmd, *args): 0609 """Send Tcl command CMD to different interpreter INTERP to be executed.""" 0610 return self.tk.call(('send', interp, cmd) + args) 0611 def lower(self, belowThis=None): 0612 """Lower this widget in the stacking order.""" 0613 self.tk.call('lower', self._w, belowThis) 0614 def tkraise(self, aboveThis=None): 0615 """Raise this widget in the stacking order.""" 0616 self.tk.call('raise', self._w, aboveThis) 0617 lift = tkraise 0618 def colormodel(self, value=None): 0619 """Useless. Not implemented in Tk.""" 0620 return self.tk.call('tk', 'colormodel', self._w, value) 0621 def winfo_atom(self, name, displayof=0): 0622 """Return integer which represents atom NAME.""" 0623 args = ('winfo', 'atom') + self._displayof(displayof) + (name,) 0624 return getint(self.tk.call(args)) 0625 def winfo_atomname(self, id, displayof=0): 0626 """Return name of atom with identifier ID.""" 0627 args = ('winfo', 'atomname') \ 0628 + self._displayof(displayof) + (id,) 0629 return self.tk.call(args) 0630 def winfo_cells(self): 0631 """Return number of cells in the colormap for this widget.""" 0632 return getint( 0633 self.tk.call('winfo', 'cells', self._w)) 0634 def winfo_children(self): 0635 """Return a list of all widgets which are children of this widget.""" 0636 result = [] 0637 for child in self.tk.splitlist( 0638 self.tk.call('winfo', 'children', self._w)): 0639 try: 0640 # Tcl sometimes returns extra windows, e.g. for 0641 # menus; those need to be skipped 0642 result.append(self._nametowidget(child)) 0643 except KeyError: 0644 pass 0645 return result 0646 0647 def winfo_class(self): 0648 """Return window class name of this widget.""" 0649 return self.tk.call('winfo', 'class', self._w) 0650 def winfo_colormapfull(self): 0651 """Return true if at the last color request the colormap was full.""" 0652 return self.tk.getboolean( 0653 self.tk.call('winfo', 'colormapfull', self._w)) 0654 def winfo_containing(self, rootX, rootY, displayof=0): 0655 """Return the widget which is at the root coordinates ROOTX, ROOTY.""" 0656 args = ('winfo', 'containing') \ 0657 + self._displayof(displayof) + (rootX, rootY) 0658 name = self.tk.call(args) 0659 if not name: return None 0660 return self._nametowidget(name) 0661 def winfo_depth(self): 0662 """Return the number of bits per pixel.""" 0663 return getint(self.tk.call('winfo', 'depth', self._w)) 0664 def winfo_exists(self): 0665 """Return true if this widget exists.""" 0666 return getint( 0667 self.tk.call('winfo', 'exists', self._w)) 0668 def winfo_fpixels(self, number): 0669 """Return the number of pixels for the given distance NUMBER 0670 (e.g. "3c") as float.""" 0671 return getdouble(self.tk.call( 0672 'winfo', 'fpixels', self._w, number)) 0673 def winfo_geometry(self): 0674 """Return geometry string for this widget in the form "widthxheight+X+Y".""" 0675 return self.tk.call('winfo', 'geometry', self._w) 0676 def winfo_height(self): 0677 """Return height of this widget.""" 0678 return getint( 0679 self.tk.call('winfo', 'height', self._w)) 0680 def winfo_id(self): 0681 """Return identifier ID for this widget.""" 0682 return self.tk.getint( 0683 self.tk.call('winfo', 'id', self._w)) 0684 def winfo_interps(self, displayof=0): 0685 """Return the name of all Tcl interpreters for this display.""" 0686 args = ('winfo', 'interps') + self._displayof(displayof) 0687 return self.tk.splitlist(self.tk.call(args)) 0688 def winfo_ismapped(self): 0689 """Return true if this widget is mapped.""" 0690 return getint( 0691 self.tk.call('winfo', 'ismapped', self._w)) 0692 def winfo_manager(self): 0693 """Return the window mananger name for this widget.""" 0694 return self.tk.call('winfo', 'manager', self._w) 0695 def winfo_name(self): 0696 """Return the name of this widget.""" 0697 return self.tk.call('winfo', 'name', self._w) 0698 def winfo_parent(self): 0699 """Return the name of the parent of this widget.""" 0700 return self.tk.call('winfo', 'parent', self._w) 0701 def winfo_pathname(self, id, displayof=0): 0702 """Return the pathname of the widget given by ID.""" 0703 args = ('winfo', 'pathname') \ 0704 + self._displayof(displayof) + (id,) 0705 return self.tk.call(args) 0706 def winfo_pixels(self, number): 0707 """Rounded integer value of winfo_fpixels.""" 0708 return getint( 0709 self.tk.call('winfo', 'pixels', self._w, number)) 0710 def winfo_pointerx(self): 0711 """Return the x coordinate of the pointer on the root window.""" 0712 return getint( 0713 self.tk.call('winfo', 'pointerx', self._w)) 0714 def winfo_pointerxy(self): 0715 """Return a tuple of x and y coordinates of the pointer on the root window.""" 0716 return self._getints( 0717 self.tk.call('winfo', 'pointerxy', self._w)) 0718 def winfo_pointery(self): 0719 """Return the y coordinate of the pointer on the root window.""" 0720 return getint( 0721 self.tk.call('winfo', 'pointery', self._w)) 0722 def winfo_reqheight(self): 0723 """Return requested height of this widget.""" 0724 return getint( 0725 self.tk.call('winfo', 'reqheight', self._w)) 0726 def winfo_reqwidth(self): 0727 """Return requested width of this widget.""" 0728 return getint( 0729 self.tk.call('winfo', 'reqwidth', self._w)) 0730 def winfo_rgb(self, color): 0731 """Return tuple of decimal values for red, green, blue for 0732 COLOR in this widget.""" 0733 return self._getints( 0734 self.tk.call('winfo', 'rgb', self._w, color)) 0735 def winfo_rootx(self): 0736 """Return x coordinate of upper left corner of this widget on the 0737 root window.""" 0738 return getint( 0739 self.tk.call('winfo', 'rootx', self._w)) 0740 def winfo_rooty(self): 0741 """Return y coordinate of upper left corner of this widget on the 0742 root window.""" 0743 return getint( 0744 self.tk.call('winfo', 'rooty', self._w)) 0745 def winfo_screen(self): 0746 """Return the screen name of this widget.""" 0747 return self.tk.call('winfo', 'screen', self._w) 0748 def winfo_screencells(self): 0749 """Return the number of the cells in the colormap of the screen 0750 of this widget.""" 0751 return getint( 0752 self.tk.call('winfo', 'screencells', self._w)) 0753 def winfo_screendepth(self): 0754 """Return the number of bits per pixel of the root window of the 0755 screen of this widget.""" 0756 return getint( 0757 self.tk.call('winfo', 'screendepth', self._w)) 0758 def winfo_screenheight(self): 0759 """Return the number of pixels of the height of the screen of this widget 0760 in pixel.""" 0761 return getint( 0762 self.tk.call('winfo', 'screenheight', self._w)) 0763 def winfo_screenmmheight(self): 0764 """Return the number of pixels of the height of the screen of 0765 this widget in mm.""" 0766 return getint( 0767 self.tk.call('winfo', 'screenmmheight', self._w)) 0768 def winfo_screenmmwidth(self): 0769 """Return the number of pixels of the width of the screen of 0770 this widget in mm.""" 0771 return getint( 0772 self.tk.call('winfo', 'screenmmwidth', self._w)) 0773 def winfo_screenvisual(self): 0774 """Return one of the strings directcolor, grayscale, pseudocolor, 0775 staticcolor, staticgray, or truecolor for the default 0776 colormodel of this screen.""" 0777 return self.tk.call('winfo', 'screenvisual', self._w) 0778 def winfo_screenwidth(self): 0779 """Return the number of pixels of the width of the screen of 0780 this widget in pixel.""" 0781 return getint( 0782 self.tk.call('winfo', 'screenwidth', self._w)) 0783 def winfo_server(self): 0784 """Return information of the X-Server of the screen of this widget in 0785 the form "XmajorRminor vendor vendorVersion".""" 0786 return self.tk.call('winfo', 'server', self._w) 0787 def winfo_toplevel(self): 0788 """Return the toplevel widget of this widget.""" 0789 return self._nametowidget(self.tk.call( 0790 'winfo', 'toplevel', self._w)) 0791 def winfo_viewable(self): 0792 """Return true if the widget and all its higher ancestors are mapped.""" 0793 return getint( 0794 self.tk.call('winfo', 'viewable', self._w)) 0795 def winfo_visual(self): 0796 """Return one of the strings directcolor, grayscale, pseudocolor, 0797 staticcolor, staticgray, or truecolor for the 0798 colormodel of this widget.""" 0799 return self.tk.call('winfo', 'visual', self._w) 0800 def winfo_visualid(self): 0801 """Return the X identifier for the visual for this widget.""" 0802 return self.tk.call('winfo', 'visualid', self._w) 0803 def winfo_visualsavailable(self, includeids=0): 0804 """Return a list of all visuals available for the screen 0805 of this widget. 0806 0807 Each item in the list consists of a visual name (see winfo_visual), a 0808 depth and if INCLUDEIDS=1 is given also the X identifier.""" 0809 data = self.tk.split( 0810 self.tk.call('winfo', 'visualsavailable', self._w, 0811 includeids and 'includeids' or None)) 0812 if type(data) is StringType: 0813 data = [self.tk.split(data)] 0814 return map(self.__winfo_parseitem, data) 0815 def __winfo_parseitem(self, t): 0816 """Internal function.""" 0817 return t[:1] + tuple(map(self.__winfo_getint, t[1:])) 0818 def __winfo_getint(self, x): 0819 """Internal function.""" 0820 return int(x, 0) 0821 def winfo_vrootheight(self): 0822 """Return the height of the virtual root window associated with this 0823 widget in pixels. If there is no virtual root window return the 0824 height of the screen.""" 0825 return getint( 0826 self.tk.call('winfo', 'vrootheight', self._w)) 0827 def winfo_vrootwidth(self): 0828 """Return the width of the virtual root window associated with this 0829 widget in pixel. If there is no virtual root window return the 0830 width of the screen.""" 0831 return getint( 0832 self.tk.call('winfo', 'vrootwidth', self._w)) 0833 def winfo_vrootx(self): 0834 """Return the x offset of the virtual root relative to the root 0835 window of the screen of this widget.""" 0836 return getint( 0837 self.tk.call('winfo', 'vrootx', self._w)) 0838 def winfo_vrooty(self): 0839 """Return the y offset of the virtual root relative to the root 0840 window of the screen of this widget.""" 0841 return getint( 0842 self.tk.call('winfo', 'vrooty', self._w)) 0843 def winfo_width(self): 0844 """Return the width of this widget.""" 0845 return getint( 0846 self.tk.call('winfo', 'width', self._w)) 0847 def winfo_x(self): 0848 """Return the x coordinate of the upper left corner of this widget 0849 in the parent.""" 0850 return getint( 0851 self.tk.call('winfo', 'x', self._w)) 0852 def winfo_y(self): 0853 """Return the y coordinate of the upper left corner of this widget 0854 in the parent.""" 0855 return getint( 0856 self.tk.call('winfo', 'y', self._w)) 0857 def update(self): 0858 """Enter event loop until all pending events have been processed by Tcl.""" 0859 self.tk.call('update') 0860 def update_idletasks(self): 0861 """Enter event loop until all idle callbacks have been called. This 0862 will update the display of windows but not process events caused by 0863 the user.""" 0864 self.tk.call('update', 'idletasks') 0865 def bindtags(self, tagList=None): 0866 """Set or get the list of bindtags for this widget. 0867 0868 With no argument return the list of all bindtags associated with 0869 this widget. With a list of strings as argument the bindtags are 0870 set to this list. The bindtags determine in which order events are 0871 processed (see bind).""" 0872 if tagList is None: 0873 return self.tk.splitlist( 0874 self.tk.call('bindtags', self._w)) 0875 else: 0876 self.tk.call('bindtags', self._w, tagList) 0877 def _bind(self, what, sequence, func, add, needcleanup=1): 0878 """Internal function.""" 0879 if type(func) is StringType: 0880 self.tk.call(what + (sequence, func)) 0881 elif func: 0882 funcid = self._register(func, self._substitute, 0883 needcleanup) 0884 cmd = ('%sif {"[%s %s]" == "break"} break\n' 0885 % 0886 (add and '+' or '', 0887 funcid, self._subst_format_str)) 0888 self.tk.call(what + (sequence, cmd)) 0889 return funcid 0890 elif sequence: 0891 return self.tk.call(what + (sequence,)) 0892 else: 0893 return self.tk.splitlist(self.tk.call(what)) 0894 def bind(self, sequence=None, func=None, add=None): 0895 """Bind to this widget at event SEQUENCE a call to function FUNC. 0896 0897 SEQUENCE is a string of concatenated event 0898 patterns. An event pattern is of the form 0899 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one 0900 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, 0901 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3, 0902 B3, Alt, Button4, B4, Double, Button5, B5 Triple, 0903 Mod1, M1. TYPE is one of Activate, Enter, Map, 0904 ButtonPress, Button, Expose, Motion, ButtonRelease 0905 FocusIn, MouseWheel, Circulate, FocusOut, Property, 0906 Colormap, Gravity Reparent, Configure, KeyPress, Key, 0907 Unmap, Deactivate, KeyRelease Visibility, Destroy, 0908 Leave and DETAIL is the button number for ButtonPress, 0909 ButtonRelease and DETAIL is the Keysym for KeyPress and 0910 KeyRelease. Examples are 0911 <Control-Button-1> for pressing Control and mouse button 1 or 0912 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted). 0913 An event pattern can also be a virtual event of the form 0914 <<AString>> where AString can be arbitrary. This 0915 event can be generated by event_generate. 0916 If events are concatenated they must appear shortly 0917 after each other. 0918 0919 FUNC will be called if the event sequence occurs with an 0920 instance of Event as argument. If the return value of FUNC is 0921 "break" no further bound function is invoked. 0922 0923 An additional boolean parameter ADD specifies whether FUNC will 0924 be called additionally to the other bound function or whether 0925 it will replace the previous function. 0926 0927 Bind will return an identifier to allow deletion of the bound function with 0928 unbind without memory leak. 0929 0930 If FUNC or SEQUENCE is omitted the bound function or list 0931 of bound events are returned.""" 0932 0933 return self._bind(('bind', self._w), sequence, func, add) 0934 def unbind(self, sequence, funcid=None): 0935 """Unbind for this widget for event SEQUENCE the 0936 function identified with FUNCID.""" 0937 self.tk.call('bind', self._w, sequence, '') 0938 if funcid: 0939 self.deletecommand(funcid) 0940 def bind_all(self, sequence=None, func=None, add=None): 0941 """Bind to all widgets at an event SEQUENCE a call to function FUNC. 0942 An additional boolean parameter ADD specifies whether FUNC will 0943 be called additionally to the other bound function or whether 0944 it will replace the previous function. See bind for the return value.""" 0945 return self._bind(('bind', 'all'), sequence, func, add, 0) 0946 def unbind_all(self, sequence): 0947 """Unbind for all widgets for event SEQUENCE all functions.""" 0948 self.tk.call('bind', 'all' , sequence, '') 0949 def bind_class(self, className, sequence=None, func=None, add=None): 0950 0951 """Bind to widgets with bindtag CLASSNAME at event 0952 SEQUENCE a call of function FUNC. An additional 0953 boolean parameter ADD specifies whether FUNC will be 0954 called additionally to the other bound function or 0955 whether it will replace the previous function. See bind for 0956 the return value.""" 0957 0958 return self._bind(('bind', className), sequence, func, add, 0) 0959 def unbind_class(self, className, sequence): 0960 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE 0961 all functions.""" 0962 self.tk.call('bind', className , sequence, '') 0963 def mainloop(self, n=0): 0964 """Call the mainloop of Tk.""" 0965 self.tk.mainloop(n) 0966 def quit(self): 0967 """Quit the Tcl interpreter. All widgets will be destroyed.""" 0968 self.tk.quit() 0969 def _getints(self, string): 0970 """Internal function.""" 0971 if string: 0972 return tuple(map(getint, self.tk.splitlist(string))) 0973 def _getdoubles(self, string): 0974 """Internal function.""" 0975 if string: 0976 return tuple(map(getdouble, self.tk.splitlist(string))) 0977 def _getboolean(self, string): 0978 """Internal function.""" 0979 if string: 0980 return self.tk.getboolean(string) 0981 def _displayof(self, displayof): 0982 """Internal function.""" 0983 if displayof: 0984 return ('-displayof', displayof) 0985 if displayof is None: 0986 return ('-displayof', self._w) 0987 return () 0988 def _options(self, cnf, kw = None): 0989 """Internal function.""" 0990 if kw: 0991 cnf = _cnfmerge((cnf, kw)) 0992 else: 0993 cnf = _cnfmerge(cnf) 0994 res = () 0995 for k, v in cnf.items(): 0996 if v is not None: 0997 if k[-1] == '_': k = k[:-1] 0998 if callable(v): 0999 v = self._register(v) 1000 res = res + ('-'+k, v) 1001 return res 1002 def nametowidget(self, name): 1003 """Return the Tkinter instance of a widget identified by 1004 its Tcl name NAME.""" 1005 w = self 1006 if name[0] == '.': 1007 w = w._root() 1008 name = name[1:] 1009 while name: 1010 i = name.find('.') 1011 if i >= 0: 1012 name, tail = name[:i], name[i+1:] 1013 else: 1014 tail = '' 1015 w = w.children[name] 1016 name = tail 1017 return w 1018 _nametowidget = nametowidget 1019 def _register(self, func, subst=None, needcleanup=1): 1020 """Return a newly created Tcl function. If this 1021 function is called, the Python function FUNC will 1022 be executed. An optional function SUBST can 1023 be given which will be executed before FUNC.""" 1024 f = CallWrapper(func, subst, self).__call__ 1025 name = repr(id(f)) 1026 try: 1027 func = func.im_func 1028 except AttributeError: 1029 pass 1030 try: 1031 name = name + func.__name__ 1032 except AttributeError: 1033 pass 1034 self.tk.createcommand(name, f) 1035 if needcleanup: 1036 if self._tclCommands is None: 1037 self._tclCommands = [] 1038 self._tclCommands.append(name) 1039 #print '+ Tkinter created command', name 1040 return name 1041 register = _register 1042 def _root(self): 1043 """Internal function.""" 1044 w = self 1045 while w.master: w = w.master 1046 return w 1047 _subst_format = ('%#', '%b', '%f', '%h', '%k', 1048 '%s', '%t', '%w', '%x', '%y', 1049 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D') 1050 _subst_format_str = " ".join(_subst_format) 1051 def _substitute(self, *args): 1052 """Internal function.""" 1053 if len(args) != len(self._subst_format): return args 1054 getboolean = self.tk.getboolean 1055 1056 getint = int 1057 def getint_event(s): 1058 """Tk changed behavior in 8.4.2, returning "??" rather more often.""" 1059 try: 1060 return int(s) 1061 except ValueError: 1062 return s 1063 1064 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args 1065 # Missing: (a, c, d, m, o, v, B, R) 1066 e = Event() 1067 # serial field: valid vor all events 1068 # number of button: ButtonPress and ButtonRelease events only 1069 # height field: Configure, ConfigureRequest, Create, 1070 # ResizeRequest, and Expose events only 1071 # keycode field: KeyPress and KeyRelease events only 1072 # time field: "valid for events that contain a time field" 1073 # width field: Configure, ConfigureRequest, Create, ResizeRequest, 1074 # and Expose events only 1075 # x field: "valid for events that contain a x field" 1076 # y field: "valid for events that contain a y field" 1077 # keysym as decimal: KeyPress and KeyRelease events only 1078 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress, 1079 # KeyRelease,and Motion events 1080 e.serial = getint(nsign) 1081 e.num = getint_event(b) 1082 try: e.focus = getboolean(f) 1083 except TclError: pass 1084 e.height = getint_event(h) 1085 e.keycode = getint_event(k) 1086 e.state = getint_event(s) 1087 e.time = getint_event(t) 1088 e.width = getint_event(w) 1089 e.x = getint_event(x) 1090 e.y = getint_event(y) 1091 e.char = A 1092 try: e.send_event = getboolean(E) 1093 except TclError: pass 1094 e.keysym = K 1095 e.keysym_num = getint_event(N) 1096 e.type = T 1097 try: 1098 e.widget = self._nametowidget(W) 1099 except KeyError: 1100 e.widget = W 1101 e.x_root = getint_event(X) 1102 e.y_root = getint_event(Y) 1103 try: 1104 e.delta = getint(D) 1105 except ValueError: 1106 e.delta = 0 1107 return (e,) 1108 def _report_exception(self): 1109 """Internal function.""" 1110 import sys 1111 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback 1112 root = self._root() 1113 root.report_callback_exception(exc, val, tb) 1114 def _configure(self, cmd, cnf, kw): 1115 """Internal function.""" 1116 if kw: 1117 cnf = _cnfmerge((cnf, kw)) 1118 elif cnf: 1119 cnf = _cnfmerge(cnf) 1120 if cnf is None: 1121 cnf = {} 1122 for x in self.tk.split( 1123 self.tk.call(_flatten((self._w, cmd)))): 1124 cnf[x[0][1:]] = (x[0][1:],) + x[1:] 1125 return cnf 1126 if type(cnf) is StringType: 1127 x = self.tk.split( 1128 self.tk.call(_flatten((self._w, cmd, '-'+cnf)))) 1129 return (x[0][1:],) + x[1:] 1130 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) 1131 # These used to be defined in Widget: 1132 def configure(self, cnf=None, **kw): 1133 """Configure resources of a widget. 1134 1135 The values for resources are specified as keyword 1136 arguments. To get an overview about 1137 the allowed keyword arguments call the method keys. 1138 """ 1139 return self._configure('configure', cnf, kw) 1140 config = configure 1141 def cget(self, key): 1142 """Return the resource value for a KEY given as string.""" 1143 return self.tk.call(self._w, 'cget', '-' + key) 1144 __getitem__ = cget 1145 def __setitem__(self, key, value): 1146 self.configure({key: value}) 1147 def keys(self): 1148 """Return a list of all resource names of this widget.""" 1149 return map(lambda x: x[0][1:], 1150 self.tk.split(self.tk.call(self._w, 'configure'))) 1151 def __str__(self): 1152 """Return the window path name of this widget.""" 1153 return self._w 1154 # Pack methods that apply to the master 1155 _noarg_ = ['_noarg_'] 1156 def pack_propagate(self, flag=_noarg_): 1157 """Set or get the status for propagation of geometry information. 1158 1159 A boolean argument specifies whether the geometry information 1160 of the slaves will determine the size of this widget. If no argument 1161 is given the current setting will be returned. 1162 """ 1163 if flag is Misc._noarg_: 1164 return self._getboolean(self.tk.call( 1165 'pack', 'propagate', self._w)) 1166 else: 1167 self.tk.call('pack', 'propagate', self._w, flag) 1168 propagate = pack_propagate 1169 def pack_slaves(self): 1170 """Return a list of all slaves of this widget 1171 in its packing order.""" 1172 return map(self._nametowidget, 1173 self.tk.splitlist( 1174 self.tk.call('pack', 'slaves', self._w))) 1175 slaves = pack_slaves 1176 # Place method that applies to the master 1177 def place_slaves(self): 1178 """Return a list of all slaves of this widget 1179 in its packing order.""" 1180 return map(self._nametowidget, 1181 self.tk.splitlist( 1182 self.tk.call( 1183 'place', 'slaves', self._w))) 1184 # Grid methods that apply to the master 1185 def grid_bbox(self, column=None, row=None, col2=None, row2=None): 1186 """Return a tuple of integer coordinates for the bounding 1187 box of this widget controlled by the geometry manager grid. 1188 1189 If COLUMN, ROW is given the bounding box applies from 1190 the cell with row and column 0 to the specified 1191 cell. If COL2 and ROW2 are given the bounding box 1192 starts at that cell. 1193 1194 The returned integers specify the offset of the upper left 1195 corner in the master widget and the width and height. 1196 """ 1197 args = ('grid', 'bbox', self._w) 1198 if column is not None and row is not None: 1199 args = args + (column, row) 1200 if col2 is not None and row2 is not None: 1201 args = args + (col2, row2) 1202 return self._getints(self.tk.call(*args)) or None 1203 1204 bbox = grid_bbox 1205 def _grid_configure(self, command, index, cnf, kw): 1206 """Internal function.""" 1207 if type(cnf) is StringType and not kw: 1208 if cnf[-1:] == '_': 1209 cnf = cnf[:-1] 1210 if cnf[:1] != '-': 1211 cnf = '-'+cnf 1212 options = (cnf,) 1213 else: 1214 options = self._options(cnf, kw) 1215 if not options: 1216 res = self.tk.call('grid', 1217 command, self._w, index) 1218 words = self.tk.splitlist(res) 1219 dict = {} 1220 for i in range(0, len(words), 2): 1221 key = words[i][1:] 1222 value = words[i+1] 1223 if not value: 1224 value = None 1225 elif '.' in value: 1226 value = getdouble(value) 1227 else: 1228 value = getint(value) 1229 dict[key] = value 1230 return dict 1231 res = self.tk.call( 1232 ('grid', command, self._w, index) 1233 + options) 1234 if len(options) == 1: 1235 if not res: return None 1236 # In Tk 7.5, -width can be a float 1237 if '.' in res: return getdouble(res) 1238 return getint(res) 1239 def grid_columnconfigure(self, index, cnf={}, **kw): 1240 """Configure column INDEX of a grid. 1241 1242 Valid resources are minsize (minimum size of the column), 1243 weight (how much does additional space propagate to this column) 1244 and pad (how much space to let additionally).""" 1245 return self._grid_configure('columnconfigure', index, cnf, kw) 1246 columnconfigure = grid_columnconfigure 1247 def grid_location(self, x, y): 1248 """Return a tuple of column and row which identify the cell 1249 at which the pixel at position X and Y inside the master 1250 widget is located.""" 1251 return self._getints( 1252 self.tk.call( 1253 'grid', 'location', self._w, x, y)) or None 1254 def grid_propagate(self, flag=_noarg_): 1255 """Set or get the status for propagation of geometry information. 1256 1257 A boolean argument specifies whether the geometry information 1258 of the slaves will determine the size of this widget. If no argument 1259 is given, the current setting will be returned. 1260 """ 1261 if flag is Misc._noarg_: 1262 return self._getboolean(self.tk.call( 1263 'grid', 'propagate', self._w)) 1264 else: 1265 self.tk.call('grid', 'propagate', self._w, flag) 1266 def grid_rowconfigure(self, index, cnf={}, **kw): 1267 """Configure row INDEX of a grid. 1268 1269 Valid resources are minsize (minimum size of the row), 1270 weight (how much does additional space propagate to this row) 1271 and pad (how much space to let additionally).""" 1272 return self._grid_configure('rowconfigure', index, cnf, kw) 1273 rowconfigure = grid_rowconfigure 1274 def grid_size(self): 1275 """Return a tuple of the number of column and rows in the grid.""" 1276 return self._getints( 1277 self.tk.call('grid', 'size', self._w)) or None 1278 size = grid_size 1279 def grid_slaves(self, row=None, column=None): 1280 """Return a list of all slaves of this widget 1281 in its packing order.""" 1282 args = () 1283 if row is not None: 1284 args = args + ('-row', row) 1285 if column is not None: 1286 args = args + ('-column', column) 1287 return map(self._nametowidget, 1288 self.tk.splitlist(self.tk.call( 1289 ('grid', 'slaves', self._w) + args))) 1290 1291 # Support for the "event" command, new in Tk 4.2. 1292 # By Case Roole. 1293 1294 def event_add(self, virtual, *sequences): 1295 """Bind a virtual event VIRTUAL (of the form <<Name>>) 1296 to an event SEQUENCE such that the virtual event is triggered 1297 whenever SEQUENCE occurs.""" 1298 args = ('event', 'add', virtual) + sequences 1299 self.tk.call(args) 1300 1301 def event_delete(self, virtual, *sequences): 1302 """Unbind a virtual event VIRTUAL from SEQUENCE.""" 1303 args = ('event', 'delete', virtual) + sequences 1304 self.tk.call(args) 1305 1306 def event_generate(self, sequence, **kw): 1307 """Generate an event SEQUENCE. Additional 1308 keyword arguments specify parameter of the event 1309 (e.g. x, y, rootx, rooty).""" 1310 args = ('event', 'generate', self._w, sequence) 1311 for k, v in kw.items(): 1312 args = args + ('-%s' % k, str(v)) 1313 self.tk.call(args) 1314 1315 def event_info(self, virtual=None): 1316 """Return a list of all virtual events or the information 1317 about the SEQUENCE bound to the virtual event VIRTUAL.""" 1318 return self.tk.splitlist( 1319 self.tk.call('event', 'info', virtual)) 1320 1321 # Image related commands 1322 1323 def image_names(self): 1324 """Return a list of all existing image names.""" 1325 return self.tk.call('image', 'names') 1326 1327 def image_types(self): 1328 """Return a list of all available image types (e.g. phote bitmap).""" 1329 return self.tk.call('image', 'types') 1330 1331 1332 class CallWrapper: 1333 """Internal class. Stores function to call when some user 1334 defined Tcl function is called e.g. after an event occurred.""" 1335 def __init__(self, func, subst, widget): 1336 """Store FUNC, SUBST and WIDGET as members.""" 1337 self.func = func 1338 self.subst = subst 1339 self.widget = widget 1340 def __call__(self, *args): 1341 """Apply first function SUBST to arguments, than FUNC.""" 1342 try: 1343 if self.subst: 1344 args = self.subst(*args) 1345 return self.func(*args) 1346 except SystemExit, msg: 1347 raise SystemExit, msg 1348 except: 1349 self.widget._report_exception() 1350 1351 1352 class Wm: 1353 """Provides functions for the communication with the window manager.""" 1354 1355 def wm_aspect(self, 1356 minNumer=None, minDenom=None, 1357 maxNumer=None, maxDenom=None): 1358 """Instruct the window manager to set the aspect ratio (width/height) 1359 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple 1360 of the actual values if no argument is given.""" 1361 return self._getints( 1362 self.tk.call('wm', 'aspect', self._w, 1363 minNumer, minDenom, 1364 maxNumer, maxDenom)) 1365 aspect = wm_aspect 1366 1367 def wm_attributes(self, *args): 1368 """This subcommand returns or sets platform specific attributes 1369 1370 The first form returns a list of the platform specific flags and 1371 their values. The second form returns the value for the specific 1372 option. The third form sets one or more of the values. The values 1373 are as follows: 1374 1375 On Windows, -disabled gets or sets whether the window is in a 1376 disabled state. -toolwindow gets or sets the style of the window 1377 to toolwindow (as defined in the MSDN). -topmost gets or sets 1378 whether this is a topmost window (displays above all other 1379 windows). 1380 1381 On Macintosh, XXXXX 1382 1383 On Unix, there are currently no special attribute values. 1384 """ 1385 args = ('wm', 'attributes', self._w) + args 1386 return self.tk.call(args) 1387 attributes=wm_attributes 1388 1389 def wm_client(self, name=None): 1390 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return 1391 current value.""" 1392 return self.tk.call('wm', 'client', self._w, name) 1393 client = wm_client 1394 def wm_colormapwindows(self, *wlist): 1395 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property 1396 of this widget. This list contains windows whose colormaps differ from their 1397 parents. Return current list of widgets if WLIST is empty.""" 1398 if len(wlist) > 1: 1399 wlist = (wlist,) # Tk needs a list of windows here 1400 args = ('wm', 'colormapwindows', self._w) + wlist 1401 return map(self._nametowidget, self.tk.call(args)) 1402 colormapwindows = wm_colormapwindows 1403 def wm_command(self, value=None): 1404 """Store VALUE in WM_COMMAND property. It is the command 1405 which shall be used to invoke the application. Return current 1406 command if VALUE is None.""" 1407 return self.tk.call('wm', 'command', self._w, value) 1408 command = wm_command 1409 def wm_deiconify(self): 1410 """Deiconify this widget. If it was never mapped it will not be mapped. 1411 On Windows it will raise this widget and give it the focus.""" 1412 return self.tk.call('wm', 'deiconify', self._w) 1413 deiconify = wm_deiconify 1414 def wm_focusmodel(self, model=None): 1415 """Set focus model to MODEL. "active" means that this widget will claim 1416 the focus itself, "passive" means that the window manager shall give 1417 the focus. Return current focus model if MODEL is None.""" 1418 return self.tk.call('wm', 'focusmodel', self._w, model) 1419 focusmodel = wm_focusmodel 1420 def wm_frame(self): 1421 """Return identifier for decorative frame of this widget if present.""" 1422 return self.tk.call('wm', 'frame', self._w) 1423 frame = wm_frame 1424 def wm_geometry(self, newGeometry=None): 1425 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return 1426 current value if None is given.""" 1427 return self.tk.call('wm', 'geometry', self._w, newGeometry) 1428 geometry = wm_geometry 1429 def wm_grid(self, 1430 baseWidth=None, baseHeight=None, 1431 widthInc=None, heightInc=None): 1432 """Instruct the window manager that this widget shall only be 1433 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and 1434 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the 1435 number of grid units requested in Tk_GeometryRequest.""" 1436 return self._getints(self.tk.call( 1437 'wm', 'grid', self._w, 1438 baseWidth, baseHeight, widthInc, heightInc)) 1439 grid = wm_grid 1440 def wm_group(self, pathName=None): 1441 """Set the group leader widgets for related widgets to PATHNAME. Return 1442 the group leader of this widget if None is given.""" 1443 return self.tk.call('wm', 'group', self._w, pathName) 1444 group = wm_group 1445 def wm_iconbitmap(self, bitmap=None): 1446 """Set bitmap for the iconified widget to BITMAP. Return 1447 the bitmap if None is given.""" 1448 return self.tk.call('wm', 'iconbitmap', self._w, bitmap) 1449 iconbitmap = wm_iconbitmap 1450 def wm_iconify(self): 1451 """Display widget as icon.""" 1452 return self.tk.call('wm', 'iconify', self._w) 1453 iconify = wm_iconify 1454 def wm_iconmask(self, bitmap=None): 1455 """Set mask for the icon bitmap of this widget. Return the 1456 mask if None is given.""" 1457 return self.tk.call('wm', 'iconmask', self._w, bitmap) 1458 iconmask = wm_iconmask 1459 def wm_iconname(self, newName=None): 1460 """Set the name of the icon for this widget. Return the name if 1461 None is given.""" 1462 return self.tk.call('wm', 'iconname', self._w, newName) 1463 iconname = wm_iconname 1464 def wm_iconposition(self, x=None, y=None): 1465 """Set the position of the icon of this widget to X and Y. Return 1466 a tuple of the current values of X and X if None is given.""" 1467 return self._getints(self.tk.call( 1468 'wm', 'iconposition', self._w, x, y)) 1469 iconposition = wm_iconposition 1470 def wm_iconwindow(self, pathName=None): 1471 """Set widget PATHNAME to be displayed instead of icon. Return the current 1472 value if None is given.""" 1473 return self.tk.call('wm', 'iconwindow', self._w, pathName) 1474 iconwindow = wm_iconwindow 1475 def wm_maxsize(self, width=None, height=None): 1476 """Set max WIDTH and HEIGHT for this widget. If the window is gridded 1477 the values are given in grid units. Return the current values if None 1478 is given.""" 1479 return self._getints(self.tk.call( 1480 'wm', 'maxsize', self._w, width, height)) 1481 maxsize = wm_maxsize 1482 def wm_minsize(self, width=None, height=None): 1483 """Set min WIDTH and HEIGHT for this widget. If the window is gridded 1484 the values are given in grid units. Return the current values if None 1485 is given.""" 1486 return self._getints(self.tk.call( 1487 'wm', 'minsize', self._w, width, height)) 1488 minsize = wm_minsize 1489 def wm_overrideredirect(self, boolean=None): 1490 """Instruct the window manager to ignore this widget 1491 if BOOLEAN is given with 1. Return the current value if None 1492 is given.""" 1493 return self._getboolean(self.tk.call( 1494 'wm', 'overrideredirect', self._w, boolean)) 1495 overrideredirect = wm_overrideredirect 1496 def wm_positionfrom(self, who=None): 1497 """Instruct the window manager that the position of this widget shall 1498 be defined by the user if WHO is "user", and by its own policy if WHO is 1499 "program".""" 1500 return self.tk.call('wm', 'positionfrom', self._w, who) 1501 positionfrom = wm_positionfrom 1502 def wm_protocol(self, name=None, func=None): 1503 """Bind function FUNC to command NAME for this widget. 1504 Return the function bound to NAME if None is given. NAME could be 1505 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW".""" 1506 if callable(func): 1507 command = self._register(func) 1508 else: 1509 command = func 1510 return self.tk.call( 1511 'wm', 'protocol', self._w, name, command) 1512 protocol = wm_protocol 1513 def wm_resizable(self, width=None, height=None): 1514 """Instruct the window manager whether this width can be resized 1515 in WIDTH or HEIGHT. Both values are boolean values.""" 1516 return self.tk.call('wm', 'resizable', self._w, width, height) 1517 resizable = wm_resizable 1518 def wm_sizefrom(self, who=None): 1519 """Instruct the window manager that the size of this widget shall 1520 be defined by the user if WHO is "user", and by its own policy if WHO is 1521 "program".""" 1522 return self.tk.call('wm', 'sizefrom', self._w, who) 1523 sizefrom = wm_sizefrom 1524 def wm_state(self, newstate=None): 1525 """Query or set the state of this widget as one of normal, icon, 1526 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only).""" 1527 return self.tk.call('wm', 'state', self._w, newstate) 1528 state = wm_state 1529 def wm_title(self, string=None): 1530 """Set the title of this widget.""" 1531 return self.tk.call('wm', 'title', self._w, string) 1532 title = wm_title 1533 def wm_transient(self, master=None): 1534 """Instruct the window manager that this widget is transient 1535 with regard to widget MASTER.""" 1536 return self.tk.call('wm', 'transient', self._w, master) 1537 transient = wm_transient 1538 def wm_withdraw(self): 1539 """Withdraw this widget from the screen such that it is unmapped 1540 and forgotten by the window manager. Re-draw it with wm_deiconify.""" 1541 return self.tk.call('wm', 'withdraw', self._w) 1542 withdraw = wm_withdraw 1543 1544 1545 class Tk(Misc, Wm): 1546 """Toplevel widget of Tk which represents mostly the main window 1547 of an appliation. It has an associated Tcl interpreter.""" 1548 _w = '.' 1549 def __init__(self, screenName=None, baseName=None, className='Tk', 1550 useTk=1, sync=0, use=None): 1551 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will 1552 be created. BASENAME will be used for the identification of the profile file (see 1553 readprofile). 1554 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME 1555 is the name of the widget class.""" 1556 self.master = None 1557 self.children = {} 1558 self._tkloaded = 0 1559 # to avoid recursions in the getattr code in case of failure, we 1560 # ensure that self.tk is always _something_. 1561 self.tk = None 1562 if baseName is None: 1563 import sys, os 1564 baseName = os.path.basename(sys.argv[0]) 1565 baseName, ext = os.path.splitext(baseName) 1566 if ext not in ('.py', '.pyc', '.pyo'): 1567 baseName = baseName + ext 1568 interactive = 0 1569 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) 1570 if useTk: 1571 self._loadtk() 1572 self.readprofile(baseName, className) 1573 def loadtk(self): 1574 if not self._tkloaded: 1575 self.tk.loadtk() 1576 self._loadtk() 1577 def _loadtk(self): 1578 self._tkloaded = 1 1579 global _default_root 1580 if _MacOS and hasattr(_MacOS, 'SchedParams'): 1581 # Disable event scanning except for Command-Period 1582 _MacOS.SchedParams(1, 0) 1583 # Work around nasty MacTk bug 1584 # XXX Is this one still needed? 1585 self.update() 1586 # Version sanity checks 1587 tk_version = self.tk.getvar('tk_version') 1588 if tk_version != _tkinter.TK_VERSION: 1589 raise RuntimeError, \ 1590 "tk.h version (%s) doesn't match libtk.a version (%s)" \ 1591 % (_tkinter.TK_VERSION, tk_version) 1592 # Under unknown circumstances, tcl_version gets coerced to float 1593 tcl_version = str(self.tk.getvar('tcl_version')) 1594 if tcl_version != _tkinter.TCL_VERSION: 1595 raise RuntimeError, \ 1596 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \ 1597 % (_tkinter.TCL_VERSION, tcl_version) 1598 if TkVersion < 4.0: 1599 raise RuntimeError, \ 1600 "Tk 4.0 or higher is required; found Tk %s" \ 1601 % str(TkVersion) 1602 self.tk.createcommand('tkerror', _tkerror) 1603 self.tk.createcommand('exit', _exit) 1604 if _support_default_root and not _default_root: 1605 _default_root = self 1606 self.protocol("WM_DELETE_WINDOW", self.destroy) 1607 def destroy(self): 1608 """Destroy this and all descendants widgets. This will 1609 end the application of this Tcl interpreter.""" 1610 for c in self.children.values(): c.destroy() 1611 self.tk.call('destroy', self._w) 1612 Misc.destroy(self) 1613 global _default_root 1614 if _support_default_root and _default_root is self: 1615 _default_root = None 1616 def readprofile(self, baseName, className): 1617 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into 1618 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if 1619 such a file exists in the home directory.""" 1620 import os 1621 if os.environ.has_key('HOME'): home = os.environ['HOME'] 1622 else: home = os.curdir 1623 class_tcl = os.path.join(home, '.%s.tcl' % className) 1624 class_py = os.path.join(home, '.%s.py' % className) 1625 base_tcl = os.path.join(home, '.%s.tcl' % baseName) 1626 base_py = os.path.join(home, '.%s.py' % baseName) 1627 dir = {'self': self} 1628 exec 'from Tkinter import *' in dir 1629 if os.path.isfile(class_tcl): 1630 self.tk.call('source', class_tcl) 1631 if os.path.isfile(class_py): 1632 execfile(class_py, dir) 1633 if os.path.isfile(base_tcl): 1634 self.tk.call('source', base_tcl) 1635 if os.path.isfile(base_py): 1636 execfile(base_py, dir) 1637 def report_callback_exception(self, exc, val, tb): 1638 """Internal function. It reports exception on sys.stderr.""" 1639 import traceback, sys 1640 sys.stderr.write("Exception in Tkinter callback\n") 1641 sys.last_type = exc 1642 sys.last_value = val 1643 sys.last_traceback = tb 1644 traceback.print_exception(exc, val, tb) 1645 def __getattr__(self, attr): 1646 "Delegate attribute access to the interpreter object" 1647 return getattr(self.tk, attr) 1648 def __hasattr__(self, attr): 1649 "Delegate attribute access to the interpreter object" 1650 return hasattr(self.tk, attr) 1651 def __delattr__(self, attr): 1652 "Delegate attribute access to the interpreter object" 1653 return delattr(self.tk, attr) 1654 1655 # Ideally, the classes Pack, Place and Grid disappear, the 1656 # pack/place/grid methods are defined on the Widget class, and 1657 # everybody uses w.pack_whatever(...) instead of Pack.whatever(w, 1658 # ...), with pack(), place() and grid() being short for 1659 # pack_configure(), place_configure() and grid_columnconfigure(), and 1660 # forget() being short for pack_forget(). As a practical matter, I'm 1661 # afraid that there is too much code out there that may be using the 1662 # Pack, Place or Grid class, so I leave them intact -- but only as 1663 # backwards compatibility features. Also note that those methods that 1664 # take a master as argument (e.g. pack_propagate) have been moved to 1665 # the Misc class (which now incorporates all methods common between 1666 # toplevel and interior widgets). Again, for compatibility, these are 1667 # copied into the Pack, Place or Grid class. 1668 1669 1670 def Tcl(screenName=None, baseName=None, className='Tk', useTk=0): 1671 return Tk(screenName, baseName, className, useTk) 1672 1673 class Pack: 1674 """Geometry manager Pack. 1675 1676 Base class to use the methods pack_* in every widget.""" 1677 def pack_configure(self, cnf={}, **kw): 1678 """Pack a widget in the parent widget. Use as options: 1679 after=widget - pack it after you have packed widget 1680 anchor=NSEW (or subset) - position widget according to 1681 given direction 1682 before=widget - pack it before you will pack widget 1683 expand=bool - expand widget if parent size grows 1684 fill=NONE or X or Y or BOTH - fill widget if widget grows 1685 in=master - use master to contain this widget 1686 ipadx=amount - add internal padding in x direction 1687 ipady=amount - add internal padding in y direction 1688 padx=amount - add padding in x direction 1689 pady=amount - add padding in y direction 1690 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. 1691 """ 1692 self.tk.call( 1693 ('pack', 'configure', self._w) 1694 + self._options(cnf, kw)) 1695 pack = configure = config = pack_configure 1696 def pack_forget(self): 1697 """Unmap this widget and do not use it for the packing order.""" 1698 self.tk.call('pack', 'forget', self._w) 1699 forget = pack_forget 1700 def pack_info(self): 1701 """Return information about the packing options 1702 for this widget.""" 1703 words = self.tk.splitlist( 1704 self.tk.call('pack', 'info', self._w)) 1705 dict = {} 1706 for i in range(0, len(words), 2): 1707 key = words[i][1:] 1708 value = words[i+1] 1709 if value[:1] == '.': 1710 value = self._nametowidget(value) 1711 dict[key] = value 1712 return dict 1713 info = pack_info 1714 propagate = pack_propagate = Misc.pack_propagate 1715 slaves = pack_slaves = Misc.pack_slaves 1716 1717 class Place: 1718 """Geometry manager Place. 1719 1720 Base class to use the methods place_* in every widget.""" 1721 def place_configure(self, cnf={}, **kw): 1722 """Place a widget in the parent widget. Use as options: 1723 in=master - master relative to which the widget is placed. 1724 x=amount - locate anchor of this widget at position x of master 1725 y=amount - locate anchor of this widget at position y of master 1726 relx=amount - locate anchor of this widget between 0.0 and 1.0 1727 relative to width of master (1.0 is right edge) 1728 rely=amount - locate anchor of this widget between 0.0 and 1.0 1729 relative to height of master (1.0 is bottom edge) 1730 anchor=NSEW (or subset) - position anchor according to given direction 1731 width=amount - width of this widget in pixel 1732 height=amount - height of this widget in pixel 1733 relwidth=amount - width of this widget between 0.0 and 1.0 1734 relative to width of master (1.0 is the same width 1735 as the master) 1736 relheight=amount - height of this widget between 0.0 and 1.0 1737 relative to height of master (1.0 is the same 1738 height as the master) 1739 bordermode="inside" or "outside" - whether to take border width of master widget 1740 into account 1741 """ 1742 for k in ['in_']: 1743 if kw.has_key(k): 1744 kw[k[:-1]] = kw[k] 1745 del kw[k] 1746 self.tk.call( 1747 ('place', 'configure', self._w) 1748 + self._options(cnf, kw)) 1749 place = configure = config = place_configure 1750 def place_forget(self): 1751 """Unmap this widget.""" 1752 self.tk.call('place', 'forget', self._w) 1753 forget = place_forget 1754 def place_info(self): 1755 """Return information about the placing options 1756 for this widget.""" 1757 words = self.tk.splitlist( 1758 self.tk.call('place', 'info', self._w)) 1759 dict = {} 1760 for i in range(0, len(words), 2): 1761 key = words[i][1:] 1762 value = words[i+1] 1763 if value[:1] == '.': 1764 value = self._nametowidget(value) 1765 dict[key] = value 1766 return dict 1767 info = place_info 1768 slaves = place_slaves = Misc.place_slaves 1769 1770 class Grid: 1771 """Geometry manager Grid. 1772 1773 Base class to use the methods grid_* in every widget.""" 1774 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu) 1775 def grid_configure(self, cnf={}, **kw): 1776 """Position a widget in the parent widget in a grid. Use as options: 1777 column=number - use cell identified with given column (starting with 0) 1778 columnspan=number - this widget will span several columns 1779 in=master - use master to contain this widget 1780 ipadx=amount - add internal padding in x direction 1781 ipady=amount - add internal padding in y direction 1782 padx=amount - add padding in x direction 1783 pady=amount - add padding in y direction 1784 row=number - use cell identified with given row (starting with 0) 1785 rowspan=number - this widget will span several rows 1786 sticky=NSEW - if cell is larger on which sides will this 1787 widget stick to the cell boundary 1788 """ 1789 self.tk.call( 1790 ('grid', 'configure', self._w) 1791 + self._options(cnf, kw)) 1792 grid = configure = config = grid_configure 1793 bbox = grid_bbox = Misc.grid_bbox 1794 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure 1795 def grid_forget(self): 1796 """Unmap this widget.""" 1797 self.tk.call('grid', 'forget', self._w) 1798 forget = grid_forget 1799 def grid_remove(self): 1800 """Unmap this widget but remember the grid options.""" 1801 self.tk.call('grid', 'remove', self._w) 1802 def grid_info(self): 1803 """Return information about the options 1804 for positioning this widget in a grid.""" 1805 words = self.tk.splitlist( 1806 self.tk.call('grid', 'info', self._w)) 1807 dict = {} 1808 for i in range(0, len(words), 2): 1809 key = words[i][1:] 1810 value = words[i+1] 1811 if value[:1] == '.': 1812 value = self._nametowidget(value) 1813 dict[key] = value 1814 return dict 1815 info = grid_info 1816 location = grid_location = Misc.grid_location 1817 propagate = grid_propagate = Misc.grid_propagate 1818 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure 1819 size = grid_size = Misc.grid_size 1820 slaves = grid_slaves = Misc.grid_slaves 1821 1822 class BaseWidget(Misc): 1823 """Internal class.""" 1824 def _setup(self, master, cnf): 1825 """Internal function. Sets up information about children.""" 1826 if _support_default_root: 1827 global _default_root 1828 if not master: 1829 if not _default_root: 1830 _default_root = Tk() 1831 master = _default_root 1832 self.master = master 1833 self.tk = master.tk 1834 name = None 1835 if cnf.has_key('name'): 1836 name = cnf['name'] 1837 del cnf['name'] 1838 if not name: 1839 name = repr(id(self)) 1840 self._name = name 1841 if master._w=='.': 1842 self._w = '.' + name 1843 else: 1844 self._w = master._w + '.' + name 1845 self.children = {} 1846 if self.master.children.has_key(self._name): 1847 self.master.children[self._name].destroy() 1848 self.master.children[self._name] = self 1849 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): 1850 """Construct a widget with the parent widget MASTER, a name WIDGETNAME 1851 and appropriate options.""" 1852 if kw: 1853 cnf = _cnfmerge((cnf, kw)) 1854 self.widgetName = widgetName 1855 BaseWidget._setup(self, master, cnf) 1856 classes = [] 1857 for k in cnf.keys(): 1858 if type(k) is ClassType: 1859 classes.append((k, cnf[k])) 1860 del cnf[k] 1861 self.tk.call( 1862 (widgetName, self._w) + extra + self._options(cnf)) 1863 for k, v in classes: 1864 k.configure(self, v) 1865 def destroy(self): 1866 """Destroy this and all descendants widgets.""" 1867 for c in self.children.values(): c.destroy() 1868 if self.master.children.has_key(self._name): 1869 del self.master.children[self._name] 1870 self.tk.call('destroy', self._w) 1871 Misc.destroy(self) 1872 def _do(self, name, args=()): 1873 # XXX Obsolete -- better use self.tk.call directly! 1874 return self.tk.call((self._w, name) + args) 1875 1876 class Widget(BaseWidget, Pack, Place, Grid): 1877 """Internal class. 1878 1879 Base class for a widget which can be positioned with the geometry managers 1880 Pack, Place or Grid.""" 1881 pass 1882 1883 class Toplevel(BaseWidget, Wm): 1884 """Toplevel widget, e.g. for dialogs.""" 1885 def __init__(self, master=None, cnf={}, **kw): 1886 """Construct a toplevel widget with the parent MASTER. 1887 1888 Valid resource names: background, bd, bg, borderwidth, class, 1889 colormap, container, cursor, height, highlightbackground, 1890 highlightcolor, highlightthickness, menu, relief, screen, takefocus, 1891 use, visual, width.""" 1892 if kw: 1893 cnf = _cnfmerge((cnf, kw)) 1894 extra = () 1895 for wmkey in ['screen', 'class_', 'class', 'visual', 1896 'colormap']: 1897 if cnf.has_key(wmkey): 1898 val = cnf[wmkey] 1899 # TBD: a hack needed because some keys 1900 # are not valid as keyword arguments 1901 if wmkey[-1] == '_': opt = '-'+wmkey[:-1] 1902 else: opt = '-'+wmkey 1903 extra = extra + (opt, val) 1904 del cnf[wmkey] 1905 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra) 1906 root = self._root() 1907 self.iconname(root.iconname()) 1908 self.title(root.title()) 1909 self.protocol("WM_DELETE_WINDOW", self.destroy) 1910 1911 class Button(Widget): 1912 """Button widget.""" 1913 def __init__(self, master=None, cnf={}, **kw): 1914 """Construct a button widget with the parent MASTER. 1915 1916 STANDARD OPTIONS 1917 1918 activebackground, activeforeground, anchor, 1919 background, bitmap, borderwidth, cursor, 1920 disabledforeground, font, foreground 1921 highlightbackground, highlightcolor, 1922 highlightthickness, image, justify, 1923 padx, pady, relief, repeatdelay, 1924 repeatinterval, takefocus, text, 1925 textvariable, underline, wraplength 1926 1927 WIDGET-SPECIFIC OPTIONS 1928 1929 command, compound, default, height, 1930 overrelief, state, width 1931 """ 1932 Widget.__init__(self, master, 'button', cnf, kw) 1933 1934 def tkButtonEnter(self, *dummy): 1935 self.tk.call('tkButtonEnter', self._w) 1936 1937 def tkButtonLeave(self, *dummy): 1938 self.tk.call('tkButtonLeave', self._w) 1939 1940 def tkButtonDown(self, *dummy): 1941 self.tk.call('tkButtonDown', self._w) 1942 1943 def tkButtonUp(self, *dummy): 1944 self.tk.call('tkButtonUp', self._w) 1945 1946 def tkButtonInvoke(self, *dummy): 1947 self.tk.call('tkButtonInvoke', self._w) 1948 1949 def flash(self): 1950 """Flash the button. 1951 1952 This is accomplished by redisplaying 1953 the button several times, alternating between active and 1954 normal colors. At the end of the flash the button is left 1955 in the same normal/active state as when the command was 1956 invoked. This command is ignored if the button's state is 1957 disabled. 1958 """ 1959 self.tk.call(self._w, 'flash') 1960 1961 def invoke(self): 1962 """Invoke the command associated with the button. 1963 1964 The return value is the return value from the command, 1965 or an empty string if there is no command associated with 1966 the button. This command is ignored if the button's state 1967 is disabled. 1968 """ 1969 return self.tk.call(self._w, 'invoke') 1970 1971 # Indices: 1972 # XXX I don't like these -- take them away 1973 def AtEnd(): 1974 return 'end' 1975 def AtInsert(*args): 1976 s = 'insert' 1977 for a in args: 1978 if a: s = s + (' ' + a) 1979 return s 1980 def AtSelFirst(): 1981 return 'sel.first' 1982 def AtSelLast(): 1983 return 'sel.last' 1984 def At(x, y=None): 1985 if y is None: 1986 return '@%r' % (x,) 1987 else: 1988 return '@%r,%r' % (x, y) 1989 1990 class Canvas(Widget): 1991 """Canvas widget to display graphical elements like lines or text.""" 1992 def __init__(self, master=None, cnf={}, **kw): 1993 """Construct a canvas widget with the parent MASTER. 1994 1995 Valid resource names: background, bd, bg, borderwidth, closeenough, 1996 confine, cursor, height, highlightbackground, highlightcolor, 1997 highlightthickness, insertbackground, insertborderwidth, 1998 insertofftime, insertontime, insertwidth, offset, relief, 1999 scrollregion, selectbackground, selectborderwidth, selectforeground, 2000 state, takefocus, width, xscrollcommand, xscrollincrement, 2001 yscrollcommand, yscrollincrement.""" 2002 Widget.__init__(self, master, 'canvas', cnf, kw) 2003 def addtag(self, *args): 2004 """Internal function.""" 2005 self.tk.call((self._w, 'addtag') + args) 2006 def addtag_above(self, newtag, tagOrId): 2007 """Add tag NEWTAG to all items above TAGORID.""" 2008 self.addtag(newtag, 'above', tagOrId) 2009 def addtag_all(self, newtag): 2010 """Add tag NEWTAG to all items.""" 2011 self.addtag(newtag, 'all') 2012 def addtag_below(self, newtag, tagOrId): 2013 """Add tag NEWTAG to all items below TAGORID.""" 2014 self.addtag(newtag, 'below', tagOrId) 2015 def addtag_closest(self, newtag, x, y, halo=None, start=None): 2016 """Add tag NEWTAG to item which is closest to pixel at X, Y. 2017 If several match take the top-most. 2018 All items closer than HALO are considered overlapping (all are 2019 closests). If START is specified the next below this tag is taken.""" 2020 self.addtag(newtag, 'closest', x, y, halo, start) 2021 def addtag_enclosed(self, newtag, x1, y1, x2, y2): 2022 """Add tag NEWTAG to all items in the rectangle defined 2023 by X1,Y1,X2,Y2.""" 2024 self.addtag(newtag, 'enclosed', x1, y1, x2, y2) 2025 def addtag_overlapping(self, newtag, x1, y1, x2, y2): 2026 """Add tag NEWTAG to all items which overlap the rectangle 2027 defined by X1,Y1,X2,Y2.""" 2028 self.addtag(newtag, 'overlapping', x1, y1, x2, y2) 2029 def addtag_withtag(self, newtag, tagOrId): 2030 """Add tag NEWTAG to all items with TAGORID.""" 2031 self.addtag(newtag, 'withtag', tagOrId) 2032 def bbox(self, *args): 2033 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle 2034 which encloses all items with tags specified as arguments.""" 2035 return self._getints( 2036 self.tk.call((self._w, 'bbox') + args)) or None 2037 def tag_unbind(self, tagOrId, sequence, funcid=None): 2038 """Unbind for all items with TAGORID for event SEQUENCE the 2039 function identified with FUNCID.""" 2040 self.tk.call(self._w, 'bind', tagOrId, sequence, '') 2041 if funcid: 2042 self.deletecommand(funcid) 2043 def tag_bind(self, tagOrId, sequence=None, func=None, add=None): 2044 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. 2045 2046 An additional boolean parameter ADD specifies whether FUNC will be 2047 called additionally to the other bound function or whether it will 2048 replace the previous function. See bind for the return value.""" 2049 return self._bind((self._w, 'bind', tagOrId), 2050 sequence, func, add) 2051 def canvasx(self, screenx, gridspacing=None): 2052 """Return the canvas x coordinate of pixel position SCREENX rounded 2053 to nearest multiple of GRIDSPACING units.""" 2054 return getdouble(self.tk.call( 2055 self._w, 'canvasx', screenx, gridspacing)) 2056 def canvasy(self, screeny, gridspacing=None): 2057 """Return the canvas y coordinate of pixel position SCREENY rounded 2058 to nearest multiple of GRIDSPACING units.""" 2059 return getdouble(self.tk.call( 2060 self._w, 'canvasy', screeny, gridspacing)) 2061 def coords(self, *args): 2062 """Return a list of coordinates for the item given in ARGS.""" 2063 # XXX Should use _flatten on args 2064 return map(getdouble, 2065 self.tk.splitlist( 2066 self.tk.call((self._w, 'coords') + args))) 2067 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={}) 2068 """Internal function.""" 2069 args = _flatten(args) 2070 cnf = args[-1] 2071 if type(cnf) in (DictionaryType, TupleType): 2072 args = args[:-1] 2073 else: 2074 cnf = {} 2075 return getint(self.tk.call( 2076 self._w, 'create', itemType, 2077 *(args + self._options(cnf, kw)))) 2078 def create_arc(self, *args, **kw): 2079 """Create arc shaped region with coordinates x1,y1,x2,y2.""" 2080 return self._create('arc', args, kw) 2081 def create_bitmap(self, *args, **kw): 2082 """Create bitmap with coordinates x1,y1.""" 2083 return self._create('bitmap', args, kw) 2084 def create_image(self, *args, **kw): 2085 """Create image item with coordinates x1,y1.""" 2086 return self._create('image', args, kw) 2087 def create_line(self, *args, **kw): 2088 """Create line with coordinates x1,y1,...,xn,yn.""" 2089 return self._create('line', args, kw) 2090 def create_oval(self, *args, **kw): 2091 """Create oval with coordinates x1,y1,x2,y2.""" 2092 return self._create('oval', args, kw) 2093 def create_polygon(self, *args, **kw): 2094 """Create polygon with coordinates x1,y1,...,xn,yn.""" 2095 return self._create('polygon', args, kw) 2096 def create_rectangle(self, *args, **kw): 2097 """Create rectangle with coordinates x1,y1,x2,y2.""" 2098 return self._create('rectangle', args, kw) 2099 def create_text(self, *args, **kw): 2100 """Create text with coordinates x1,y1.""" 2101 return self._create('text', args, kw) 2102 def create_window(self, *args, **kw): 2103 """Create window with coordinates x1,y1,x2,y2.""" 2104 return self._create('window', args, kw) 2105 def dchars(self, *args): 2106 """Delete characters of text items identified by tag or id in ARGS (possibly 2107 several times) from FIRST to LAST character (including).""" 2108 self.tk.call((self._w, 'dchars') + args) 2109 def delete(self, *args): 2110 """Delete items identified by all tag or ids contained in ARGS.""" 2111 self.tk.call((self._w, 'delete') + args) 2112 def dtag(self, *args): 2113 """Delete tag or id given as last arguments in ARGS from items 2114 identified by first argument in ARGS.""" 2115 self.tk.call((self._w, 'dtag') + args) 2116 def find(self, *args): 2117 """Internal function.""" 2118 return self._getints( 2119 self.tk.call((self._w, 'find') + args)) or () 2120 def find_above(self, tagOrId): 2121 """Return items above TAGORID.""" 2122 return self.find('above', tagOrId) 2123 def find_all(self): 2124 """Return all items.""" 2125 return self.find('all') 2126 def find_below(self, tagOrId): 2127 """Return all items below TAGORID.""" 2128 return self.find('below', tagOrId) 2129 def find_closest(self, x, y, halo=None, start=None): 2130 """Return item which is closest to pixel at X, Y. 2131 If several match take the top-most. 2132 All items closer than HALO are considered overlapping (all are 2133 closests). If START is specified the next below this tag is taken.""" 2134 return self.find('closest', x, y, halo, start) 2135 def find_enclosed(self, x1, y1, x2, y2): 2136 """Return all items in rectangle defined 2137 by X1,Y1,X2,Y2.""" 2138 return self.find('enclosed', x1, y1, x2, y2) 2139 def find_overlapping(self, x1, y1, x2, y2): 2140 """Return all items which overlap the rectangle 2141 defined by X1,Y1,X2,Y2.""" 2142 return self.find('overlapping', x1, y1, x2, y2) 2143 def find_withtag(self, tagOrId): 2144 """Return all items with TAGORID.""" 2145 return self.find('withtag', tagOrId) 2146 def focus(self, *args): 2147 """Set focus to the first item specified in ARGS.""" 2148 return self.tk.call((self._w, 'focus') + args) 2149 def gettags(self, *args): 2150 """Return tags associated with the first item specified in ARGS.""" 2151 return self.tk.splitlist( 2152 self.tk.call((self._w, 'gettags') + args)) 2153 def icursor(self, *args): 2154 """Set cursor at position POS in the item identified by TAGORID. 2155 In ARGS TAGORID must be first.""" 2156 self.tk.call((self._w, 'icursor') + args) 2157 def index(self, *args): 2158 """Return position of cursor as integer in item specified in ARGS.""" 2159 return getint(self.tk.call((self._w, 'index') + args)) 2160 def insert(self, *args): 2161 """Insert TEXT in item TAGORID at position POS. ARGS must 2162 be TAGORID POS TEXT.""" 2163 self.tk.call((self._w, 'insert') + args) 2164 def itemcget(self, tagOrId, option): 2165 """Return the resource value for an OPTION for item TAGORID.""" 2166 return self.tk.call( 2167 (self._w, 'itemcget') + (tagOrId, '-'+option)) 2168 def itemconfigure(self, tagOrId, cnf=None, **kw): 2169 """Configure resources of an item TAGORID. 2170 2171 The values for resources are specified as keyword 2172 arguments. To get an overview about 2173 the allowed keyword arguments call the method without arguments. 2174 """ 2175 return self._configure(('itemconfigure', tagOrId), cnf, kw) 2176 itemconfig = itemconfigure 2177 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift, 2178 # so the preferred name for them is tag_lower, tag_raise 2179 # (similar to tag_bind, and similar to the Text widget); 2180 # unfortunately can't delete the old ones yet (maybe in 1.6) 2181 def tag_lower(self, *args): 2182 """Lower an item TAGORID given in ARGS 2183 (optional below another item).""" 2184 self.tk.call((self._w, 'lower') + args) 2185 lower = tag_lower 2186 def move(self, *args): 2187 """Move an item TAGORID given in ARGS.""" 2188 self.tk.call((self._w, 'move') + args) 2189 def postscript(self, cnf={}, **kw): 2190 """Print the contents of the canvas to a postscript 2191 file. Valid options: colormap, colormode, file, fontmap, 2192 height, pageanchor, pageheight, pagewidth, pagex, pagey, 2193 rotate, witdh, x, y.""" 2194 return self.tk.call((self._w, 'postscript') + 2195 self._options(cnf, kw)) 2196 def tag_raise(self, *args): 2197 """Raise an item TAGORID given in ARGS 2198 (optional above another item).""" 2199 self.tk.call((self._w, 'raise') + args) 2200 lift = tkraise = tag_raise 2201 def scale(self, *args): 2202 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.""" 2203 self.tk.call((self._w, 'scale') + args) 2204 def scan_mark(self, x, y): 2205 """Remember the current X, Y coordinates.""" 2206 self.tk.call(self._w, 'scan', 'mark', x, y) 2207 def scan_dragto(self, x, y, gain=10): 2208 """Adjust the view of the canvas to GAIN times the 2209 difference between X and Y and the coordinates given in 2210 scan_mark.""" 2211 self.tk.call(self._w, 'scan', 'dragto', x, y, gain) 2212 def select_adjust(self, tagOrId, index): 2213 """Adjust the end of the selection near the cursor of an item TAGORID to index.""" 2214 self.tk.call(self._w, 'select', 'adjust', tagOrId, index) 2215 def select_clear(self): 2216 """Clear the selection if it is in this widget.""" 2217 self.tk.call(self._w, 'select', 'clear') 2218 def select_from(self, tagOrId, index): 2219 """Set the fixed end of a selection in item TAGORID to INDEX.""" 2220 self.tk.call(self._w, 'select', 'from', tagOrId, index) 2221 def select_item(self): 2222 """Return the item which has the selection.""" 2223 return self.tk.call(self._w, 'select', 'item') or None 2224 def select_to(self, tagOrId, index): 2225 """Set the variable end of a selection in item TAGORID to INDEX.""" 2226 self.tk.call(self._w, 'select', 'to', tagOrId, index) 2227 def type(self, tagOrId): 2228 """Return the type of the item TAGORID.""" 2229 return self.tk.call(self._w, 'type', tagOrId) or None 2230 def xview(self, *args): 2231 """Query and change horizontal position of the view.""" 2232 if not args: 2233 return self._getdoubles(self.tk.call(self._w, 'xview')) 2234 self.tk.call((self._w, 'xview') + args) 2235 def xview_moveto(self, fraction): 2236 """Adjusts the view in the window so that FRACTION of the 2237 total width of the canvas is off-screen to the left.""" 2238 self.tk.call(self._w, 'xview', 'moveto', fraction) 2239 def xview_scroll(self, number, what): 2240 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" 2241 self.tk.call(self._w, 'xview', 'scroll', number, what) 2242 def yview(self, *args): 2243 """Query and change vertical position of the view.""" 2244 if not args: 2245 return self._getdoubles(self.tk.call(self._w, 'yview')) 2246 self.tk.call((self._w, 'yview') + args) 2247 def yview_moveto(self, fraction): 2248 """Adjusts the view in the window so that FRACTION of the 2249 total height of the canvas is off-screen to the top.""" 2250 self.tk.call(self._w, 'yview', 'moveto', fraction) 2251 def yview_scroll(self, number, what): 2252 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" 2253 self.tk.call(self._w, 'yview', 'scroll', number, what) 2254 2255 class Checkbutton(Widget): 2256 """Checkbutton widget which is either in on- or off-state.""" 2257 def __init__(self, master=None, cnf={}, **kw): 2258 """Construct a checkbutton widget with the parent MASTER. 2259 2260 Valid resource names: activebackground, activeforeground, anchor, 2261 background, bd, bg, bitmap, borderwidth, command, cursor, 2262 disabledforeground, fg, font, foreground, height, 2263 highlightbackground, highlightcolor, highlightthickness, image, 2264 indicatoron, justify, offvalue, onvalue, padx, pady, relief, 2265 selectcolor, selectimage, state, takefocus, text, textvariable, 2266 underline, variable, width, wraplength.""" 2267 Widget.__init__(self, master, 'checkbutton', cnf, kw) 2268 def deselect(self): 2269 """Put the button in off-state.""" 2270 self.tk.call(self._w, 'deselect') 2271 def flash(self): 2272 """Flash the button.""" 2273 self.tk.call(self._w, 'flash') 2274 def invoke(self): 2275 """Toggle the button and invoke a command if given as resource.""" 2276 return self.tk.call(self._w, 'invoke') 2277 def select(self): 2278 """Put the button in on-state.""" 2279 self.tk.call(self._w, 'select') 2280 def toggle(self): 2281 """Toggle the button.""" 2282 self.tk.call(self._w, 'toggle') 2283 2284 class Entry(Widget): 2285 """Entry widget which allows to display simple text.""" 2286 def __init__(self, master=None, cnf={}, **kw): 2287 """Construct an entry widget with the parent MASTER. 2288 2289 Valid resource names: background, bd, bg, borderwidth, cursor, 2290 exportselection, fg, font, foreground, highlightbackground, 2291 highlightcolor, highlightthickness, insertbackground, 2292 insertborderwidth, insertofftime, insertontime, insertwidth, 2293 invalidcommand, invcmd, justify, relief, selectbackground, 2294 selectborderwidth, selectforeground, show, state, takefocus, 2295 textvariable, validate, validatecommand, vcmd, width, 2296 xscrollcommand.""" 2297 Widget.__init__(self, master, 'entry', cnf, kw) 2298 def delete(self, first, last=None): 2299 """Delete text from FIRST to LAST (not included).""" 2300 self.tk.call(self._w, 'delete', first, last) 2301 def get(self): 2302 """Return the text.""" 2303 return self.tk.call(self._w, 'get') 2304 def icursor(self, index): 2305 """Insert cursor at INDEX.""" 2306 self.tk.call(self._w, 'icursor', index) 2307 def index(self, index): 2308 """Return position of cursor.""" 2309 return getint(self.tk.call( 2310 self._w, 'index', index)) 2311 def insert(self, index, string): 2312 """Insert STRING at INDEX.""" 2313 self.tk.call(self._w, 'insert', index, string) 2314 def scan_mark(self, x): 2315 """Remember the current X, Y coordinates.""" 2316 self.tk.call(self._w, 'scan', 'mark', x) 2317 def scan_dragto(self, x): 2318 """Adjust the view of the canvas to 10 times the 2319 difference between X and Y and the coordinates given in 2320 scan_mark.""" 2321 self.tk.call(self._w, 'scan', 'dragto', x) 2322 def selection_adjust(self, index): 2323 """Adjust the end of the selection near the cursor to INDEX.""" 2324 self.tk.call(self._w, 'selection', 'adjust', index) 2325 select_adjust = selection_adjust 2326 def selection_clear(self): 2327 """Clear the selection if it is in this widget.""" 2328 self.tk.call(self._w, 'selection', 'clear') 2329 select_clear = selection_clear 2330 def selection_from(self, index): 2331 """Set the fixed end of a selection to INDEX.""" 2332 self.tk.call(self._w, 'selection', 'from', index) 2333 select_from = selection_from 2334 def selection_present(self): 2335 """Return whether the widget has the selection.""" 2336 return self.tk.getboolean( 2337 self.tk.call(self._w, 'selection', 'present')) 2338 select_present = selection_present 2339 def selection_range(self, start, end): 2340 """Set the selection from START to END (not included).""" 2341 self.tk.call(self._w, 'selection', 'range', start, end) 2342 select_range = selection_range 2343 def selection_to(self, index): 2344 """Set the variable end of a selection to INDEX.""" 2345 self.tk.call(self._w, 'selection', 'to', index) 2346 select_to = selection_to 2347 def xview(self, index): 2348 """Query and change horizontal position of the view.""" 2349 self.tk.call(self._w, 'xview', index) 2350 def xview_moveto(self, fraction): 2351 """Adjust the view in the window so that FRACTION of the 2352 total width of the entry is off-screen to the left.""" 2353 self.tk.call(self._w, 'xview', 'moveto', fraction) 2354 def xview_scroll(self, number, what): 2355 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" 2356 self.tk.call(self._w, 'xview', 'scroll', number, what) 2357 2358 class Frame(Widget): 2359 """Frame widget which may contain other widgets and can have a 3D border.""" 2360 def __init__(self, master=None, cnf={}, **kw): 2361 """Construct a frame widget with the parent MASTER. 2362 2363 Valid resource names: background, bd, bg, borderwidth, class, 2364 colormap, container, cursor, height, highlightbackground, 2365 highlightcolor, highlightthickness, relief, takefocus, visual, width.""" 2366 cnf = _cnfmerge((cnf, kw)) 2367 extra = () 2368 if cnf.has_key('class_'): 2369 extra = ('-class', cnf['class_']) 2370 del cnf['class_'] 2371 elif cnf.has_key('class'): 2372 extra = ('-class', cnf['class']) 2373 del cnf['class'] 2374 Widget.__init__(self, master, 'frame', cnf, {}, extra) 2375 2376 class Label(Widget): 2377 """Label widget which can display text and bitmaps.""" 2378 def __init__(self, master=None, cnf={}, **kw): 2379 """Construct a label widget with the parent MASTER. 2380 2381 STANDARD OPTIONS 2382 2383 activebackground, activeforeground, anchor, 2384 background, bitmap, borderwidth, cursor, 2385 disabledforeground, font, foreground, 2386 highlightbackground, highlightcolor, 2387 highlightthickness, image, justify, 2388 padx, pady, relief, takefocus, text, 2389 textvariable, underline, wraplength 2390 2391 WIDGET-SPECIFIC OPTIONS 2392 2393 height, state, width 2394 2395 """ 2396 Widget.__init__(self, master, 'label', cnf, kw) 2397 2398 class Listbox(Widget): 2399 """Listbox widget which can display a list of strings.""" 2400 def __init__(self, master=None, cnf={}, **kw): 2401 """Construct a listbox widget with the parent MASTER. 2402 2403 Valid resource names: background, bd, bg, borderwidth, cursor, 2404 exportselection, fg, font, foreground, height, highlightbackground, 2405 highlightcolor, highlightthickness, relief, selectbackground, 2406 selectborderwidth, selectforeground, selectmode, setgrid, takefocus, 2407 width, xscrollcommand, yscrollcommand, listvariable.""" 2408 Widget.__init__(self, master, 'listbox', cnf, kw) 2409 def activate(self, index): 2410 """Activate item identified by INDEX.""" 2411 self.tk.call(self._w, 'activate', index) 2412 def bbox(self, *args): 2413 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle 2414 which encloses the item identified by index in ARGS.""" 2415 return self._getints( 2416 self.tk.call((self._w, 'bbox') + args)) or None 2417 def curselection(self): 2418 """Return list of indices of currently selected item.""" 2419 # XXX Ought to apply self._getints()... 2420 return self.tk.splitlist(self.tk.call( 2421 self._w, 'curselection')) 2422 def delete(self, first, last=None): 2423 """Delete items from FIRST to LAST (not included).""" 2424 self.tk.call(self._w, 'delete', first, last) 2425 def get(self, first, last=None): 2426 """Get list of items from FIRST to LAST (not included).""" 2427 if last: 2428 return self.tk.splitlist(self.tk.call( 2429 self._w, 'get', first, last)) 2430 else: 2431 return self.tk.call(self._w, 'get', first) 2432 def index(self, index): 2433 """Return index of item identified with INDEX.""" 2434 i = self.tk.call(self._w, 'index', index) 2435 if i == 'none': return None 2436 return getint(i) 2437 def insert(self, index, *elements): 2438 """Insert ELEMENTS at INDEX.""" 2439 self.tk.call((self._w, 'insert', index) + elements) 2440 def nearest(self, y): 2441 """Get index of item which is nearest to y coordinate Y.""" 2442 return getint(self.tk.call( 2443 self._w, 'nearest', y)) 2444 def scan_mark(self, x, y): 2445 """Remember the current X, Y coordinates.""" 2446 self.tk.call(self._w, 'scan', 'mark', x, y) 2447 def scan_dragto(self, x, y): 2448 """Adjust the view of the listbox to 10 times the 2449 difference between X and Y and the coordinates given in 2450 scan_mark.""" 2451 self.tk.call(self._w, 'scan', 'dragto', x, y) 2452 def see(self, index): 2453 """Scroll such that INDEX is visible.""" 2454 self.tk.call(self._w, 'see', index) 2455 def selection_anchor(self, index): 2456 """Set the fixed end oft the selection to INDEX.""" 2457 self.tk.call(self._w, 'selection', 'anchor', index) 2458 select_anchor = selection_anchor 2459 def selection_clear(self, first, last=None): 2460 """Clear the selection from FIRST to LAST (not included).""" 2461 self.tk.call(self._w, 2462 'selection', 'clear', first, last) 2463 select_clear = selection_clear 2464 def selection_includes(self, index): 2465 """Return 1 if INDEX is part of the selection.""" 2466 return self.tk.getboolean(self.tk.call( 2467 self._w, 'selection', 'includes', index)) 2468 select_includes = selection_includes 2469 def selection_set(self, first, last=None): 2470 """Set the selection from FIRST to LAST (not included) without 2471 changing the currently selected elements.""" 2472 self.tk.call(self._w, 'selection', 'set', first, last) 2473 select_set = selection_set 2474 def size(self): 2475 """Return the number of elements in the listbox.""" 2476 return getint(self.tk.call(self._w, 'size')) 2477 def xview(self, *what): 2478 """Query and change horizontal position of the view.""" 2479 if not what: 2480 return self._getdoubles(self.tk.call(self._w, 'xview')) 2481 self.tk.call((self._w, 'xview') + what) 2482 def xview_moveto(self, fraction): 2483 """Adjust the view in the window so that FRACTION of the 2484 total width of the entry is off-screen to the left.""" 2485 self.tk.call(self._w, 'xview', 'moveto', fraction) 2486 def xview_scroll(self, number, what): 2487 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" 2488 self.tk.call(self._w, 'xview', 'scroll', number, what) 2489 def yview(self, *what): 2490 """Query and change vertical position of the view.""" 2491 if not what: 2492 return self._getdoubles(self.tk.call(self._w, 'yview')) 2493 self.tk.call((self._w, 'yview') + what) 2494 def yview_moveto(self, fraction): 2495 """Adjust the view in the window so that FRACTION of the 2496 total width of the entry is off-screen to the top.""" 2497 self.tk.call(self._w, 'yview', 'moveto', fraction) 2498 def yview_scroll(self, number, what): 2499 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" 2500 self.tk.call(self._w, 'yview', 'scroll', number, what) 2501 def itemcget(self, index, option): 2502 """Return the resource value for an ITEM and an OPTION.""" 2503 return self.tk.call( 2504 (self._w, 'itemcget') + (index, '-'+option)) 2505 def itemconfigure(self, index, cnf=None, **kw): 2506 """Configure resources of an ITEM. 2507 2508 The values for resources are specified as keyword arguments. 2509 To get an overview about the allowed keyword arguments 2510 call the method without arguments. 2511 Valid resource names: background, bg, foreground, fg, 2512 selectbackground, selectforeground.""" 2513 return self._configure(('itemconfigure', index), cnf, kw) 2514 itemconfig = itemconfigure 2515 2516 class Menu(Widget): 2517 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus.""" 2518 def __init__(self, master=None, cnf={}, **kw): 2519 """Construct menu widget with the parent MASTER. 2520 2521 Valid resource names: activebackground, activeborderwidth, 2522 activeforeground, background, bd, bg, borderwidth, cursor, 2523 disabledforeground, fg, font, foreground, postcommand, relief, 2524 selectcolor, takefocus, tearoff, tearoffcommand, title, type.""" 2525 Widget.__init__(self, master, 'menu', cnf, kw) 2526 def tk_bindForTraversal(self): 2527 pass # obsolete since Tk 4.0 2528 def tk_mbPost(self): 2529 self.tk.call('tk_mbPost', self._w) 2530 def tk_mbUnpost(self): 2531 self.tk.call('tk_mbUnpost') 2532 def tk_traverseToMenu(self, char): 2533 self.tk.call('tk_traverseToMenu', self._w, char) 2534 def tk_traverseWithinMenu(self, char): 2535 self.tk.call('tk_traverseWithinMenu', self._w, char) 2536 def tk_getMenuButtons(self): 2537 return self.tk.call('tk_getMenuButtons', self._w) 2538 def tk_nextMenu(self, count): 2539 self.tk.call('tk_nextMenu', count) 2540 def tk_nextMenuEntry(self, count): 2541 self.tk.call('tk_nextMenuEntry', count) 2542 def tk_invokeMenu(self): 2543 self.tk.call('tk_invokeMenu', self._w) 2544 def tk_firstMenu(self): 2545 self.tk.call('tk_firstMenu', self._w) 2546 def tk_mbButtonDown(self): 2547 self.tk.call('tk_mbButtonDown', self._w) 2548 def tk_popup(self, x, y, entry=""): 2549 """Post the menu at position X,Y with entry ENTRY.""" 2550 self.tk.call('tk_popup', self._w, x, y, entry) 2551 def activate(self, index): 2552 """Activate entry at INDEX.""" 2553 self.tk.call(self._w, 'activate', index) 2554 def add(self, itemType, cnf={}, **kw): 2555 """Internal function.""" 2556 self.tk.call((self._w, 'add', itemType) + 2557 self._options(cnf, kw)) 2558 def add_cascade(self, cnf={}, **kw): 2559 """Add hierarchical menu item.""" 2560 self.add('cascade', cnf or kw) 2561 def add_checkbutton(self, cnf={}, **kw): 2562 """Add checkbutton menu item.""" 2563 self.add('checkbutton', cnf or kw) 2564 def add_command(self, cnf={}, **kw): 2565 """Add command menu item.""" 2566 self.add('command', cnf or kw) 2567 def add_radiobutton(self, cnf={}, **kw): 2568 """Addd radio menu item.""" 2569 self.add('radiobutton', cnf or kw) 2570 def add_separator(self, cnf={}, **kw): 2571 """Add separator.""" 2572 self.add('separator', cnf or kw) 2573 def insert(self, index, itemType, cnf={}, **kw): 2574 """Internal function.""" 2575 self.tk.call((self._w, 'insert', index, itemType) + 2576 self._options(cnf, kw)) 2577 def insert_cascade(self, index, cnf={}, **kw): 2578 """Add hierarchical menu item at INDEX.""" 2579 self.insert(index, 'cascade', cnf or kw) 2580 def insert_checkbutton(self, index, cnf={}, **kw): 2581 """Add checkbutton menu item at INDEX.""" 2582 self.insert(index, 'checkbutton', cnf or kw) 2583 def insert_command(self, index, cnf={}, **kw): 2584 """Add command menu item at INDEX.""" 2585 self.insert(index, 'command', cnf or kw) 2586 def insert_radiobutton(self, index, cnf={}, **kw): 2587 """Addd radio menu item at INDEX.""" 2588 self.insert(index, 'radiobutton', cnf or kw) 2589 def insert_separator(self, index, cnf={}, **kw): 2590 """Add separator at INDEX.""" 2591 self.insert(index, 'separator', cnf or kw) 2592 def delete(self, index1, index2=None): 2593 """Delete menu items between INDEX1 and INDEX2 (not included).""" 2594 self.tk.call(self._w, 'delete', index1, index2) 2595 def entrycget(self, index, option): 2596 """Return the resource value of an menu item for OPTION at INDEX.""" 2597 return self.tk.call(self._w, 'entrycget', index, '-' + option) 2598 def entryconfigure(self, index, cnf=None, **kw): 2599 """Configure a menu item at INDEX.""" 2600 return self._configure(('entryconfigure', index), cnf, kw) 2601 entryconfig = entryconfigure 2602 def index(self, index): 2603 """Return the index of a menu item identified by INDEX.""" 2604 i = self.tk.call(self._w, 'index', index) 2605 if i == 'none': return None 2606 return getint(i) 2607 def invoke(self, index): 2608 """Invoke a menu item identified by INDEX and execute 2609 the associated command.""" 2610 return self.tk.call(self._w, 'invoke', index) 2611 def post(self, x, y): 2612 """Display a menu at position X,Y.""" 2613 self.tk.call(self._w, 'post', x, y) 2614 def type(self, index): 2615 """Return the type of the menu item at INDEX.""" 2616 return self.tk.call(self._w, 'type', index) 2617 def unpost(self): 2618 """Unmap a menu.""" 2619 self.tk.call(self._w, 'unpost') 2620 def yposition(self, index): 2621 """Return the y-position of the topmost pixel of the menu item at INDEX.""" 2622 return getint(self.tk.call( 2623 self._w, 'yposition', index)) 2624 2625 class Menubutton(Widget): 2626 """Menubutton widget, obsolete since Tk8.0.""" 2627 def __init__(self, master=None, cnf={}, **kw): 2628 Widget.__init__(self, master, 'menubutton', cnf, kw) 2629 2630 class Message(Widget): 2631 """Message widget to display multiline text. Obsolete since Label does it too.""" 2632 def __init__(self, master=None, cnf={}, **kw): 2633 Widget.__init__(self, master, 'message', cnf, kw) 2634 2635 class Radiobutton(Widget): 2636 """Radiobutton widget which shows only one of several buttons in on-state.""" 2637 def __init__(self, master=None, cnf={}, **kw): 2638 """Construct a radiobutton widget with the parent MASTER. 2639 2640 Valid resource names: activebackground, activeforeground, anchor, 2641 background, bd, bg, bitmap, borderwidth, command, cursor, 2642 disabledforeground, fg, font, foreground, height, 2643 highlightbackground, highlightcolor, highlightthickness, image, 2644 indicatoron, justify, padx, pady, relief, selectcolor, selectimage, 2645 state, takefocus, text, textvariable, underline, value, variable, 2646 width, wraplength.""" 2647 Widget.__init__(self, master, 'radiobutton', cnf, kw) 2648 def deselect(self): 2649 """Put the button in off-state.""" 2650 2651 self.tk.call(self._w, 'deselect') 2652 def flash(self): 2653 """Flash the button.""" 2654 self.tk.call(self._w, 'flash') 2655 def invoke(self): 2656 """Toggle the button and invoke a command if given as resource.""" 2657 return self.tk.call(self._w, 'invoke') 2658 def select(self): 2659 """Put the button in on-state.""" 2660 self.tk.call(self._w, 'select') 2661 2662 class Scale(Widget): 2663 """Scale widget which can display a numerical scale.""" 2664 def __init__(self, master=None, cnf={}, **kw): 2665 """Construct a scale widget with the parent MASTER. 2666 2667 Valid resource names: activebackground, background, bigincrement, bd, 2668 bg, borderwidth, command, cursor, digits, fg, font, foreground, from, 2669 highlightbackground, highlightcolor, highlightthickness, label, 2670 length, orient, relief, repeatdelay, repeatinterval, resolution, 2671 showvalue, sliderlength, sliderrelief, state, takefocus, 2672 tickinterval, to, troughcolor, variable, width.""" 2673 Widget.__init__(self, master, 'scale', cnf, kw) 2674 def get(self): 2675 """Get the current value as integer or float.""" 2676 value = self.tk.call(self._w, 'get') 2677 try: 2678 return getint(value) 2679 except ValueError: 2680 return getdouble(value) 2681 def set(self, value): 2682 """Set the value to VALUE.""" 2683 self.tk.call(self._w, 'set', value) 2684 def coords(self, value=None): 2685 """Return a tuple (X,Y) of the point along the centerline of the 2686 trough that corresponds to VALUE or the current value if None is 2687 given.""" 2688 2689 return self._getints(self.tk.call(self._w, 'coords', value)) 2690 def identify(self, x, y): 2691 """Return where the point X,Y lies. Valid return values are "slider", 2692 "though1" and "though2".""" 2693 return self.tk.call(self._w, 'identify', x, y) 2694 2695 class Scrollbar(Widget): 2696 """Scrollbar widget which displays a slider at a certain position.""" 2697 def __init__(self, master=None, cnf={}, **kw): 2698 """Construct a scrollbar widget with the parent MASTER. 2699 2700 Valid resource names: activebackground, activerelief, 2701 background, bd, bg, borderwidth, command, cursor, 2702 elementborderwidth, highlightbackground, 2703 highlightcolor, highlightthickness, jump, orient, 2704 relief, repeatdelay, repeatinterval, takefocus, 2705 troughcolor, width.""" 2706 Widget.__init__(self, master, 'scrollbar', cnf, kw) 2707 def activate(self, index): 2708 """Display the element at INDEX with activebackground and activerelief. 2709 INDEX can be "arrow1","slider" or "arrow2".""" 2710 self.tk.call(self._w, 'activate', index) 2711 def delta(self, deltax, deltay): 2712 """Return the fractional change of the scrollbar setting if it 2713 would be moved by DELTAX or DELTAY pixels.""" 2714 return getdouble( 2715 self.tk.call(self._w, 'delta', deltax, deltay)) 2716 def fraction(self, x, y): 2717 """Return the fractional value which corresponds to a slider 2718 position of X,Y.""" 2719 return getdouble(self.tk.call(self._w, 'fraction', x, y)) 2720 def identify(self, x, y): 2721 """Return the element under position X,Y as one of 2722 "arrow1","slider","arrow2" or "".""" 2723 return self.tk.call(self._w, 'identify', x, y) 2724 def get(self): 2725 """Return the current fractional values (upper and lower end) 2726 of the slider position.""" 2727 return self._getdoubles(self.tk.call(self._w, 'get')) 2728 def set(self, *args): 2729 """Set the fractional values of the slider position (upper and 2730 lower ends as value between 0 and 1).""" 2731 self.tk.call((self._w, 'set') + args) 2732 2733 2734 2735 class Text(Widget): 2736 """Text widget which can display text in various forms.""" 2737 def __init__(self, master=None, cnf={}, **kw): 2738 """Construct a text widget with the parent MASTER. 2739 2740 STANDARD OPTIONS 2741 2742 background, borderwidth, cursor, 2743 exportselection, font, foreground, 2744 highlightbackground, highlightcolor, 2745 highlightthickness, insertbackground, 2746 insertborderwidth, insertofftime, 2747 insertontime, insertwidth, padx, pady, 2748 relief, selectbackground, 2749 selectborderwidth, selectforeground, 2750 setgrid, takefocus, 2751 xscrollcommand, yscrollcommand, 2752 2753 WIDGET-SPECIFIC OPTIONS 2754 2755 autoseparators, height, maxundo, 2756 spacing1, spacing2, spacing3, 2757 state, tabs, undo, width, wrap, 2758 2759 """ 2760 Widget.__init__(self, master, 'text', cnf, kw) 2761 def bbox(self, *args): 2762 """Return a tuple of (x,y,width,height) which gives the bounding 2763 box of the visible part of the character at the index in ARGS.""" 2764 return self._getints( 2765 self.tk.call((self._w, 'bbox') + args)) or None 2766 def tk_textSelectTo(self, index): 2767 self.tk.call('tk_textSelectTo', self._w, index) 2768 def tk_textBackspace(self): 2769 self.tk.call('tk_textBackspace', self._w) 2770 def tk_textIndexCloser(self, a, b, c): 2771 self.tk.call('tk_textIndexCloser', self._w, a, b, c) 2772 def tk_textResetAnchor(self, index): 2773 self.tk.call('tk_textResetAnchor', self._w, index) 2774 def compare(self, index1, op, index2): 2775 """Return whether between index INDEX1 and index INDEX2 the 2776 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.""" 2777 return self.tk.getboolean(self.tk.call( 2778 self._w, 'compare', index1, op, index2)) 2779 def debug(self, boolean=None): 2780 """Turn on the internal consistency checks of the B-Tree inside the text 2781 widget according to BOOLEAN.""" 2782 return self.tk.getboolean(self.tk.call( 2783 self._w, 'debug', boolean)) 2784 def delete(self, index1, index2=None): 2785 """Delete the characters between INDEX1 and INDEX2 (not included).""" 2786 self.tk.call(self._w, 'delete', index1, index2) 2787 def dlineinfo(self, index): 2788 """Return tuple (x,y,width,height,baseline) giving the bounding box 2789 and baseline position of the visible part of the line containing 2790 the character at INDEX.""" 2791 return self._getints(self.tk.call(self._w, 'dlineinfo', index)) 2792 def dump(self, index1, index2=None, command=None, **kw): 2793 """Return the contents of the widget between index1 and index2. 2794 2795 The type of contents returned in filtered based on the keyword 2796 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are 2797 given and true, then the corresponding items are returned. The result 2798 is a list of triples of the form (key, value, index). If none of the 2799 keywords are true then 'all' is used by default. 2800 2801 If the 'command' argument is given, it is called once for each element 2802 of the list of triples, with the values of each triple serving as the 2803 arguments to the function. In this case the list is not returned.""" 2804 args = [] 2805 func_name = None 2806 result = None 2807 if not command: 2808 # Never call the dump command without the -command flag, since the 2809 # output could involve Tcl quoting and would be a pain to parse 2810 # right. Instead just set the command to build a list of triples 2811 # as if we had done the parsing. 2812 result = [] 2813 def append_triple(key, value, index, result=result): 2814 result.append((key, value, index)) 2815 command = append_triple 2816 try: 2817 if not isinstance(command, str): 2818 func_name = command = self._register(command) 2819 args += ["-command", command] 2820 for key in kw: 2821 if kw[key]: args.append("-" + key) 2822 args.append(index1) 2823 if index2: 2824 args.append(index2) 2825 self.tk.call(self._w, "dump", *args) 2826 return result 2827 finally: 2828 if func_name: 2829 self.deletecommand(func_name) 2830 2831 ## new in tk8.4 2832 def edit(self, *args): 2833 """Internal method 2834 2835 This method controls the undo mechanism and 2836 the modified flag. The exact behavior of the 2837 command depends on the option argument that 2838 follows the edit argument. The following forms 2839 of the command are currently supported: 2840 2841 edit_modified, edit_redo, edit_reset, edit_separator 2842 and edit_undo 2843 2844 """ 2845 return self._getints( 2846 self.tk.call((self._w, 'edit') + args)) or () 2847 2848 def edit_modified(self, arg=None): 2849 """Get or Set the modified flag 2850 2851 If arg is not specified, returns the modified 2852 flag of the widget. The insert, delete, edit undo and 2853 edit redo commands or the user can set or clear the 2854 modified flag. If boolean is specified, sets the 2855 modified flag of the widget to arg. 2856 """ 2857 return self.edit("modified", arg) 2858 2859 def edit_redo(self): 2860 """Redo the last undone edit 2861 2862 When the undo option is true, reapplies the last 2863 undone edits provided no other edits were done since 2864 then. Generates an error when the redo stack is empty. 2865 Does nothing when the undo option is false. 2866 """ 2867 return self.edit("redo") 2868 2869 def edit_reset(self): 2870 """Clears the undo and redo stacks 2871 """ 2872 return self.edit("reset") 2873 2874 def edit_separator(self): 2875 """Inserts a separator (boundary) on the undo stack. 2876 2877 Does nothing when the undo option is false 2878 """ 2879 return self.edit("separator") 2880 2881 def edit_undo(self): 2882 """Undoes the last edit action 2883 2884 If the undo option is true. An edit action is defined 2885 as all the insert and delete commands that are recorded 2886 on the undo stack in between two separators. Generates 2887 an error when the undo stack is empty. Does nothing 2888 when the undo option is false 2889 """ 2890 return self.edit("undo") 2891 2892 def get(self, index1, index2=None): 2893 """Return the text from INDEX1 to INDEX2 (not included).""" 2894 return self.tk.call(self._w, 'get', index1, index2) 2895 # (Image commands are new in 8.0) 2896 def image_cget(self, index, option): 2897 """Return the value of OPTION of an embedded image at INDEX.""" 2898 if option[:1] != "-": 2899 option = "-" + option 2900 if option[-1:] == "_": 2901 option = option[:-1] 2902 return self.tk.call(self._w, "image", "cget", index, option) 2903 def image_configure(self, index, cnf=None, **kw): 2904 """Configure an embedded image at INDEX.""" 2905 return self._configure(('image', 'configure', index), cnf, kw) 2906 def image_create(self, index, cnf={}, **kw): 2907 """Create an embedded image at INDEX.""" 2908 return self.tk.call( 2909 self._w, "image", "create", index, 2910 *self._options(cnf, kw)) 2911 def image_names(self): 2912 """Return all names of embedded images in this widget.""" 2913 return self.tk.call(self._w, "image", "names") 2914 def index(self, index): 2915 """Return the index in the form line.char for INDEX.""" 2916 return self.tk.call(self._w, 'index', index) 2917 def insert(self, index, chars, *args): 2918 """Insert CHARS before the characters at INDEX. An additional 2919 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS.""" 2920 self.tk.call((self._w, 'insert', index, chars) + args) 2921 def mark_gravity(self, markName, direction=None): 2922 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). 2923 Return the current value if None is given for DIRECTION.""" 2924 return self.tk.call( 2925 (self._w, 'mark', 'gravity', markName, direction)) 2926 def mark_names(self): 2927 """Return all mark names.""" 2928 return self.tk.splitlist(self.tk.call( 2929 self._w, 'mark', 'names')) 2930 def mark_set(self, markName, index): 2931 """Set mark MARKNAME before the character at INDEX.""" 2932 self.tk.call(self._w, 'mark', 'set', markName, index) 2933 def mark_unset(self, *markNames): 2934 """Delete all marks in MARKNAMES.""" 2935 self.tk.call((self._w, 'mark', 'unset') + markNames) 2936 def mark_next(self, index): 2937 """Return the name of the next mark after INDEX.""" 2938 return self.tk.call(self._w, 'mark', 'next', index) or None 2939 def mark_previous(self, index): 2940 """Return the name of the previous mark before INDEX.""" 2941 return self.tk.call(self._w, 'mark', 'previous', index) or None 2942 def scan_mark(self, x, y): 2943 """Remember the current X, Y coordinates.""" 2944 self.tk.call(self._w, 'scan', 'mark', x, y) 2945 def scan_dragto(self, x, y): 2946 """Adjust the view of the text to 10 times the 2947 difference between X and Y and the coordinates given in 2948 scan_mark.""" 2949 self.tk.call(self._w, 'scan', 'dragto', x, y) 2950 def search(self, pattern, index, stopindex=None, 2951 forwards=None, backwards=None, exact=None, 2952 regexp=None, nocase=None, count=None): 2953 """Search PATTERN beginning from INDEX until STOPINDEX. 2954 Return the index of the first character of a match or an empty string.""" 2955 args = [self._w, 'search'] 2956 if forwards: args.append('-forwards') 2957 if backwards: args.append('-backwards') 2958 if exact: args.append('-exact') 2959 if regexp: args.append('-regexp') 2960 if nocase: args.append('-nocase') 2961 if count: args.append('-count'); args.append(count) 2962 if pattern[0] == '-': args.append('--') 2963 args.append(pattern) 2964 args.append(index) 2965 if stopindex: args.append(stopindex) 2966 return self.tk.call(tuple(args)) 2967 def see(self, index): 2968 """Scroll such that the character at INDEX is visible.""" 2969 self.tk.call(self._w, 'see', index) 2970 def tag_add(self, tagName, index1, *args): 2971 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. 2972 Additional pairs of indices may follow in ARGS.""" 2973 self.tk.call( 2974 (self._w, 'tag', 'add', tagName, index1) + args) 2975 def tag_unbind(self, tagName, sequence, funcid=None): 2976 """Unbind for all characters with TAGNAME for event SEQUENCE the 2977 function identified with FUNCID.""" 2978 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') 2979 if funcid: 2980 self.deletecommand(funcid) 2981 def tag_bind(self, tagName, sequence, func, add=None): 2982 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. 2983 2984 An additional boolean parameter ADD specifies whether FUNC will be 2985 called additionally to the other bound function or whether it will 2986 replace the previous function. See bind for the return value.""" 2987 return self._bind((self._w, 'tag', 'bind', tagName), 2988 sequence, func, add) 2989 def tag_cget(self, tagName, option): 2990 """Return the value of OPTION for tag TAGNAME.""" 2991 if option[:1] != '-': 2992 option = '-' + option 2993 if option[-1:] == '_': 2994 option = option[:-1] 2995 return self.tk.call(self._w, 'tag', 'cget', tagName, option) 2996 def tag_configure(self, tagName, cnf=None, **kw): 2997 """Configure a tag TAGNAME.""" 2998 return self._configure(('tag', 'configure', tagName), cnf, kw) 2999 tag_config = tag_configure 3000 def tag_delete(self, *tagNames): 3001 """Delete all tags in TAGNAMES.""" 3002 self.tk.call((self._w, 'tag', 'delete') + tagNames) 3003 def tag_lower(self, tagName, belowThis=None): 3004 """Change the priority of tag TAGNAME such that it is lower 3005 than the priority of BELOWTHIS.""" 3006 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis) 3007 def tag_names(self, index=None): 3008 """Return a list of all tag names.""" 3009 return self.tk.splitlist( 3010 self.tk.call(self._w, 'tag', 'names', index)) 3011 def tag_nextrange(self, tagName, index1, index2=None): 3012 """Return a list of start and end index for the first sequence of 3013 characters between INDEX1 and INDEX2 which all have tag TAGNAME. 3014 The text is searched forward from INDEX1.""" 3015 return self.tk.splitlist(self.tk.call( 3016 self._w, 'tag', 'nextrange', tagName, index1, index2)) 3017 def tag_prevrange(self, tagName, index1, index2=None): 3018 """Return a list of start and end index for the first sequence of 3019 characters between INDEX1 and INDEX2 which all have tag TAGNAME. 3020 The text is searched backwards from INDEX1.""" 3021 return self.tk.splitlist(self.tk.call( 3022 self._w, 'tag', 'prevrange', tagName, index1, index2)) 3023 def tag_raise(self, tagName, aboveThis=None): 3024 """Change the priority of tag TAGNAME such that it is higher 3025 than the priority of ABOVETHIS.""" 3026 self.tk.call( 3027 self._w, 'tag', 'raise', tagName, aboveThis) 3028 def tag_ranges(self, tagName): 3029 """Return a list of ranges of text which have tag TAGNAME.""" 3030 return self.tk.splitlist(self.tk.call( 3031 self._w, 'tag', 'ranges', tagName)) 3032 def tag_remove(self, tagName, index1, index2=None): 3033 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2.""" 3034 self.tk.call( 3035 self._w, 'tag', 'remove', tagName, index1, index2) 3036 def window_cget(self, index, option): 3037 """Return the value of OPTION of an embedded window at INDEX.""" 3038 if option[:1] != '-': 3039 option = '-' + option 3040 if option[-1:] == '_': 3041 option = option[:-1] 3042 return self.tk.call(self._w, 'window', 'cget', index, option) 3043 def window_configure(self, index, cnf=None, **kw): 3044 """Configure an embedded window at INDEX.""" 3045 return self._configure(('window', 'configure', index), cnf, kw) 3046 window_config = window_configure 3047 def window_create(self, index, cnf={}, **kw): 3048 """Create a window at INDEX.""" 3049 self.tk.call( 3050 (self._w, 'window', 'create', index) 3051 + self._options(cnf, kw)) 3052 def window_names(self): 3053 """Return all names of embedded windows in this widget.""" 3054 return self.tk.splitlist( 3055 self.tk.call(self._w, 'window', 'names')) 3056 def xview(self, *what): 3057 """Query and change horizontal position of the view.""" 3058 if not what: 3059 return self._getdoubles(self.tk.call(self._w, 'xview')) 3060 self.tk.call((self._w, 'xview') + what) 3061 def xview_moveto(self, fraction): 3062 """Adjusts the view in the window so that FRACTION of the 3063 total width of the canvas is off-screen to the left.""" 3064 self.tk.call(self._w, 'xview', 'moveto', fraction) 3065 def xview_scroll(self, number, what): 3066 """Shift the x-view according to NUMBER which is measured 3067 in "units" or "pages" (WHAT).""" 3068 self.tk.call(self._w, 'xview', 'scroll', number, what) 3069 def yview(self, *what): 3070 """Query and change vertical position of the view.""" 3071 if not what: 3072 return self._getdoubles(self.tk.call(self._w, 'yview')) 3073 self.tk.call((self._w, 'yview') + what) 3074 def yview_moveto(self, fraction): 3075 """Adjusts the view in the window so that FRACTION of the 3076 total height of the canvas is off-screen to the top.""" 3077 self.tk.call(self._w, 'yview', 'moveto', fraction) 3078 def yview_scroll(self, number, what): 3079 """Shift the y-view according to NUMBER which is measured 3080 in "units" or "pages" (WHAT).""" 3081 self.tk.call(self._w, 'yview', 'scroll', number, what) 3082 def yview_pickplace(self, *what): 3083 """Obsolete function, use see.""" 3084 self.tk.call((self._w, 'yview', '-pickplace') + what) 3085 3086 3087 class _setit: 3088 """Internal class. It wraps the command in the widget OptionMenu.""" 3089 def __init__(self, var, value, callback=None): 3090 self.__value = value 3091 self.__var = var 3092 self.__callback = callback 3093 def __call__(self, *args): 3094 self.__var.set(self.__value) 3095 if self.__callback: 3096 self.__callback(self.__value, *args) 3097 3098 class OptionMenu(Menubutton): 3099 """OptionMenu which allows the user to select a value from a menu.""" 3100 def __init__(self, master, variable, value, *values, **kwargs): 3101 """Construct an optionmenu widget with the parent MASTER, with 3102 the resource textvariable set to VARIABLE, the initially selected 3103 value VALUE, the other menu values VALUES and an additional 3104 keyword argument command.""" 3105 kw = {"borderwidth": 2, "textvariable": variable, 3106 "indicatoron": 1, "relief": RAISED, "anchor": "c", 3107 "highlightthickness": 2} 3108 Widget.__init__(self, master, "menubutton", kw) 3109 self.widgetName = 'tk_optionMenu' 3110 menu = self.__menu = Menu(self, name="menu", tearoff=0) 3111 self.menuname = menu._w 3112 # 'command' is the only supported keyword 3113 callback = kwargs.get('command') 3114 if kwargs.has_key('command'): 3115 del kwargs['command'] 3116 if kwargs: 3117 raise TclError, 'unknown option -'+kwargs.keys()[0] 3118 menu.add_command(label=value, 3119 command=_setit(variable, value, callback)) 3120 for v in values: 3121 menu.add_command(label=v, 3122 command=_setit(variable, v, callback)) 3123 self["menu"] = menu 3124 3125 def __getitem__(self, name): 3126 if name == 'menu': 3127 return self.__menu 3128 return Widget.__getitem__(self, name) 3129 3130 def destroy(self): 3131 """Destroy this widget and the associated menu.""" 3132 Menubutton.destroy(self) 3133 self.__menu = None 3134 3135 class Image: 3136 """Base class for images.""" 3137 _last_id = 0 3138 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): 3139 self.name = None 3140 if not master: 3141 master = _default_root 3142 if not master: 3143 raise RuntimeError, 'Too early to create image' 3144 self.tk = master.tk 3145 if not name: 3146 Image._last_id += 1 3147 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x> 3148 # The following is needed for systems where id(x) 3149 # can return a negative number, such as Linux/m68k: 3150 if name[0] == '-': name = '_' + name[1:] 3151 if kw and cnf: cnf = _cnfmerge((cnf, kw)) 3152 elif kw: cnf = kw 3153 options = () 3154 for k, v in cnf.items(): 3155 if callable(v): 3156 v = self._register(v) 3157 options = options + ('-'+k, v) 3158 self.tk.call(('image', 'create', imgtype, name,) + options) 3159 self.name = name 3160 def __str__(self): return self.name 3161 def __del__(self): 3162 if self.name: 3163 try: 3164 self.tk.call('image', 'delete', self.name) 3165 except TclError: 3166 # May happen if the root was destroyed 3167 pass 3168 def __setitem__(self, key, value): 3169 self.tk.call(self.name, 'configure', '-'+key, value) 3170 def __getitem__(self, key): 3171 return self.tk.call(self.name, 'configure', '-'+key) 3172 def configure(self, **kw): 3173 """Configure the image.""" 3174 res = () 3175 for k, v in _cnfmerge(kw).items(): 3176 if v is not None: 3177 if k[-1] == '_': k = k[:-1] 3178 if callable(v): 3179 v = self._register(v) 3180 res = res + ('-'+k, v) 3181 self.tk.call((self.name, 'config') + res) 3182 config = configure 3183 def height(self): 3184 """Return the height of the image.""" 3185 return getint( 3186 self.tk.call('image', 'height', self.name)) 3187 def type(self): 3188 """Return the type of the imgage, e.g. "photo" or "bitmap".""" 3189 return self.tk.call('image', 'type', self.name) 3190 def width(self): 3191 """Return the width of the image.""" 3192 return getint( 3193 self.tk.call('image', 'width', self.name)) 3194 3195 class PhotoImage(Image): 3196 """Widget which can display colored images in GIF, PPM/PGM format.""" 3197 def __init__(self, name=None, cnf={}, master=None, **kw): 3198 """Create an image with NAME. 3199 3200 Valid resource names: data, format, file, gamma, height, palette, 3201 width.""" 3202 Image.__init__(self, 'photo', name, cnf, master, **kw) 3203 def blank(self): 3204 """Display a transparent image.""" 3205 self.tk.call(self.name, 'blank') 3206 def cget(self, option): 3207 """Return the value of OPTION.""" 3208 return self.tk.call(self.name, 'cget', '-' + option) 3209 # XXX config 3210 def __getitem__(self, key): 3211 return self.tk.call(self.name, 'cget', '-' + key) 3212 # XXX copy -from, -to, ...? 3213 def copy(self): 3214 """Return a new PhotoImage with the same image as this widget.""" 3215 destImage = PhotoImage() 3216 self.tk.call(destImage, 'copy', self.name) 3217 return destImage 3218 def zoom(self,x,y=''): 3219 """Return a new PhotoImage with the same image as this widget 3220 but zoom it with X and Y.""" 3221 destImage = PhotoImage() 3222 if y=='': y=x 3223 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) 3224 return destImage 3225 def subsample(self,x,y=''): 3226 """Return a new PhotoImage based on the same image as this widget 3227 but use only every Xth or Yth pixel.""" 3228 destImage = PhotoImage() 3229 if y=='': y=x 3230 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) 3231 return destImage 3232 def get(self, x, y): 3233 """Return the color (red, green, blue) of the pixel at X,Y.""" 3234 return self.tk.call(self.name, 'get', x, y) 3235 def put(self, data, to=None): 3236 """Put row formated colors to image starting from 3237 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))""" 3238 args = (self.name, 'put', data) 3239 if to: 3240 if to[0] == '-to': 3241 to = to[1:] 3242 args = args + ('-to',) + tuple(to) 3243 self.tk.call(args) 3244 # XXX read 3245 def write(self, filename, format=None, from_coords=None): 3246 """Write image to file FILENAME in FORMAT starting from 3247 position FROM_COORDS.""" 3248 args = (self.name, 'write', filename) 3249 if format: 3250 args = args + ('-format', format) 3251 if from_coords: 3252 args = args + ('-from',) + tuple(from_coords) 3253 self.tk.call(args) 3254 3255 class BitmapImage(Image): 3256 """Widget which can display a bitmap.""" 3257 def __init__(self, name=None, cnf={}, master=None, **kw): 3258 """Create a bitmap with NAME. 3259 3260 Valid resource names: background, data, file, foreground, maskdata, maskfile.""" 3261 Image.__init__(self, 'bitmap', name, cnf, master, **kw) 3262 3263 def image_names(): return _default_root.tk.call('image', 'names') 3264 def image_types(): return _default_root.tk.call('image', 'types') 3265 3266 3267 class Spinbox(Widget): 3268 """spinbox widget.""" 3269 def __init__(self, master=None, cnf={}, **kw): 3270 """Construct a spinbox widget with the parent MASTER. 3271 3272 STANDARD OPTIONS 3273 3274 activebackground, background, borderwidth, 3275 cursor, exportselection, font, foreground, 3276 highlightbackground, highlightcolor, 3277 highlightthickness, insertbackground, 3278 insertborderwidth, insertofftime, 3279 insertontime, insertwidth, justify, relief, 3280 repeatdelay, repeatinterval, 3281 selectbackground, selectborderwidth 3282 selectforeground, takefocus, textvariable 3283 xscrollcommand. 3284 3285 WIDGET-SPECIFIC OPTIONS 3286 3287 buttonbackground, buttoncursor, 3288 buttondownrelief, buttonuprelief, 3289 command, disabledbackground, 3290 disabledforeground, format, from, 3291 invalidcommand, increment, 3292 readonlybackground, state, to, 3293 validate, validatecommand values, 3294 width, wrap, 3295 """ 3296 Widget.__init__(self, master, 'spinbox', cnf, kw) 3297 3298 def bbox(self, index): 3299 """Return a tuple of X1,Y1,X2,Y2 coordinates for a 3300 rectangle which encloses the character given by index. 3301 3302 The first two elements of the list give the x and y 3303 coordinates of the upper-left corner of the screen 3304 area covered by the character (in pixels relative 3305 to the widget) and the last two elements give the 3306 width and height of the character, in pixels. The 3307 bounding box may refer to a region outside the 3308 visible area of the window. 3309 """ 3310 return self.tk.call(self._w, 'bbox', index) 3311 3312 def delete(self, first, last=None): 3313 """Delete one or more elements of the spinbox. 3314 3315 First is the index of the first character to delete, 3316 and last is the index of the character just after 3317 the last one to delete. If last isn't specified it 3318 defaults to first+1, i.e. a single character is 3319 deleted. This command returns an empty string. 3320 """ 3321 return self.tk.call(self._w, 'delete', first, last) 3322 3323 def get(self): 3324 """Returns the spinbox's string""" 3325 return self.tk.call(self._w, 'get') 3326 3327 def icursor(self, index): 3328 """Alter the position of the insertion cursor. 3329 3330 The insertion cursor will be displayed just before 3331 the character given by index. Returns an empty string 3332 """ 3333 return self.tk.call(self._w, 'icursor', index) 3334 3335 def identify(self, x, y): 3336 """Returns the name of the widget at position x, y 3337 3338 Return value is one of: none, buttondown, buttonup, entry 3339 """ 3340 return self.tk.call(self._w, 'identify', x, y) 3341 3342 def index(self, index): 3343 """Returns the numerical index corresponding to index 3344 """ 3345 return self.tk.call(self._w, 'index', index) 3346 3347 def insert(self, index, s): 3348 """Insert string s at index 3349 3350 Returns an empty string. 3351 """ 3352 return self.tk.call(self._w, 'insert', index, s) 3353 3354 def invoke(self, element): 3355 """Causes the specified element to be invoked 3356 3357 The element could be buttondown or buttonup 3358 triggering the action associated with it. 3359 """ 3360 return self.tk.call(self._w, 'invoke', element) 3361 3362 def scan(self, *args): 3363 """Internal function.""" 3364 return self._getints( 3365 self.tk.call((self._w, 'scan') + args)) or () 3366 3367 def scan_mark(self, x): 3368 """Records x and the current view in the spinbox window; 3369 3370 used in conjunction with later scan dragto commands. 3371 Typically this command is associated with a mouse button 3372 press in the widget. It returns an empty string. 3373 """ 3374 return self.scan("mark", x) 3375 3376 def scan_dragto(self, x): 3377 """Compute the difference between the given x argument 3378 and the x argument to the last scan mark command 3379 3380 It then adjusts the view left or right by 10 times the 3381 difference in x-coordinates. This command is typically 3382 associated with mouse motion events in the widget, to 3383 produce the effect of dragging the spinbox at high speed 3384 through the window. The return value is an empty string. 3385 """ 3386 return self.scan("dragto", x) 3387 3388 def selection(self, *args): 3389 """Internal function.""" 3390 return self._getints( 3391 self.tk.call((self._w, 'selection') + args)) or () 3392 3393 def selection_adjust(self, index): 3394 """Locate the end of the selection nearest to the character 3395 given by index, 3396 3397 Then adjust that end of the selection to be at index 3398 (i.e including but not going beyond index). The other 3399 end of the selection is made the anchor point for future 3400 select to commands. If the selection isn't currently in 3401 the spinbox, then a new selection is created to include 3402 the characters between index and the most recent selection 3403 anchor point, inclusive. Returns an empty string. 3404 """ 3405 return self.selection("adjust", index) 3406 3407 def selection_clear(self): 3408 """Clear the selection 3409 3410 If the selection isn't in this widget then the 3411 command has no effect. Returns an empty string. 3412 """ 3413 return self.selection("clear") 3414 3415 def selection_element(self, element=None): 3416 """Sets or gets the currently selected element. 3417 3418 If a spinbutton element is specified, it will be 3419 displayed depressed 3420 """ 3421 return self.selection("element", element) 3422 3423 ########################################################################### 3424 3425 class LabelFrame(Widget): 3426 """labelframe widget.""" 3427 def __init__(self, master=None, cnf={}, **kw): 3428 """Construct a labelframe widget with the parent MASTER. 3429 3430 STANDARD OPTIONS 3431 3432 borderwidth, cursor, font, foreground, 3433 highlightbackground, highlightcolor, 3434 highlightthickness, padx, pady, relief, 3435 takefocus, text 3436 3437 WIDGET-SPECIFIC OPTIONS 3438 3439 background, class, colormap, container, 3440 height, labelanchor, labelwidget, 3441 visual, width 3442 """ 3443 Widget.__init__(self, master, 'labelframe', cnf, kw) 3444 3445 ######################################################################## 3446 3447 class PanedWindow(Widget): 3448 """panedwindow widget.""" 3449 def __init__(self, master=None, cnf={}, **kw): 3450 """Construct a panedwindow widget with the parent MASTER. 3451 3452 STANDARD OPTIONS 3453 3454 background, borderwidth, cursor, height, 3455 orient, relief, width 3456 3457 WIDGET-SPECIFIC OPTIONS 3458 3459 handlepad, handlesize, opaqueresize, 3460 sashcursor, sashpad, sashrelief, 3461 sashwidth, showhandle, 3462 """ 3463 Widget.__init__(self, master, 'panedwindow', cnf, kw) 3464 3465 def add(self, child, **kw): 3466 """Add a child widget to the panedwindow in a new pane. 3467 3468 The child argument is the name of the child widget 3469 followed by pairs of arguments that specify how to 3470 manage the windows. Options may have any of the values 3471 accepted by the configure subcommand. 3472 """ 3473 self.tk.call((self._w, 'add', child) + self._options(kw)) 3474 3475 def remove(self, child): 3476 """Remove the pane containing child from the panedwindow 3477 3478 All geometry management options for child will be forgotten. 3479 """ 3480 self.tk.call(self._w, 'forget', child) 3481 forget=remove 3482 3483 def identify(self, x, y): 3484 """Identify the panedwindow component at point x, y 3485 3486 If the point is over a sash or a sash handle, the result 3487 is a two element list containing the index of the sash or 3488 handle, and a word indicating whether it is over a sash 3489 or a handle, such as {0 sash} or {2 handle}. If the point 3490 is over any other part of the panedwindow, the result is 3491 an empty list. 3492 """ 3493 return self.tk.call(self._w, 'identify', x, y) 3494 3495 def proxy(self, *args): 3496 """Internal function.""" 3497 return self._getints( 3498 self.tk.call((self._w, 'proxy') + args)) or () 3499 3500 def proxy_coord(self): 3501 """Return the x and y pair of the most recent proxy location 3502 """ 3503 return self.proxy("coord") 3504 3505 def proxy_forget(self): 3506 """Remove the proxy from the display. 3507 """ 3508 return self.proxy("forget") 3509 3510 def proxy_place(self, x, y): 3511 """Place the proxy at the given x and y coordinates. 3512 """ 3513 return self.proxy("place", x, y) 3514 3515 def sash(self, *args): 3516 """Internal function.""" 3517 return self._getints( 3518 self.tk.call((self._w, 'sash') + args)) or () 3519 3520 def sash_coord(self, index): 3521 """Return the current x and y pair for the sash given by index. 3522 3523 Index must be an integer between 0 and 1 less than the 3524 number of panes in the panedwindow. The coordinates given are 3525 those of the top left corner of the region containing the sash. 3526 pathName sash dragto index x y This command computes the 3527 difference between the given coordinates and the coordinates 3528 given to the last sash coord command for the given sash. It then 3529 moves that sash the computed difference. The return value is the 3530 empty string. 3531 """ 3532 return self.sash("coord", index) 3533 3534 def sash_mark(self, index): 3535 """Records x and y for the sash given by index; 3536 3537 Used in conjunction with later dragto commands to move the sash. 3538 """ 3539 return self.sash("mark", index) 3540 3541 def sash_place(self, index, x, y): 3542 """Place the sash given by index at the given coordinates 3543 """ 3544 return self.sash("place", index, x, y) 3545 3546 def panecget(self, child, option): 3547 """Query a management option for window. 3548 3549 Option may be any value allowed by the paneconfigure subcommand 3550 """ 3551 return self.tk.call( 3552 (self._w, 'panecget') + (child, '-'+option)) 3553 3554 def paneconfigure(self, tagOrId, cnf=None, **kw): 3555 """Query or modify the management options for window. 3556 3557 If no option is specified, returns a list describing all 3558 of the available options for pathName. If option is 3559 specified with no value, then the command returns a list 3560 describing the one named option (this list will be identical 3561 to the corresponding sublist of the value returned if no 3562 option is specified). If one or more option-value pairs are 3563 specified, then the command modifies the given widget 3564 option(s) to have the given value(s); in this case the 3565 command returns an empty string. The following options 3566 are supported: 3567 3568 after window 3569 Insert the window after the window specified. window 3570 should be the name of a window already managed by pathName. 3571 before window 3572 Insert the window before the window specified. window 3573 should be the name of a window already managed by pathName. 3574 height size 3575 Specify a height for the window. The height will be the 3576 outer dimension of the window including its border, if 3577 any. If size is an empty string, or if -height is not 3578 specified, then the height requested internally by the 3579 window will be used initially; the height may later be 3580 adjusted by the movement of sashes in the panedwindow. 3581 Size may be any value accepted by Tk_GetPixels. 3582 minsize n 3583 Specifies that the size of the window cannot be made 3584 less than n. This constraint only affects the size of 3585 the widget in the paned dimension -- the x dimension 3586 for horizontal panedwindows, the y dimension for 3587 vertical panedwindows. May be any value accepted by 3588 Tk_GetPixels. 3589 padx n 3590 Specifies a non-negative value indicating how much 3591 extra space to leave on each side of the window in 3592 the X-direction. The value may have any of the forms 3593 accepted by Tk_GetPixels. 3594 pady n 3595 Specifies a non-negative value indicating how much 3596 extra space to leave on each side of the window in 3597 the Y-direction. The value may have any of the forms 3598 accepted by Tk_GetPixels. 3599 sticky style 3600 If a window's pane is larger than the requested 3601 dimensions of the window, this option may be used 3602 to position (or stretch) the window within its pane. 3603 Style is a string that contains zero or more of the 3604 characters n, s, e or w. The string can optionally 3605 contains spaces or commas, but they are ignored. Each 3606 letter refers to a side (north, south, east, or west) 3607 that the window will "stick" to. If both n and s 3608 (or e and w) are specified, the window will be 3609 stretched to fill the entire height (or width) of 3610 its cavity. 3611 width size 3612 Specify a width for the window. The width will be 3613 the outer dimension of the window including its 3614 border, if any. If size is an empty string, or 3615 if -width is not specified, then the width requested 3616 internally by the window will be used initially; the 3617 width may later be adjusted by the movement of sashes 3618 in the panedwindow. Size may be any value accepted by 3619 Tk_GetPixels. 3620 3621 """ 3622 if cnf is None and not kw: 3623 cnf = {} 3624 for x in self.tk.split( 3625 self.tk.call(self._w, 3626 'paneconfigure', tagOrId)): 3627 cnf[x[0][1:]] = (x[0][1:],) + x[1:] 3628 return cnf 3629 if type(cnf) == StringType and not kw: 3630 x = self.tk.split(self.tk.call( 3631 self._w, 'paneconfigure', tagOrId, '-'+cnf)) 3632 return (x[0][1:],) + x[1:] 3633 self.tk.call((self._w, 'paneconfigure', tagOrId) + 3634 self._options(cnf, kw)) 3635 paneconfig = paneconfigure 3636 3637 def panes(self): 3638 """Returns an ordered list of the child panes.""" 3639 return self.tk.call(self._w, 'panes') 3640 3641 ###################################################################### 3642 # Extensions: 3643 3644 class Studbutton(Button): 3645 def __init__(self, master=None, cnf={}, **kw): 3646 Widget.__init__(self, master, 'studbutton', cnf, kw) 3647 self.bind('<Any-Enter>', self.tkButtonEnter) 3648 self.bind('<Any-Leave>', self.tkButtonLeave) 3649 self.bind('<1>', self.tkButtonDown) 3650 self.bind('<ButtonRelease-1>', self.tkButtonUp) 3651 3652 class Tributton(Button): 3653 def __init__(self, master=None, cnf={}, **kw): 3654 Widget.__init__(self, master, 'tributton', cnf, kw) 3655 self.bind('<Any-Enter>', self.tkButtonEnter) 3656 self.bind('<Any-Leave>', self.tkButtonLeave) 3657 self.bind('<1>', self.tkButtonDown) 3658 self.bind('<ButtonRelease-1>', self.tkButtonUp) 3659 self['fg'] = self['bg'] 3660 self['activebackground'] = self['bg'] 3661 3662 ###################################################################### 3663 # Test: 3664 3665 def _test(): 3666 root = Tk() 3667 text = "This is Tcl/Tk version %s" % TclVersion 3668 if TclVersion >= 8.1: 3669 try: 3670 text = text + unicode("\nThis should be a cedilla: \347", 3671 "iso-8859-1") 3672 except NameError: 3673 pass # no unicode support 3674 label = Label(root, text=text) 3675 label.pack() 3676 test = Button(root, text="Click me!", 3677 command=lambda root=root: root.test.configure( 3678 text="[%s]" % root.test['text'])) 3679 test.pack() 3680 root.test = test 3681 quit = Button(root, text="QUIT", command=root.destroy) 3682 quit.pack() 3683 # The following three commands are needed so the window pops 3684 # up on top on Windows... 3685 root.iconify() 3686 root.update() 3687 root.deiconify() 3688 root.mainloop() 3689 3690 if __name__ == '__main__': 3691 _test() 3692
Generated by PyXR 0.9.4