blob: 549e0738afcada52962317fceede58e356221300 [file] [log] [blame]
Georg Brandl33cece02008-05-20 06:58:21 +00001"""Wrapper functions for Tcl/Tk.
2
3Tkinter provides classes which allow the display, positioning and
4control of widgets. Toplevel widgets are Tk and Toplevel. Other
5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
6Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
7LabelFrame and PanedWindow.
8
9Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
11under Tk.
12
13Widgets are positioned with one of the geometry managers Place, Pack
14or Grid. These managers can be called with methods place, pack, grid
15available in every Widget.
16
17Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
19
20Example (Hello, World):
Georg Brandl6634bf22008-05-20 07:13:37 +000021import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
Georg Brandl33cece02008-05-20 06:58:21 +000025frame.pack(fill=BOTH,expand=1)
Georg Brandl6634bf22008-05-20 07:13:37 +000026label = Tkinter.Label(frame, text="Hello, World")
Georg Brandl33cece02008-05-20 06:58:21 +000027label.pack(fill=X, expand=1)
Georg Brandl6634bf22008-05-20 07:13:37 +000028button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
Georg Brandl33cece02008-05-20 06:58:21 +000029button.pack(side=BOTTOM)
30tk.mainloop()
31"""
32
33__version__ = "$Revision$"
34
35import sys
36if sys.platform == "win32":
37 # Attempt to configure Tcl/Tk without requiring PATH
Georg Brandl6634bf22008-05-20 07:13:37 +000038 import FixTk
Georg Brandl33cece02008-05-20 06:58:21 +000039import _tkinter # If this fails your Python may not be configured for Tk
Georg Brandl6634bf22008-05-20 07:13:37 +000040tkinter = _tkinter # b/w compat for export
Georg Brandl33cece02008-05-20 06:58:21 +000041TclError = _tkinter.TclError
42from types import *
Georg Brandl6634bf22008-05-20 07:13:37 +000043from Tkconstants import *
Georg Brandl33cece02008-05-20 06:58:21 +000044try:
45 import MacOS; _MacOS = MacOS; del MacOS
46except ImportError:
47 _MacOS = None
48
49wantobjects = 1
50
51TkVersion = float(_tkinter.TK_VERSION)
52TclVersion = float(_tkinter.TCL_VERSION)
53
54READABLE = _tkinter.READABLE
55WRITABLE = _tkinter.WRITABLE
56EXCEPTION = _tkinter.EXCEPTION
57
58# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
59try: _tkinter.createfilehandler
60except AttributeError: _tkinter.createfilehandler = None
61try: _tkinter.deletefilehandler
62except AttributeError: _tkinter.deletefilehandler = None
63
64
65def _flatten(tuple):
66 """Internal function."""
67 res = ()
68 for item in tuple:
69 if type(item) in (TupleType, ListType):
70 res = res + _flatten(item)
71 elif item is not None:
72 res = res + (item,)
73 return res
74
75try: _flatten = _tkinter._flatten
76except AttributeError: pass
77
78def _cnfmerge(cnfs):
79 """Internal function."""
80 if type(cnfs) is DictionaryType:
81 return cnfs
82 elif type(cnfs) in (NoneType, StringType):
83 return cnfs
84 else:
85 cnf = {}
86 for c in _flatten(cnfs):
87 try:
88 cnf.update(c)
89 except (AttributeError, TypeError), msg:
90 print "_cnfmerge: fallback due to:", msg
91 for k, v in c.items():
92 cnf[k] = v
93 return cnf
94
95try: _cnfmerge = _tkinter._cnfmerge
96except AttributeError: pass
97
98class Event:
99 """Container for the properties of an event.
100
101 Instances of this type are generated if one of the following events occurs:
102
103 KeyPress, KeyRelease - for keyboard events
104 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
105 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
106 Colormap, Gravity, Reparent, Property, Destroy, Activate,
107 Deactivate - for window events.
108
109 If a callback function for one of these events is registered
110 using bind, bind_all, bind_class, or tag_bind, the callback is
111 called with an Event as first argument. It will have the
112 following attributes (in braces are the event types for which
113 the attribute is valid):
114
115 serial - serial number of event
116 num - mouse button pressed (ButtonPress, ButtonRelease)
117 focus - whether the window has the focus (Enter, Leave)
118 height - height of the exposed window (Configure, Expose)
119 width - width of the exposed window (Configure, Expose)
120 keycode - keycode of the pressed key (KeyPress, KeyRelease)
121 state - state of the event as a number (ButtonPress, ButtonRelease,
122 Enter, KeyPress, KeyRelease,
123 Leave, Motion)
124 state - state as a string (Visibility)
125 time - when the event occurred
126 x - x-position of the mouse
127 y - y-position of the mouse
128 x_root - x-position of the mouse on the screen
129 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
130 y_root - y-position of the mouse on the screen
131 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
132 char - pressed character (KeyPress, KeyRelease)
133 send_event - see X/Windows documentation
134 keysym - keysym of the event as a string (KeyPress, KeyRelease)
135 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
136 type - type of the event as a number
137 widget - widget in which the event occurred
138 delta - delta of wheel movement (MouseWheel)
139 """
140 pass
141
142_support_default_root = 1
143_default_root = None
144
145def NoDefaultRoot():
146 """Inhibit setting of default root window.
147
148 Call this function to inhibit that the first instance of
149 Tk is used for windows without an explicit parent window.
150 """
151 global _support_default_root
152 _support_default_root = 0
153 global _default_root
154 _default_root = None
155 del _default_root
156
157def _tkerror(err):
158 """Internal function."""
159 pass
160
161def _exit(code='0'):
162 """Internal function. Calling it will throw the exception SystemExit."""
163 raise SystemExit, code
164
165_varnum = 0
166class Variable:
167 """Class to define value holders for e.g. buttons.
168
169 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
170 that constrain the type of the value returned from get()."""
171 _default = ""
172 def __init__(self, master=None, value=None, name=None):
173 """Construct a variable
174
175 MASTER can be given as master widget.
176 VALUE is an optional value (defaults to "")
177 NAME is an optional Tcl name (defaults to PY_VARnum).
178
179 If NAME matches an existing variable and VALUE is omitted
180 then the existing value is retained.
181 """
182 global _varnum
183 if not master:
184 master = _default_root
185 self._master = master
186 self._tk = master.tk
187 if name:
188 self._name = name
189 else:
190 self._name = 'PY_VAR' + repr(_varnum)
191 _varnum += 1
192 if value is not None:
193 self.set(value)
194 elif not self._tk.call("info", "exists", self._name):
195 self.set(self._default)
196 def __del__(self):
197 """Unset the variable in Tcl."""
198 self._tk.globalunsetvar(self._name)
199 def __str__(self):
200 """Return the name of the variable in Tcl."""
201 return self._name
202 def set(self, value):
203 """Set the variable to VALUE."""
204 return self._tk.globalsetvar(self._name, value)
205 def get(self):
206 """Return value of variable."""
207 return self._tk.globalgetvar(self._name)
208 def trace_variable(self, mode, callback):
209 """Define a trace callback for the variable.
210
211 MODE is one of "r", "w", "u" for read, write, undefine.
212 CALLBACK must be a function which is called when
213 the variable is read, written or undefined.
214
215 Return the name of the callback.
216 """
217 cbname = self._master._register(callback)
218 self._tk.call("trace", "variable", self._name, mode, cbname)
219 return cbname
220 trace = trace_variable
221 def trace_vdelete(self, mode, cbname):
222 """Delete the trace callback for a variable.
223
224 MODE is one of "r", "w", "u" for read, write, undefine.
225 CBNAME is the name of the callback returned from trace_variable or trace.
226 """
227 self._tk.call("trace", "vdelete", self._name, mode, cbname)
228 self._master.deletecommand(cbname)
229 def trace_vinfo(self):
230 """Return all trace callback information."""
231 return map(self._tk.split, self._tk.splitlist(
232 self._tk.call("trace", "vinfo", self._name)))
233 def __eq__(self, other):
234 """Comparison for equality (==).
235
236 Note: if the Variable's master matters to behavior
237 also compare self._master == other._master
238 """
239 return self.__class__.__name__ == other.__class__.__name__ \
240 and self._name == other._name
241
242class StringVar(Variable):
243 """Value holder for strings variables."""
244 _default = ""
245 def __init__(self, master=None, value=None, name=None):
246 """Construct a string variable.
247
248 MASTER can be given as master widget.
249 VALUE is an optional value (defaults to "")
250 NAME is an optional Tcl name (defaults to PY_VARnum).
251
252 If NAME matches an existing variable and VALUE is omitted
253 then the existing value is retained.
254 """
255 Variable.__init__(self, master, value, name)
256
257 def get(self):
258 """Return value of variable as string."""
259 value = self._tk.globalgetvar(self._name)
260 if isinstance(value, basestring):
261 return value
262 return str(value)
263
264class IntVar(Variable):
265 """Value holder for integer variables."""
266 _default = 0
267 def __init__(self, master=None, value=None, name=None):
268 """Construct an integer variable.
269
270 MASTER can be given as master widget.
271 VALUE is an optional value (defaults to 0)
272 NAME is an optional Tcl name (defaults to PY_VARnum).
273
274 If NAME matches an existing variable and VALUE is omitted
275 then the existing value is retained.
276 """
277 Variable.__init__(self, master, value, name)
278
279 def set(self, value):
280 """Set the variable to value, converting booleans to integers."""
281 if isinstance(value, bool):
282 value = int(value)
283 return Variable.set(self, value)
284
285 def get(self):
286 """Return the value of the variable as an integer."""
287 return getint(self._tk.globalgetvar(self._name))
288
289class DoubleVar(Variable):
290 """Value holder for float variables."""
291 _default = 0.0
292 def __init__(self, master=None, value=None, name=None):
293 """Construct a float variable.
294
295 MASTER can be given as master widget.
296 VALUE is an optional value (defaults to 0.0)
297 NAME is an optional Tcl name (defaults to PY_VARnum).
298
299 If NAME matches an existing variable and VALUE is omitted
300 then the existing value is retained.
301 """
302 Variable.__init__(self, master, value, name)
303
304 def get(self):
305 """Return the value of the variable as a float."""
306 return getdouble(self._tk.globalgetvar(self._name))
307
308class BooleanVar(Variable):
309 """Value holder for boolean variables."""
310 _default = False
311 def __init__(self, master=None, value=None, name=None):
312 """Construct a boolean variable.
313
314 MASTER can be given as master widget.
315 VALUE is an optional value (defaults to False)
316 NAME is an optional Tcl name (defaults to PY_VARnum).
317
318 If NAME matches an existing variable and VALUE is omitted
319 then the existing value is retained.
320 """
321 Variable.__init__(self, master, value, name)
322
323 def get(self):
324 """Return the value of the variable as a bool."""
325 return self._tk.getboolean(self._tk.globalgetvar(self._name))
326
327def mainloop(n=0):
328 """Run the main loop of Tcl."""
329 _default_root.tk.mainloop(n)
330
331getint = int
332
333getdouble = float
334
335def getboolean(s):
336 """Convert true and false to integer values 1 and 0."""
337 return _default_root.tk.getboolean(s)
338
339# Methods defined on both toplevel and interior widgets
340class Misc:
341 """Internal class.
342
343 Base class which defines methods common for interior widgets."""
344
345 # XXX font command?
346 _tclCommands = None
347 def destroy(self):
348 """Internal function.
349
350 Delete all Tcl commands created for
351 this widget in the Tcl interpreter."""
352 if self._tclCommands is not None:
353 for name in self._tclCommands:
354 #print '- Tkinter: deleted command', name
355 self.tk.deletecommand(name)
356 self._tclCommands = None
357 def deletecommand(self, name):
358 """Internal function.
359
360 Delete the Tcl command provided in NAME."""
361 #print '- Tkinter: deleted command', name
362 self.tk.deletecommand(name)
363 try:
364 self._tclCommands.remove(name)
365 except ValueError:
366 pass
367 def tk_strictMotif(self, boolean=None):
368 """Set Tcl internal variable, whether the look and feel
369 should adhere to Motif.
370
371 A parameter of 1 means adhere to Motif (e.g. no color
372 change if mouse passes over slider).
373 Returns the set value."""
374 return self.tk.getboolean(self.tk.call(
375 'set', 'tk_strictMotif', boolean))
376 def tk_bisque(self):
377 """Change the color scheme to light brown as used in Tk 3.6 and before."""
378 self.tk.call('tk_bisque')
379 def tk_setPalette(self, *args, **kw):
380 """Set a new color scheme for all widget elements.
381
382 A single color as argument will cause that all colors of Tk
383 widget elements are derived from this.
384 Alternatively several keyword parameters and its associated
385 colors can be given. The following keywords are valid:
386 activeBackground, foreground, selectColor,
387 activeForeground, highlightBackground, selectBackground,
388 background, highlightColor, selectForeground,
389 disabledForeground, insertBackground, troughColor."""
390 self.tk.call(('tk_setPalette',)
391 + _flatten(args) + _flatten(kw.items()))
392 def tk_menuBar(self, *args):
393 """Do not use. Needed in Tk 3.6 and earlier."""
394 pass # obsolete since Tk 4.0
395 def wait_variable(self, name='PY_VAR'):
396 """Wait until the variable is modified.
397
398 A parameter of type IntVar, StringVar, DoubleVar or
399 BooleanVar must be given."""
400 self.tk.call('tkwait', 'variable', name)
401 waitvar = wait_variable # XXX b/w compat
402 def wait_window(self, window=None):
403 """Wait until a WIDGET is destroyed.
404
405 If no parameter is given self is used."""
406 if window is None:
407 window = self
408 self.tk.call('tkwait', 'window', window._w)
409 def wait_visibility(self, window=None):
410 """Wait until the visibility of a WIDGET changes
411 (e.g. it appears).
412
413 If no parameter is given self is used."""
414 if window is None:
415 window = self
416 self.tk.call('tkwait', 'visibility', window._w)
417 def setvar(self, name='PY_VAR', value='1'):
418 """Set Tcl variable NAME to VALUE."""
419 self.tk.setvar(name, value)
420 def getvar(self, name='PY_VAR'):
421 """Return value of Tcl variable NAME."""
422 return self.tk.getvar(name)
423 getint = int
424 getdouble = float
425 def getboolean(self, s):
426 """Return a boolean value for Tcl boolean values true and false given as parameter."""
427 return self.tk.getboolean(s)
428 def focus_set(self):
429 """Direct input focus to this widget.
430
431 If the application currently does not have the focus
432 this widget will get the focus if the application gets
433 the focus through the window manager."""
434 self.tk.call('focus', self._w)
435 focus = focus_set # XXX b/w compat?
436 def focus_force(self):
437 """Direct input focus to this widget even if the
438 application does not have the focus. Use with
439 caution!"""
440 self.tk.call('focus', '-force', self._w)
441 def focus_get(self):
442 """Return the widget which has currently the focus in the
443 application.
444
445 Use focus_displayof to allow working with several
446 displays. Return None if application does not have
447 the focus."""
448 name = self.tk.call('focus')
449 if name == 'none' or not name: return None
450 return self._nametowidget(name)
451 def focus_displayof(self):
452 """Return the widget which has currently the focus on the
453 display where this widget is located.
454
455 Return None if the application does not have the focus."""
456 name = self.tk.call('focus', '-displayof', self._w)
457 if name == 'none' or not name: return None
458 return self._nametowidget(name)
459 def focus_lastfor(self):
460 """Return the widget which would have the focus if top level
461 for this widget gets the focus from the window manager."""
462 name = self.tk.call('focus', '-lastfor', self._w)
463 if name == 'none' or not name: return None
464 return self._nametowidget(name)
465 def tk_focusFollowsMouse(self):
466 """The widget under mouse will get automatically focus. Can not
467 be disabled easily."""
468 self.tk.call('tk_focusFollowsMouse')
469 def tk_focusNext(self):
470 """Return the next widget in the focus order which follows
471 widget which has currently the focus.
472
473 The focus order first goes to the next child, then to
474 the children of the child recursively and then to the
475 next sibling which is higher in the stacking order. A
476 widget is omitted if it has the takefocus resource set
477 to 0."""
478 name = self.tk.call('tk_focusNext', self._w)
479 if not name: return None
480 return self._nametowidget(name)
481 def tk_focusPrev(self):
482 """Return previous widget in the focus order. See tk_focusNext for details."""
483 name = self.tk.call('tk_focusPrev', self._w)
484 if not name: return None
485 return self._nametowidget(name)
486 def after(self, ms, func=None, *args):
487 """Call function once after given time.
488
489 MS specifies the time in milliseconds. FUNC gives the
490 function which shall be called. Additional parameters
491 are given as parameters to the function call. Return
492 identifier to cancel scheduling with after_cancel."""
493 if not func:
494 # I'd rather use time.sleep(ms*0.001)
495 self.tk.call('after', ms)
496 else:
497 def callit():
498 try:
499 func(*args)
500 finally:
501 try:
502 self.deletecommand(name)
503 except TclError:
504 pass
505 name = self._register(callit)
506 return self.tk.call('after', ms, name)
507 def after_idle(self, func, *args):
508 """Call FUNC once if the Tcl main loop has no event to
509 process.
510
511 Return an identifier to cancel the scheduling with
512 after_cancel."""
513 return self.after('idle', func, *args)
514 def after_cancel(self, id):
515 """Cancel scheduling of function identified with ID.
516
517 Identifier returned by after or after_idle must be
518 given as first parameter."""
519 try:
520 data = self.tk.call('after', 'info', id)
521 # In Tk 8.3, splitlist returns: (script, type)
522 # In Tk 8.4, splitlist may return (script, type) or (script,)
523 script = self.tk.splitlist(data)[0]
524 self.deletecommand(script)
525 except TclError:
526 pass
527 self.tk.call('after', 'cancel', id)
528 def bell(self, displayof=0):
529 """Ring a display's bell."""
530 self.tk.call(('bell',) + self._displayof(displayof))
531
532 # Clipboard handling:
533 def clipboard_get(self, **kw):
534 """Retrieve data from the clipboard on window's display.
535
536 The window keyword defaults to the root window of the Tkinter
537 application.
538
539 The type keyword specifies the form in which the data is
540 to be returned and should be an atom name such as STRING
541 or FILE_NAME. Type defaults to STRING.
542
543 This command is equivalent to:
544
545 selection_get(CLIPBOARD)
546 """
547 return self.tk.call(('clipboard', 'get') + self._options(kw))
548
549 def clipboard_clear(self, **kw):
550 """Clear the data in the Tk clipboard.
551
552 A widget specified for the optional displayof keyword
553 argument specifies the target display."""
554 if not kw.has_key('displayof'): kw['displayof'] = self._w
555 self.tk.call(('clipboard', 'clear') + self._options(kw))
556 def clipboard_append(self, string, **kw):
557 """Append STRING to the Tk clipboard.
558
559 A widget specified at the optional displayof keyword
560 argument specifies the target display. The clipboard
561 can be retrieved with selection_get."""
562 if not kw.has_key('displayof'): kw['displayof'] = self._w
563 self.tk.call(('clipboard', 'append') + self._options(kw)
564 + ('--', string))
565 # XXX grab current w/o window argument
566 def grab_current(self):
567 """Return widget which has currently the grab in this application
568 or None."""
569 name = self.tk.call('grab', 'current', self._w)
570 if not name: return None
571 return self._nametowidget(name)
572 def grab_release(self):
573 """Release grab for this widget if currently set."""
574 self.tk.call('grab', 'release', self._w)
575 def grab_set(self):
576 """Set grab for this widget.
577
578 A grab directs all events to this and descendant
579 widgets in the application."""
580 self.tk.call('grab', 'set', self._w)
581 def grab_set_global(self):
582 """Set global grab for this widget.
583
584 A global grab directs all events to this and
585 descendant widgets on the display. Use with caution -
586 other applications do not get events anymore."""
587 self.tk.call('grab', 'set', '-global', self._w)
588 def grab_status(self):
589 """Return None, "local" or "global" if this widget has
590 no, a local or a global grab."""
591 status = self.tk.call('grab', 'status', self._w)
592 if status == 'none': status = None
593 return status
594 def option_add(self, pattern, value, priority = None):
595 """Set a VALUE (second parameter) for an option
596 PATTERN (first parameter).
597
598 An optional third parameter gives the numeric priority
599 (defaults to 80)."""
600 self.tk.call('option', 'add', pattern, value, priority)
601 def option_clear(self):
602 """Clear the option database.
603
604 It will be reloaded if option_add is called."""
605 self.tk.call('option', 'clear')
606 def option_get(self, name, className):
607 """Return the value for an option NAME for this widget
608 with CLASSNAME.
609
610 Values with higher priority override lower values."""
611 return self.tk.call('option', 'get', self._w, name, className)
612 def option_readfile(self, fileName, priority = None):
613 """Read file FILENAME into the option database.
614
615 An optional second parameter gives the numeric
616 priority."""
617 self.tk.call('option', 'readfile', fileName, priority)
618 def selection_clear(self, **kw):
619 """Clear the current X selection."""
620 if not kw.has_key('displayof'): kw['displayof'] = self._w
621 self.tk.call(('selection', 'clear') + self._options(kw))
622 def selection_get(self, **kw):
623 """Return the contents of the current X selection.
624
625 A keyword parameter selection specifies the name of
626 the selection and defaults to PRIMARY. A keyword
627 parameter displayof specifies a widget on the display
628 to use."""
629 if not kw.has_key('displayof'): kw['displayof'] = self._w
630 return self.tk.call(('selection', 'get') + self._options(kw))
631 def selection_handle(self, command, **kw):
632 """Specify a function COMMAND to call if the X
633 selection owned by this widget is queried by another
634 application.
635
636 This function must return the contents of the
637 selection. The function will be called with the
638 arguments OFFSET and LENGTH which allows the chunking
639 of very long selections. The following keyword
640 parameters can be provided:
641 selection - name of the selection (default PRIMARY),
642 type - type of the selection (e.g. STRING, FILE_NAME)."""
643 name = self._register(command)
644 self.tk.call(('selection', 'handle') + self._options(kw)
645 + (self._w, name))
646 def selection_own(self, **kw):
647 """Become owner of X selection.
648
649 A keyword parameter selection specifies the name of
650 the selection (default PRIMARY)."""
651 self.tk.call(('selection', 'own') +
652 self._options(kw) + (self._w,))
653 def selection_own_get(self, **kw):
654 """Return owner of X selection.
655
656 The following keyword parameter can
657 be provided:
658 selection - name of the selection (default PRIMARY),
659 type - type of the selection (e.g. STRING, FILE_NAME)."""
660 if not kw.has_key('displayof'): kw['displayof'] = self._w
661 name = self.tk.call(('selection', 'own') + self._options(kw))
662 if not name: return None
663 return self._nametowidget(name)
664 def send(self, interp, cmd, *args):
665 """Send Tcl command CMD to different interpreter INTERP to be executed."""
666 return self.tk.call(('send', interp, cmd) + args)
667 def lower(self, belowThis=None):
668 """Lower this widget in the stacking order."""
669 self.tk.call('lower', self._w, belowThis)
670 def tkraise(self, aboveThis=None):
671 """Raise this widget in the stacking order."""
672 self.tk.call('raise', self._w, aboveThis)
673 lift = tkraise
674 def colormodel(self, value=None):
675 """Useless. Not implemented in Tk."""
676 return self.tk.call('tk', 'colormodel', self._w, value)
677 def winfo_atom(self, name, displayof=0):
678 """Return integer which represents atom NAME."""
679 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
680 return getint(self.tk.call(args))
681 def winfo_atomname(self, id, displayof=0):
682 """Return name of atom with identifier ID."""
683 args = ('winfo', 'atomname') \
684 + self._displayof(displayof) + (id,)
685 return self.tk.call(args)
686 def winfo_cells(self):
687 """Return number of cells in the colormap for this widget."""
688 return getint(
689 self.tk.call('winfo', 'cells', self._w))
690 def winfo_children(self):
691 """Return a list of all widgets which are children of this widget."""
692 result = []
693 for child in self.tk.splitlist(
694 self.tk.call('winfo', 'children', self._w)):
695 try:
696 # Tcl sometimes returns extra windows, e.g. for
697 # menus; those need to be skipped
698 result.append(self._nametowidget(child))
699 except KeyError:
700 pass
701 return result
702
703 def winfo_class(self):
704 """Return window class name of this widget."""
705 return self.tk.call('winfo', 'class', self._w)
706 def winfo_colormapfull(self):
707 """Return true if at the last color request the colormap was full."""
708 return self.tk.getboolean(
709 self.tk.call('winfo', 'colormapfull', self._w))
710 def winfo_containing(self, rootX, rootY, displayof=0):
711 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
712 args = ('winfo', 'containing') \
713 + self._displayof(displayof) + (rootX, rootY)
714 name = self.tk.call(args)
715 if not name: return None
716 return self._nametowidget(name)
717 def winfo_depth(self):
718 """Return the number of bits per pixel."""
719 return getint(self.tk.call('winfo', 'depth', self._w))
720 def winfo_exists(self):
721 """Return true if this widget exists."""
722 return getint(
723 self.tk.call('winfo', 'exists', self._w))
724 def winfo_fpixels(self, number):
725 """Return the number of pixels for the given distance NUMBER
726 (e.g. "3c") as float."""
727 return getdouble(self.tk.call(
728 'winfo', 'fpixels', self._w, number))
729 def winfo_geometry(self):
730 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
731 return self.tk.call('winfo', 'geometry', self._w)
732 def winfo_height(self):
733 """Return height of this widget."""
734 return getint(
735 self.tk.call('winfo', 'height', self._w))
736 def winfo_id(self):
737 """Return identifier ID for this widget."""
738 return self.tk.getint(
739 self.tk.call('winfo', 'id', self._w))
740 def winfo_interps(self, displayof=0):
741 """Return the name of all Tcl interpreters for this display."""
742 args = ('winfo', 'interps') + self._displayof(displayof)
743 return self.tk.splitlist(self.tk.call(args))
744 def winfo_ismapped(self):
745 """Return true if this widget is mapped."""
746 return getint(
747 self.tk.call('winfo', 'ismapped', self._w))
748 def winfo_manager(self):
749 """Return the window mananger name for this widget."""
750 return self.tk.call('winfo', 'manager', self._w)
751 def winfo_name(self):
752 """Return the name of this widget."""
753 return self.tk.call('winfo', 'name', self._w)
754 def winfo_parent(self):
755 """Return the name of the parent of this widget."""
756 return self.tk.call('winfo', 'parent', self._w)
757 def winfo_pathname(self, id, displayof=0):
758 """Return the pathname of the widget given by ID."""
759 args = ('winfo', 'pathname') \
760 + self._displayof(displayof) + (id,)
761 return self.tk.call(args)
762 def winfo_pixels(self, number):
763 """Rounded integer value of winfo_fpixels."""
764 return getint(
765 self.tk.call('winfo', 'pixels', self._w, number))
766 def winfo_pointerx(self):
767 """Return the x coordinate of the pointer on the root window."""
768 return getint(
769 self.tk.call('winfo', 'pointerx', self._w))
770 def winfo_pointerxy(self):
771 """Return a tuple of x and y coordinates of the pointer on the root window."""
772 return self._getints(
773 self.tk.call('winfo', 'pointerxy', self._w))
774 def winfo_pointery(self):
775 """Return the y coordinate of the pointer on the root window."""
776 return getint(
777 self.tk.call('winfo', 'pointery', self._w))
778 def winfo_reqheight(self):
779 """Return requested height of this widget."""
780 return getint(
781 self.tk.call('winfo', 'reqheight', self._w))
782 def winfo_reqwidth(self):
783 """Return requested width of this widget."""
784 return getint(
785 self.tk.call('winfo', 'reqwidth', self._w))
786 def winfo_rgb(self, color):
787 """Return tuple of decimal values for red, green, blue for
788 COLOR in this widget."""
789 return self._getints(
790 self.tk.call('winfo', 'rgb', self._w, color))
791 def winfo_rootx(self):
792 """Return x coordinate of upper left corner of this widget on the
793 root window."""
794 return getint(
795 self.tk.call('winfo', 'rootx', self._w))
796 def winfo_rooty(self):
797 """Return y coordinate of upper left corner of this widget on the
798 root window."""
799 return getint(
800 self.tk.call('winfo', 'rooty', self._w))
801 def winfo_screen(self):
802 """Return the screen name of this widget."""
803 return self.tk.call('winfo', 'screen', self._w)
804 def winfo_screencells(self):
805 """Return the number of the cells in the colormap of the screen
806 of this widget."""
807 return getint(
808 self.tk.call('winfo', 'screencells', self._w))
809 def winfo_screendepth(self):
810 """Return the number of bits per pixel of the root window of the
811 screen of this widget."""
812 return getint(
813 self.tk.call('winfo', 'screendepth', self._w))
814 def winfo_screenheight(self):
815 """Return the number of pixels of the height of the screen of this widget
816 in pixel."""
817 return getint(
818 self.tk.call('winfo', 'screenheight', self._w))
819 def winfo_screenmmheight(self):
820 """Return the number of pixels of the height of the screen of
821 this widget in mm."""
822 return getint(
823 self.tk.call('winfo', 'screenmmheight', self._w))
824 def winfo_screenmmwidth(self):
825 """Return the number of pixels of the width of the screen of
826 this widget in mm."""
827 return getint(
828 self.tk.call('winfo', 'screenmmwidth', self._w))
829 def winfo_screenvisual(self):
830 """Return one of the strings directcolor, grayscale, pseudocolor,
831 staticcolor, staticgray, or truecolor for the default
832 colormodel of this screen."""
833 return self.tk.call('winfo', 'screenvisual', self._w)
834 def winfo_screenwidth(self):
835 """Return the number of pixels of the width of the screen of
836 this widget in pixel."""
837 return getint(
838 self.tk.call('winfo', 'screenwidth', self._w))
839 def winfo_server(self):
840 """Return information of the X-Server of the screen of this widget in
841 the form "XmajorRminor vendor vendorVersion"."""
842 return self.tk.call('winfo', 'server', self._w)
843 def winfo_toplevel(self):
844 """Return the toplevel widget of this widget."""
845 return self._nametowidget(self.tk.call(
846 'winfo', 'toplevel', self._w))
847 def winfo_viewable(self):
848 """Return true if the widget and all its higher ancestors are mapped."""
849 return getint(
850 self.tk.call('winfo', 'viewable', self._w))
851 def winfo_visual(self):
852 """Return one of the strings directcolor, grayscale, pseudocolor,
853 staticcolor, staticgray, or truecolor for the
854 colormodel of this widget."""
855 return self.tk.call('winfo', 'visual', self._w)
856 def winfo_visualid(self):
857 """Return the X identifier for the visual for this widget."""
858 return self.tk.call('winfo', 'visualid', self._w)
859 def winfo_visualsavailable(self, includeids=0):
860 """Return a list of all visuals available for the screen
861 of this widget.
862
863 Each item in the list consists of a visual name (see winfo_visual), a
864 depth and if INCLUDEIDS=1 is given also the X identifier."""
865 data = self.tk.split(
866 self.tk.call('winfo', 'visualsavailable', self._w,
867 includeids and 'includeids' or None))
868 if type(data) is StringType:
869 data = [self.tk.split(data)]
870 return map(self.__winfo_parseitem, data)
871 def __winfo_parseitem(self, t):
872 """Internal function."""
873 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
874 def __winfo_getint(self, x):
875 """Internal function."""
876 return int(x, 0)
877 def winfo_vrootheight(self):
878 """Return the height of the virtual root window associated with this
879 widget in pixels. If there is no virtual root window return the
880 height of the screen."""
881 return getint(
882 self.tk.call('winfo', 'vrootheight', self._w))
883 def winfo_vrootwidth(self):
884 """Return the width of the virtual root window associated with this
885 widget in pixel. If there is no virtual root window return the
886 width of the screen."""
887 return getint(
888 self.tk.call('winfo', 'vrootwidth', self._w))
889 def winfo_vrootx(self):
890 """Return the x offset of the virtual root relative to the root
891 window of the screen of this widget."""
892 return getint(
893 self.tk.call('winfo', 'vrootx', self._w))
894 def winfo_vrooty(self):
895 """Return the y offset of the virtual root relative to the root
896 window of the screen of this widget."""
897 return getint(
898 self.tk.call('winfo', 'vrooty', self._w))
899 def winfo_width(self):
900 """Return the width of this widget."""
901 return getint(
902 self.tk.call('winfo', 'width', self._w))
903 def winfo_x(self):
904 """Return the x coordinate of the upper left corner of this widget
905 in the parent."""
906 return getint(
907 self.tk.call('winfo', 'x', self._w))
908 def winfo_y(self):
909 """Return the y coordinate of the upper left corner of this widget
910 in the parent."""
911 return getint(
912 self.tk.call('winfo', 'y', self._w))
913 def update(self):
914 """Enter event loop until all pending events have been processed by Tcl."""
915 self.tk.call('update')
916 def update_idletasks(self):
917 """Enter event loop until all idle callbacks have been called. This
918 will update the display of windows but not process events caused by
919 the user."""
920 self.tk.call('update', 'idletasks')
921 def bindtags(self, tagList=None):
922 """Set or get the list of bindtags for this widget.
923
924 With no argument return the list of all bindtags associated with
925 this widget. With a list of strings as argument the bindtags are
926 set to this list. The bindtags determine in which order events are
927 processed (see bind)."""
928 if tagList is None:
929 return self.tk.splitlist(
930 self.tk.call('bindtags', self._w))
931 else:
932 self.tk.call('bindtags', self._w, tagList)
933 def _bind(self, what, sequence, func, add, needcleanup=1):
934 """Internal function."""
935 if type(func) is StringType:
936 self.tk.call(what + (sequence, func))
937 elif func:
938 funcid = self._register(func, self._substitute,
939 needcleanup)
940 cmd = ('%sif {"[%s %s]" == "break"} break\n'
941 %
942 (add and '+' or '',
943 funcid, self._subst_format_str))
944 self.tk.call(what + (sequence, cmd))
945 return funcid
946 elif sequence:
947 return self.tk.call(what + (sequence,))
948 else:
949 return self.tk.splitlist(self.tk.call(what))
950 def bind(self, sequence=None, func=None, add=None):
951 """Bind to this widget at event SEQUENCE a call to function FUNC.
952
953 SEQUENCE is a string of concatenated event
954 patterns. An event pattern is of the form
955 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
956 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
957 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
958 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
959 Mod1, M1. TYPE is one of Activate, Enter, Map,
960 ButtonPress, Button, Expose, Motion, ButtonRelease
961 FocusIn, MouseWheel, Circulate, FocusOut, Property,
962 Colormap, Gravity Reparent, Configure, KeyPress, Key,
963 Unmap, Deactivate, KeyRelease Visibility, Destroy,
964 Leave and DETAIL is the button number for ButtonPress,
965 ButtonRelease and DETAIL is the Keysym for KeyPress and
966 KeyRelease. Examples are
967 <Control-Button-1> for pressing Control and mouse button 1 or
968 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
969 An event pattern can also be a virtual event of the form
970 <<AString>> where AString can be arbitrary. This
971 event can be generated by event_generate.
972 If events are concatenated they must appear shortly
973 after each other.
974
975 FUNC will be called if the event sequence occurs with an
976 instance of Event as argument. If the return value of FUNC is
977 "break" no further bound function is invoked.
978
979 An additional boolean parameter ADD specifies whether FUNC will
980 be called additionally to the other bound function or whether
981 it will replace the previous function.
982
983 Bind will return an identifier to allow deletion of the bound function with
984 unbind without memory leak.
985
986 If FUNC or SEQUENCE is omitted the bound function or list
987 of bound events are returned."""
988
989 return self._bind(('bind', self._w), sequence, func, add)
990 def unbind(self, sequence, funcid=None):
991 """Unbind for this widget for event SEQUENCE the
992 function identified with FUNCID."""
993 self.tk.call('bind', self._w, sequence, '')
994 if funcid:
995 self.deletecommand(funcid)
996 def bind_all(self, sequence=None, func=None, add=None):
997 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
998 An additional boolean parameter ADD specifies whether FUNC will
999 be called additionally to the other bound function or whether
1000 it will replace the previous function. See bind for the return value."""
1001 return self._bind(('bind', 'all'), sequence, func, add, 0)
1002 def unbind_all(self, sequence):
1003 """Unbind for all widgets for event SEQUENCE all functions."""
1004 self.tk.call('bind', 'all' , sequence, '')
1005 def bind_class(self, className, sequence=None, func=None, add=None):
1006
1007 """Bind to widgets with bindtag CLASSNAME at event
1008 SEQUENCE a call of function FUNC. An additional
1009 boolean parameter ADD specifies whether FUNC will be
1010 called additionally to the other bound function or
1011 whether it will replace the previous function. See bind for
1012 the return value."""
1013
1014 return self._bind(('bind', className), sequence, func, add, 0)
1015 def unbind_class(self, className, sequence):
1016 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1017 all functions."""
1018 self.tk.call('bind', className , sequence, '')
1019 def mainloop(self, n=0):
1020 """Call the mainloop of Tk."""
1021 self.tk.mainloop(n)
1022 def quit(self):
1023 """Quit the Tcl interpreter. All widgets will be destroyed."""
1024 self.tk.quit()
1025 def _getints(self, string):
1026 """Internal function."""
1027 if string:
1028 return tuple(map(getint, self.tk.splitlist(string)))
1029 def _getdoubles(self, string):
1030 """Internal function."""
1031 if string:
1032 return tuple(map(getdouble, self.tk.splitlist(string)))
1033 def _getboolean(self, string):
1034 """Internal function."""
1035 if string:
1036 return self.tk.getboolean(string)
1037 def _displayof(self, displayof):
1038 """Internal function."""
1039 if displayof:
1040 return ('-displayof', displayof)
1041 if displayof is None:
1042 return ('-displayof', self._w)
1043 return ()
1044 def _options(self, cnf, kw = None):
1045 """Internal function."""
1046 if kw:
1047 cnf = _cnfmerge((cnf, kw))
1048 else:
1049 cnf = _cnfmerge(cnf)
1050 res = ()
1051 for k, v in cnf.items():
1052 if v is not None:
1053 if k[-1] == '_': k = k[:-1]
1054 if callable(v):
1055 v = self._register(v)
Georg Brandl7943a322008-05-29 07:18:49 +00001056 elif isinstance(v, (tuple, list)):
Georg Brandl4ed3ed12008-06-03 10:23:15 +00001057 nv = []
Georg Brandl7943a322008-05-29 07:18:49 +00001058 for item in v:
1059 if not isinstance(item, (basestring, int)):
1060 break
Georg Brandl4ed3ed12008-06-03 10:23:15 +00001061 elif isinstance(item, int):
1062 nv.append('%d' % item)
1063 else:
1064 # format it to proper Tcl code if it contains space
1065 nv.append(('{%s}' if ' ' in item else '%s') % item)
Georg Brandl7943a322008-05-29 07:18:49 +00001066 else:
Georg Brandl4ed3ed12008-06-03 10:23:15 +00001067 v = ' '.join(nv)
Georg Brandl33cece02008-05-20 06:58:21 +00001068 res = res + ('-'+k, v)
1069 return res
1070 def nametowidget(self, name):
1071 """Return the Tkinter instance of a widget identified by
1072 its Tcl name NAME."""
1073 w = self
1074 if name[0] == '.':
1075 w = w._root()
1076 name = name[1:]
1077 while name:
1078 i = name.find('.')
1079 if i >= 0:
1080 name, tail = name[:i], name[i+1:]
1081 else:
1082 tail = ''
1083 w = w.children[name]
1084 name = tail
1085 return w
1086 _nametowidget = nametowidget
1087 def _register(self, func, subst=None, needcleanup=1):
1088 """Return a newly created Tcl function. If this
1089 function is called, the Python function FUNC will
1090 be executed. An optional function SUBST can
1091 be given which will be executed before FUNC."""
1092 f = CallWrapper(func, subst, self).__call__
1093 name = repr(id(f))
1094 try:
1095 func = func.im_func
1096 except AttributeError:
1097 pass
1098 try:
1099 name = name + func.__name__
1100 except AttributeError:
1101 pass
1102 self.tk.createcommand(name, f)
1103 if needcleanup:
1104 if self._tclCommands is None:
1105 self._tclCommands = []
1106 self._tclCommands.append(name)
Georg Brandl33cece02008-05-20 06:58:21 +00001107 return name
1108 register = _register
1109 def _root(self):
1110 """Internal function."""
1111 w = self
1112 while w.master: w = w.master
1113 return w
1114 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1115 '%s', '%t', '%w', '%x', '%y',
1116 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1117 _subst_format_str = " ".join(_subst_format)
1118 def _substitute(self, *args):
1119 """Internal function."""
1120 if len(args) != len(self._subst_format): return args
1121 getboolean = self.tk.getboolean
1122
1123 getint = int
1124 def getint_event(s):
1125 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1126 try:
1127 return int(s)
1128 except ValueError:
1129 return s
1130
1131 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1132 # Missing: (a, c, d, m, o, v, B, R)
1133 e = Event()
1134 # serial field: valid vor all events
1135 # number of button: ButtonPress and ButtonRelease events only
1136 # height field: Configure, ConfigureRequest, Create,
1137 # ResizeRequest, and Expose events only
1138 # keycode field: KeyPress and KeyRelease events only
1139 # time field: "valid for events that contain a time field"
1140 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1141 # and Expose events only
1142 # x field: "valid for events that contain a x field"
1143 # y field: "valid for events that contain a y field"
1144 # keysym as decimal: KeyPress and KeyRelease events only
1145 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1146 # KeyRelease,and Motion events
1147 e.serial = getint(nsign)
1148 e.num = getint_event(b)
1149 try: e.focus = getboolean(f)
1150 except TclError: pass
1151 e.height = getint_event(h)
1152 e.keycode = getint_event(k)
1153 e.state = getint_event(s)
1154 e.time = getint_event(t)
1155 e.width = getint_event(w)
1156 e.x = getint_event(x)
1157 e.y = getint_event(y)
1158 e.char = A
1159 try: e.send_event = getboolean(E)
1160 except TclError: pass
1161 e.keysym = K
1162 e.keysym_num = getint_event(N)
1163 e.type = T
1164 try:
1165 e.widget = self._nametowidget(W)
1166 except KeyError:
1167 e.widget = W
1168 e.x_root = getint_event(X)
1169 e.y_root = getint_event(Y)
1170 try:
1171 e.delta = getint(D)
1172 except ValueError:
1173 e.delta = 0
1174 return (e,)
1175 def _report_exception(self):
1176 """Internal function."""
1177 import sys
1178 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1179 root = self._root()
1180 root.report_callback_exception(exc, val, tb)
1181 def _configure(self, cmd, cnf, kw):
1182 """Internal function."""
1183 if kw:
1184 cnf = _cnfmerge((cnf, kw))
1185 elif cnf:
1186 cnf = _cnfmerge(cnf)
1187 if cnf is None:
1188 cnf = {}
1189 for x in self.tk.split(
1190 self.tk.call(_flatten((self._w, cmd)))):
1191 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1192 return cnf
1193 if type(cnf) is StringType:
1194 x = self.tk.split(
1195 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1196 return (x[0][1:],) + x[1:]
1197 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1198 # These used to be defined in Widget:
1199 def configure(self, cnf=None, **kw):
1200 """Configure resources of a widget.
1201
1202 The values for resources are specified as keyword
1203 arguments. To get an overview about
1204 the allowed keyword arguments call the method keys.
1205 """
1206 return self._configure('configure', cnf, kw)
1207 config = configure
1208 def cget(self, key):
1209 """Return the resource value for a KEY given as string."""
Georg Brandl33cece02008-05-20 06:58:21 +00001210 return self.tk.call(self._w, 'cget', '-' + key)
1211 __getitem__ = cget
1212 def __setitem__(self, key, value):
1213 self.configure({key: value})
Georg Brandlae019e12008-05-20 08:48:34 +00001214 def __contains__(self, key):
1215 raise TypeError("Tkinter objects don't support 'in' tests.")
Georg Brandl33cece02008-05-20 06:58:21 +00001216 def keys(self):
1217 """Return a list of all resource names of this widget."""
1218 return map(lambda x: x[0][1:],
1219 self.tk.split(self.tk.call(self._w, 'configure')))
1220 def __str__(self):
1221 """Return the window path name of this widget."""
1222 return self._w
1223 # Pack methods that apply to the master
1224 _noarg_ = ['_noarg_']
1225 def pack_propagate(self, flag=_noarg_):
1226 """Set or get the status for propagation of geometry information.
1227
1228 A boolean argument specifies whether the geometry information
1229 of the slaves will determine the size of this widget. If no argument
1230 is given the current setting will be returned.
1231 """
1232 if flag is Misc._noarg_:
1233 return self._getboolean(self.tk.call(
1234 'pack', 'propagate', self._w))
1235 else:
1236 self.tk.call('pack', 'propagate', self._w, flag)
1237 propagate = pack_propagate
1238 def pack_slaves(self):
1239 """Return a list of all slaves of this widget
1240 in its packing order."""
1241 return map(self._nametowidget,
1242 self.tk.splitlist(
1243 self.tk.call('pack', 'slaves', self._w)))
1244 slaves = pack_slaves
1245 # Place method that applies to the master
1246 def place_slaves(self):
1247 """Return a list of all slaves of this widget
1248 in its packing order."""
1249 return map(self._nametowidget,
1250 self.tk.splitlist(
1251 self.tk.call(
1252 'place', 'slaves', self._w)))
1253 # Grid methods that apply to the master
1254 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1255 """Return a tuple of integer coordinates for the bounding
1256 box of this widget controlled by the geometry manager grid.
1257
1258 If COLUMN, ROW is given the bounding box applies from
1259 the cell with row and column 0 to the specified
1260 cell. If COL2 and ROW2 are given the bounding box
1261 starts at that cell.
1262
1263 The returned integers specify the offset of the upper left
1264 corner in the master widget and the width and height.
1265 """
1266 args = ('grid', 'bbox', self._w)
1267 if column is not None and row is not None:
1268 args = args + (column, row)
1269 if col2 is not None and row2 is not None:
1270 args = args + (col2, row2)
1271 return self._getints(self.tk.call(*args)) or None
1272
1273 bbox = grid_bbox
1274 def _grid_configure(self, command, index, cnf, kw):
1275 """Internal function."""
1276 if type(cnf) is StringType and not kw:
1277 if cnf[-1:] == '_':
1278 cnf = cnf[:-1]
1279 if cnf[:1] != '-':
1280 cnf = '-'+cnf
1281 options = (cnf,)
1282 else:
1283 options = self._options(cnf, kw)
1284 if not options:
1285 res = self.tk.call('grid',
1286 command, self._w, index)
1287 words = self.tk.splitlist(res)
1288 dict = {}
1289 for i in range(0, len(words), 2):
1290 key = words[i][1:]
1291 value = words[i+1]
1292 if not value:
1293 value = None
1294 elif '.' in value:
1295 value = getdouble(value)
1296 else:
1297 value = getint(value)
1298 dict[key] = value
1299 return dict
1300 res = self.tk.call(
1301 ('grid', command, self._w, index)
1302 + options)
1303 if len(options) == 1:
1304 if not res: return None
1305 # In Tk 7.5, -width can be a float
1306 if '.' in res: return getdouble(res)
1307 return getint(res)
1308 def grid_columnconfigure(self, index, cnf={}, **kw):
1309 """Configure column INDEX of a grid.
1310
1311 Valid resources are minsize (minimum size of the column),
1312 weight (how much does additional space propagate to this column)
1313 and pad (how much space to let additionally)."""
1314 return self._grid_configure('columnconfigure', index, cnf, kw)
1315 columnconfigure = grid_columnconfigure
1316 def grid_location(self, x, y):
1317 """Return a tuple of column and row which identify the cell
1318 at which the pixel at position X and Y inside the master
1319 widget is located."""
1320 return self._getints(
1321 self.tk.call(
1322 'grid', 'location', self._w, x, y)) or None
1323 def grid_propagate(self, flag=_noarg_):
1324 """Set or get the status for propagation of geometry information.
1325
1326 A boolean argument specifies whether the geometry information
1327 of the slaves will determine the size of this widget. If no argument
1328 is given, the current setting will be returned.
1329 """
1330 if flag is Misc._noarg_:
1331 return self._getboolean(self.tk.call(
1332 'grid', 'propagate', self._w))
1333 else:
1334 self.tk.call('grid', 'propagate', self._w, flag)
1335 def grid_rowconfigure(self, index, cnf={}, **kw):
1336 """Configure row INDEX of a grid.
1337
1338 Valid resources are minsize (minimum size of the row),
1339 weight (how much does additional space propagate to this row)
1340 and pad (how much space to let additionally)."""
1341 return self._grid_configure('rowconfigure', index, cnf, kw)
1342 rowconfigure = grid_rowconfigure
1343 def grid_size(self):
1344 """Return a tuple of the number of column and rows in the grid."""
1345 return self._getints(
1346 self.tk.call('grid', 'size', self._w)) or None
1347 size = grid_size
1348 def grid_slaves(self, row=None, column=None):
1349 """Return a list of all slaves of this widget
1350 in its packing order."""
1351 args = ()
1352 if row is not None:
1353 args = args + ('-row', row)
1354 if column is not None:
1355 args = args + ('-column', column)
1356 return map(self._nametowidget,
1357 self.tk.splitlist(self.tk.call(
1358 ('grid', 'slaves', self._w) + args)))
1359
1360 # Support for the "event" command, new in Tk 4.2.
1361 # By Case Roole.
1362
1363 def event_add(self, virtual, *sequences):
1364 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1365 to an event SEQUENCE such that the virtual event is triggered
1366 whenever SEQUENCE occurs."""
1367 args = ('event', 'add', virtual) + sequences
1368 self.tk.call(args)
1369
1370 def event_delete(self, virtual, *sequences):
1371 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1372 args = ('event', 'delete', virtual) + sequences
1373 self.tk.call(args)
1374
1375 def event_generate(self, sequence, **kw):
1376 """Generate an event SEQUENCE. Additional
1377 keyword arguments specify parameter of the event
1378 (e.g. x, y, rootx, rooty)."""
1379 args = ('event', 'generate', self._w, sequence)
1380 for k, v in kw.items():
1381 args = args + ('-%s' % k, str(v))
1382 self.tk.call(args)
1383
1384 def event_info(self, virtual=None):
1385 """Return a list of all virtual events or the information
1386 about the SEQUENCE bound to the virtual event VIRTUAL."""
1387 return self.tk.splitlist(
1388 self.tk.call('event', 'info', virtual))
1389
1390 # Image related commands
1391
1392 def image_names(self):
1393 """Return a list of all existing image names."""
1394 return self.tk.call('image', 'names')
1395
1396 def image_types(self):
1397 """Return a list of all available image types (e.g. phote bitmap)."""
1398 return self.tk.call('image', 'types')
1399
1400
1401class CallWrapper:
1402 """Internal class. Stores function to call when some user
1403 defined Tcl function is called e.g. after an event occurred."""
1404 def __init__(self, func, subst, widget):
1405 """Store FUNC, SUBST and WIDGET as members."""
1406 self.func = func
1407 self.subst = subst
1408 self.widget = widget
1409 def __call__(self, *args):
1410 """Apply first function SUBST to arguments, than FUNC."""
1411 try:
1412 if self.subst:
1413 args = self.subst(*args)
1414 return self.func(*args)
1415 except SystemExit, msg:
1416 raise SystemExit, msg
1417 except:
1418 self.widget._report_exception()
1419
1420
1421class Wm:
1422 """Provides functions for the communication with the window manager."""
1423
1424 def wm_aspect(self,
1425 minNumer=None, minDenom=None,
1426 maxNumer=None, maxDenom=None):
1427 """Instruct the window manager to set the aspect ratio (width/height)
1428 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1429 of the actual values if no argument is given."""
1430 return self._getints(
1431 self.tk.call('wm', 'aspect', self._w,
1432 minNumer, minDenom,
1433 maxNumer, maxDenom))
1434 aspect = wm_aspect
1435
1436 def wm_attributes(self, *args):
1437 """This subcommand returns or sets platform specific attributes
1438
1439 The first form returns a list of the platform specific flags and
1440 their values. The second form returns the value for the specific
1441 option. The third form sets one or more of the values. The values
1442 are as follows:
1443
1444 On Windows, -disabled gets or sets whether the window is in a
1445 disabled state. -toolwindow gets or sets the style of the window
1446 to toolwindow (as defined in the MSDN). -topmost gets or sets
1447 whether this is a topmost window (displays above all other
1448 windows).
1449
1450 On Macintosh, XXXXX
1451
1452 On Unix, there are currently no special attribute values.
1453 """
1454 args = ('wm', 'attributes', self._w) + args
1455 return self.tk.call(args)
1456 attributes=wm_attributes
1457
1458 def wm_client(self, name=None):
1459 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1460 current value."""
1461 return self.tk.call('wm', 'client', self._w, name)
1462 client = wm_client
1463 def wm_colormapwindows(self, *wlist):
1464 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1465 of this widget. This list contains windows whose colormaps differ from their
1466 parents. Return current list of widgets if WLIST is empty."""
1467 if len(wlist) > 1:
1468 wlist = (wlist,) # Tk needs a list of windows here
1469 args = ('wm', 'colormapwindows', self._w) + wlist
1470 return map(self._nametowidget, self.tk.call(args))
1471 colormapwindows = wm_colormapwindows
1472 def wm_command(self, value=None):
1473 """Store VALUE in WM_COMMAND property. It is the command
1474 which shall be used to invoke the application. Return current
1475 command if VALUE is None."""
1476 return self.tk.call('wm', 'command', self._w, value)
1477 command = wm_command
1478 def wm_deiconify(self):
1479 """Deiconify this widget. If it was never mapped it will not be mapped.
1480 On Windows it will raise this widget and give it the focus."""
1481 return self.tk.call('wm', 'deiconify', self._w)
1482 deiconify = wm_deiconify
1483 def wm_focusmodel(self, model=None):
1484 """Set focus model to MODEL. "active" means that this widget will claim
1485 the focus itself, "passive" means that the window manager shall give
1486 the focus. Return current focus model if MODEL is None."""
1487 return self.tk.call('wm', 'focusmodel', self._w, model)
1488 focusmodel = wm_focusmodel
1489 def wm_frame(self):
1490 """Return identifier for decorative frame of this widget if present."""
1491 return self.tk.call('wm', 'frame', self._w)
1492 frame = wm_frame
1493 def wm_geometry(self, newGeometry=None):
1494 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1495 current value if None is given."""
1496 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1497 geometry = wm_geometry
1498 def wm_grid(self,
1499 baseWidth=None, baseHeight=None,
1500 widthInc=None, heightInc=None):
1501 """Instruct the window manager that this widget shall only be
1502 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1503 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1504 number of grid units requested in Tk_GeometryRequest."""
1505 return self._getints(self.tk.call(
1506 'wm', 'grid', self._w,
1507 baseWidth, baseHeight, widthInc, heightInc))
1508 grid = wm_grid
1509 def wm_group(self, pathName=None):
1510 """Set the group leader widgets for related widgets to PATHNAME. Return
1511 the group leader of this widget if None is given."""
1512 return self.tk.call('wm', 'group', self._w, pathName)
1513 group = wm_group
1514 def wm_iconbitmap(self, bitmap=None, default=None):
1515 """Set bitmap for the iconified widget to BITMAP. Return
1516 the bitmap if None is given.
1517
1518 Under Windows, the DEFAULT parameter can be used to set the icon
1519 for the widget and any descendents that don't have an icon set
1520 explicitly. DEFAULT can be the relative path to a .ico file
1521 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1522 documentation for more information."""
1523 if default:
1524 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1525 else:
1526 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1527 iconbitmap = wm_iconbitmap
1528 def wm_iconify(self):
1529 """Display widget as icon."""
1530 return self.tk.call('wm', 'iconify', self._w)
1531 iconify = wm_iconify
1532 def wm_iconmask(self, bitmap=None):
1533 """Set mask for the icon bitmap of this widget. Return the
1534 mask if None is given."""
1535 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1536 iconmask = wm_iconmask
1537 def wm_iconname(self, newName=None):
1538 """Set the name of the icon for this widget. Return the name if
1539 None is given."""
1540 return self.tk.call('wm', 'iconname', self._w, newName)
1541 iconname = wm_iconname
1542 def wm_iconposition(self, x=None, y=None):
1543 """Set the position of the icon of this widget to X and Y. Return
1544 a tuple of the current values of X and X if None is given."""
1545 return self._getints(self.tk.call(
1546 'wm', 'iconposition', self._w, x, y))
1547 iconposition = wm_iconposition
1548 def wm_iconwindow(self, pathName=None):
1549 """Set widget PATHNAME to be displayed instead of icon. Return the current
1550 value if None is given."""
1551 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1552 iconwindow = wm_iconwindow
1553 def wm_maxsize(self, width=None, height=None):
1554 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1555 the values are given in grid units. Return the current values if None
1556 is given."""
1557 return self._getints(self.tk.call(
1558 'wm', 'maxsize', self._w, width, height))
1559 maxsize = wm_maxsize
1560 def wm_minsize(self, width=None, height=None):
1561 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1562 the values are given in grid units. Return the current values if None
1563 is given."""
1564 return self._getints(self.tk.call(
1565 'wm', 'minsize', self._w, width, height))
1566 minsize = wm_minsize
1567 def wm_overrideredirect(self, boolean=None):
1568 """Instruct the window manager to ignore this widget
1569 if BOOLEAN is given with 1. Return the current value if None
1570 is given."""
1571 return self._getboolean(self.tk.call(
1572 'wm', 'overrideredirect', self._w, boolean))
1573 overrideredirect = wm_overrideredirect
1574 def wm_positionfrom(self, who=None):
1575 """Instruct the window manager that the position of this widget shall
1576 be defined by the user if WHO is "user", and by its own policy if WHO is
1577 "program"."""
1578 return self.tk.call('wm', 'positionfrom', self._w, who)
1579 positionfrom = wm_positionfrom
1580 def wm_protocol(self, name=None, func=None):
1581 """Bind function FUNC to command NAME for this widget.
1582 Return the function bound to NAME if None is given. NAME could be
1583 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1584 if callable(func):
1585 command = self._register(func)
1586 else:
1587 command = func
1588 return self.tk.call(
1589 'wm', 'protocol', self._w, name, command)
1590 protocol = wm_protocol
1591 def wm_resizable(self, width=None, height=None):
1592 """Instruct the window manager whether this width can be resized
1593 in WIDTH or HEIGHT. Both values are boolean values."""
1594 return self.tk.call('wm', 'resizable', self._w, width, height)
1595 resizable = wm_resizable
1596 def wm_sizefrom(self, who=None):
1597 """Instruct the window manager that the size of this widget shall
1598 be defined by the user if WHO is "user", and by its own policy if WHO is
1599 "program"."""
1600 return self.tk.call('wm', 'sizefrom', self._w, who)
1601 sizefrom = wm_sizefrom
1602 def wm_state(self, newstate=None):
1603 """Query or set the state of this widget as one of normal, icon,
1604 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1605 return self.tk.call('wm', 'state', self._w, newstate)
1606 state = wm_state
1607 def wm_title(self, string=None):
1608 """Set the title of this widget."""
1609 return self.tk.call('wm', 'title', self._w, string)
1610 title = wm_title
1611 def wm_transient(self, master=None):
1612 """Instruct the window manager that this widget is transient
1613 with regard to widget MASTER."""
1614 return self.tk.call('wm', 'transient', self._w, master)
1615 transient = wm_transient
1616 def wm_withdraw(self):
1617 """Withdraw this widget from the screen such that it is unmapped
1618 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1619 return self.tk.call('wm', 'withdraw', self._w)
1620 withdraw = wm_withdraw
1621
1622
1623class Tk(Misc, Wm):
1624 """Toplevel widget of Tk which represents mostly the main window
1625 of an appliation. It has an associated Tcl interpreter."""
1626 _w = '.'
1627 def __init__(self, screenName=None, baseName=None, className='Tk',
1628 useTk=1, sync=0, use=None):
1629 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1630 be created. BASENAME will be used for the identification of the profile file (see
1631 readprofile).
1632 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1633 is the name of the widget class."""
1634 self.master = None
1635 self.children = {}
1636 self._tkloaded = 0
1637 # to avoid recursions in the getattr code in case of failure, we
1638 # ensure that self.tk is always _something_.
1639 self.tk = None
1640 if baseName is None:
1641 import sys, os
1642 baseName = os.path.basename(sys.argv[0])
1643 baseName, ext = os.path.splitext(baseName)
1644 if ext not in ('.py', '.pyc', '.pyo'):
1645 baseName = baseName + ext
1646 interactive = 0
1647 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
1648 if useTk:
1649 self._loadtk()
1650 self.readprofile(baseName, className)
1651 def loadtk(self):
1652 if not self._tkloaded:
1653 self.tk.loadtk()
1654 self._loadtk()
1655 def _loadtk(self):
1656 self._tkloaded = 1
1657 global _default_root
1658 if _MacOS and hasattr(_MacOS, 'SchedParams'):
1659 # Disable event scanning except for Command-Period
1660 _MacOS.SchedParams(1, 0)
1661 # Work around nasty MacTk bug
1662 # XXX Is this one still needed?
1663 self.update()
1664 # Version sanity checks
1665 tk_version = self.tk.getvar('tk_version')
1666 if tk_version != _tkinter.TK_VERSION:
1667 raise RuntimeError, \
1668 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1669 % (_tkinter.TK_VERSION, tk_version)
1670 # Under unknown circumstances, tcl_version gets coerced to float
1671 tcl_version = str(self.tk.getvar('tcl_version'))
1672 if tcl_version != _tkinter.TCL_VERSION:
1673 raise RuntimeError, \
1674 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1675 % (_tkinter.TCL_VERSION, tcl_version)
1676 if TkVersion < 4.0:
1677 raise RuntimeError, \
1678 "Tk 4.0 or higher is required; found Tk %s" \
1679 % str(TkVersion)
1680 # Create and register the tkerror and exit commands
1681 # We need to inline parts of _register here, _ register
1682 # would register differently-named commands.
1683 if self._tclCommands is None:
1684 self._tclCommands = []
1685 self.tk.createcommand('tkerror', _tkerror)
1686 self.tk.createcommand('exit', _exit)
1687 self._tclCommands.append('tkerror')
1688 self._tclCommands.append('exit')
1689 if _support_default_root and not _default_root:
1690 _default_root = self
1691 self.protocol("WM_DELETE_WINDOW", self.destroy)
1692 def destroy(self):
1693 """Destroy this and all descendants widgets. This will
1694 end the application of this Tcl interpreter."""
1695 for c in self.children.values(): c.destroy()
1696 self.tk.call('destroy', self._w)
1697 Misc.destroy(self)
1698 global _default_root
1699 if _support_default_root and _default_root is self:
1700 _default_root = None
1701 def readprofile(self, baseName, className):
1702 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1703 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1704 such a file exists in the home directory."""
1705 import os
1706 if os.environ.has_key('HOME'): home = os.environ['HOME']
1707 else: home = os.curdir
1708 class_tcl = os.path.join(home, '.%s.tcl' % className)
1709 class_py = os.path.join(home, '.%s.py' % className)
1710 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1711 base_py = os.path.join(home, '.%s.py' % baseName)
1712 dir = {'self': self}
Georg Brandl6634bf22008-05-20 07:13:37 +00001713 exec 'from Tkinter import *' in dir
Georg Brandl33cece02008-05-20 06:58:21 +00001714 if os.path.isfile(class_tcl):
1715 self.tk.call('source', class_tcl)
1716 if os.path.isfile(class_py):
1717 execfile(class_py, dir)
1718 if os.path.isfile(base_tcl):
1719 self.tk.call('source', base_tcl)
1720 if os.path.isfile(base_py):
1721 execfile(base_py, dir)
1722 def report_callback_exception(self, exc, val, tb):
1723 """Internal function. It reports exception on sys.stderr."""
1724 import traceback, sys
1725 sys.stderr.write("Exception in Tkinter callback\n")
1726 sys.last_type = exc
1727 sys.last_value = val
1728 sys.last_traceback = tb
1729 traceback.print_exception(exc, val, tb)
1730 def __getattr__(self, attr):
1731 "Delegate attribute access to the interpreter object"
1732 return getattr(self.tk, attr)
1733
1734# Ideally, the classes Pack, Place and Grid disappear, the
1735# pack/place/grid methods are defined on the Widget class, and
1736# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1737# ...), with pack(), place() and grid() being short for
1738# pack_configure(), place_configure() and grid_columnconfigure(), and
1739# forget() being short for pack_forget(). As a practical matter, I'm
1740# afraid that there is too much code out there that may be using the
1741# Pack, Place or Grid class, so I leave them intact -- but only as
1742# backwards compatibility features. Also note that those methods that
1743# take a master as argument (e.g. pack_propagate) have been moved to
1744# the Misc class (which now incorporates all methods common between
1745# toplevel and interior widgets). Again, for compatibility, these are
1746# copied into the Pack, Place or Grid class.
1747
1748
1749def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1750 return Tk(screenName, baseName, className, useTk)
1751
1752class Pack:
1753 """Geometry manager Pack.
1754
1755 Base class to use the methods pack_* in every widget."""
1756 def pack_configure(self, cnf={}, **kw):
1757 """Pack a widget in the parent widget. Use as options:
1758 after=widget - pack it after you have packed widget
1759 anchor=NSEW (or subset) - position widget according to
1760 given direction
Georg Brandl7943a322008-05-29 07:18:49 +00001761 before=widget - pack it before you will pack widget
Georg Brandl33cece02008-05-20 06:58:21 +00001762 expand=bool - expand widget if parent size grows
1763 fill=NONE or X or Y or BOTH - fill widget if widget grows
1764 in=master - use master to contain this widget
Georg Brandl7943a322008-05-29 07:18:49 +00001765 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001766 ipadx=amount - add internal padding in x direction
1767 ipady=amount - add internal padding in y direction
1768 padx=amount - add padding in x direction
1769 pady=amount - add padding in y direction
1770 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1771 """
1772 self.tk.call(
1773 ('pack', 'configure', self._w)
1774 + self._options(cnf, kw))
1775 pack = configure = config = pack_configure
1776 def pack_forget(self):
1777 """Unmap this widget and do not use it for the packing order."""
1778 self.tk.call('pack', 'forget', self._w)
1779 forget = pack_forget
1780 def pack_info(self):
1781 """Return information about the packing options
1782 for this widget."""
1783 words = self.tk.splitlist(
1784 self.tk.call('pack', 'info', self._w))
1785 dict = {}
1786 for i in range(0, len(words), 2):
1787 key = words[i][1:]
1788 value = words[i+1]
1789 if value[:1] == '.':
1790 value = self._nametowidget(value)
1791 dict[key] = value
1792 return dict
1793 info = pack_info
1794 propagate = pack_propagate = Misc.pack_propagate
1795 slaves = pack_slaves = Misc.pack_slaves
1796
1797class Place:
1798 """Geometry manager Place.
1799
1800 Base class to use the methods place_* in every widget."""
1801 def place_configure(self, cnf={}, **kw):
1802 """Place a widget in the parent widget. Use as options:
Georg Brandl7943a322008-05-29 07:18:49 +00001803 in=master - master relative to which the widget is placed
1804 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001805 x=amount - locate anchor of this widget at position x of master
1806 y=amount - locate anchor of this widget at position y of master
1807 relx=amount - locate anchor of this widget between 0.0 and 1.0
1808 relative to width of master (1.0 is right edge)
Georg Brandl7943a322008-05-29 07:18:49 +00001809 rely=amount - locate anchor of this widget between 0.0 and 1.0
Georg Brandl33cece02008-05-20 06:58:21 +00001810 relative to height of master (1.0 is bottom edge)
Georg Brandl7943a322008-05-29 07:18:49 +00001811 anchor=NSEW (or subset) - position anchor according to given direction
Georg Brandl33cece02008-05-20 06:58:21 +00001812 width=amount - width of this widget in pixel
1813 height=amount - height of this widget in pixel
1814 relwidth=amount - width of this widget between 0.0 and 1.0
1815 relative to width of master (1.0 is the same width
Georg Brandl7943a322008-05-29 07:18:49 +00001816 as the master)
1817 relheight=amount - height of this widget between 0.0 and 1.0
Georg Brandl33cece02008-05-20 06:58:21 +00001818 relative to height of master (1.0 is the same
Georg Brandl7943a322008-05-29 07:18:49 +00001819 height as the master)
1820 bordermode="inside" or "outside" - whether to take border width of
1821 master widget into account
1822 """
Georg Brandl33cece02008-05-20 06:58:21 +00001823 self.tk.call(
1824 ('place', 'configure', self._w)
1825 + self._options(cnf, kw))
1826 place = configure = config = place_configure
1827 def place_forget(self):
1828 """Unmap this widget."""
1829 self.tk.call('place', 'forget', self._w)
1830 forget = place_forget
1831 def place_info(self):
1832 """Return information about the placing options
1833 for this widget."""
1834 words = self.tk.splitlist(
1835 self.tk.call('place', 'info', self._w))
1836 dict = {}
1837 for i in range(0, len(words), 2):
1838 key = words[i][1:]
1839 value = words[i+1]
1840 if value[:1] == '.':
1841 value = self._nametowidget(value)
1842 dict[key] = value
1843 return dict
1844 info = place_info
1845 slaves = place_slaves = Misc.place_slaves
1846
1847class Grid:
1848 """Geometry manager Grid.
1849
1850 Base class to use the methods grid_* in every widget."""
1851 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1852 def grid_configure(self, cnf={}, **kw):
1853 """Position a widget in the parent widget in a grid. Use as options:
1854 column=number - use cell identified with given column (starting with 0)
1855 columnspan=number - this widget will span several columns
1856 in=master - use master to contain this widget
Georg Brandl7943a322008-05-29 07:18:49 +00001857 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001858 ipadx=amount - add internal padding in x direction
1859 ipady=amount - add internal padding in y direction
1860 padx=amount - add padding in x direction
1861 pady=amount - add padding in y direction
1862 row=number - use cell identified with given row (starting with 0)
1863 rowspan=number - this widget will span several rows
1864 sticky=NSEW - if cell is larger on which sides will this
1865 widget stick to the cell boundary
1866 """
1867 self.tk.call(
1868 ('grid', 'configure', self._w)
1869 + self._options(cnf, kw))
1870 grid = configure = config = grid_configure
1871 bbox = grid_bbox = Misc.grid_bbox
1872 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1873 def grid_forget(self):
1874 """Unmap this widget."""
1875 self.tk.call('grid', 'forget', self._w)
1876 forget = grid_forget
1877 def grid_remove(self):
1878 """Unmap this widget but remember the grid options."""
1879 self.tk.call('grid', 'remove', self._w)
1880 def grid_info(self):
1881 """Return information about the options
1882 for positioning this widget in a grid."""
1883 words = self.tk.splitlist(
1884 self.tk.call('grid', 'info', self._w))
1885 dict = {}
1886 for i in range(0, len(words), 2):
1887 key = words[i][1:]
1888 value = words[i+1]
1889 if value[:1] == '.':
1890 value = self._nametowidget(value)
1891 dict[key] = value
1892 return dict
1893 info = grid_info
1894 location = grid_location = Misc.grid_location
1895 propagate = grid_propagate = Misc.grid_propagate
1896 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1897 size = grid_size = Misc.grid_size
1898 slaves = grid_slaves = Misc.grid_slaves
1899
1900class BaseWidget(Misc):
1901 """Internal class."""
1902 def _setup(self, master, cnf):
1903 """Internal function. Sets up information about children."""
1904 if _support_default_root:
1905 global _default_root
1906 if not master:
1907 if not _default_root:
1908 _default_root = Tk()
1909 master = _default_root
1910 self.master = master
1911 self.tk = master.tk
1912 name = None
1913 if cnf.has_key('name'):
1914 name = cnf['name']
1915 del cnf['name']
1916 if not name:
1917 name = repr(id(self))
1918 self._name = name
1919 if master._w=='.':
1920 self._w = '.' + name
1921 else:
1922 self._w = master._w + '.' + name
1923 self.children = {}
1924 if self.master.children.has_key(self._name):
1925 self.master.children[self._name].destroy()
1926 self.master.children[self._name] = self
1927 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1928 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1929 and appropriate options."""
1930 if kw:
1931 cnf = _cnfmerge((cnf, kw))
1932 self.widgetName = widgetName
1933 BaseWidget._setup(self, master, cnf)
1934 classes = []
1935 for k in cnf.keys():
1936 if type(k) is ClassType:
1937 classes.append((k, cnf[k]))
1938 del cnf[k]
1939 self.tk.call(
1940 (widgetName, self._w) + extra + self._options(cnf))
1941 for k, v in classes:
1942 k.configure(self, v)
1943 def destroy(self):
1944 """Destroy this and all descendants widgets."""
1945 for c in self.children.values(): c.destroy()
1946 self.tk.call('destroy', self._w)
1947 if self.master.children.has_key(self._name):
1948 del self.master.children[self._name]
1949 Misc.destroy(self)
1950 def _do(self, name, args=()):
1951 # XXX Obsolete -- better use self.tk.call directly!
1952 return self.tk.call((self._w, name) + args)
1953
1954class Widget(BaseWidget, Pack, Place, Grid):
1955 """Internal class.
1956
1957 Base class for a widget which can be positioned with the geometry managers
1958 Pack, Place or Grid."""
1959 pass
1960
1961class Toplevel(BaseWidget, Wm):
1962 """Toplevel widget, e.g. for dialogs."""
1963 def __init__(self, master=None, cnf={}, **kw):
1964 """Construct a toplevel widget with the parent MASTER.
1965
1966 Valid resource names: background, bd, bg, borderwidth, class,
1967 colormap, container, cursor, height, highlightbackground,
1968 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1969 use, visual, width."""
1970 if kw:
1971 cnf = _cnfmerge((cnf, kw))
1972 extra = ()
1973 for wmkey in ['screen', 'class_', 'class', 'visual',
1974 'colormap']:
1975 if cnf.has_key(wmkey):
1976 val = cnf[wmkey]
1977 # TBD: a hack needed because some keys
1978 # are not valid as keyword arguments
1979 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1980 else: opt = '-'+wmkey
1981 extra = extra + (opt, val)
1982 del cnf[wmkey]
1983 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1984 root = self._root()
1985 self.iconname(root.iconname())
1986 self.title(root.title())
1987 self.protocol("WM_DELETE_WINDOW", self.destroy)
1988
1989class Button(Widget):
1990 """Button widget."""
1991 def __init__(self, master=None, cnf={}, **kw):
1992 """Construct a button widget with the parent MASTER.
1993
1994 STANDARD OPTIONS
1995
1996 activebackground, activeforeground, anchor,
1997 background, bitmap, borderwidth, cursor,
1998 disabledforeground, font, foreground
1999 highlightbackground, highlightcolor,
2000 highlightthickness, image, justify,
2001 padx, pady, relief, repeatdelay,
2002 repeatinterval, takefocus, text,
2003 textvariable, underline, wraplength
2004
2005 WIDGET-SPECIFIC OPTIONS
2006
2007 command, compound, default, height,
2008 overrelief, state, width
2009 """
2010 Widget.__init__(self, master, 'button', cnf, kw)
2011
2012 def tkButtonEnter(self, *dummy):
2013 self.tk.call('tkButtonEnter', self._w)
2014
2015 def tkButtonLeave(self, *dummy):
2016 self.tk.call('tkButtonLeave', self._w)
2017
2018 def tkButtonDown(self, *dummy):
2019 self.tk.call('tkButtonDown', self._w)
2020
2021 def tkButtonUp(self, *dummy):
2022 self.tk.call('tkButtonUp', self._w)
2023
2024 def tkButtonInvoke(self, *dummy):
2025 self.tk.call('tkButtonInvoke', self._w)
2026
2027 def flash(self):
2028 """Flash the button.
2029
2030 This is accomplished by redisplaying
2031 the button several times, alternating between active and
2032 normal colors. At the end of the flash the button is left
2033 in the same normal/active state as when the command was
2034 invoked. This command is ignored if the button's state is
2035 disabled.
2036 """
2037 self.tk.call(self._w, 'flash')
2038
2039 def invoke(self):
2040 """Invoke the command associated with the button.
2041
2042 The return value is the return value from the command,
2043 or an empty string if there is no command associated with
2044 the button. This command is ignored if the button's state
2045 is disabled.
2046 """
2047 return self.tk.call(self._w, 'invoke')
2048
2049# Indices:
2050# XXX I don't like these -- take them away
2051def AtEnd():
2052 return 'end'
2053def AtInsert(*args):
2054 s = 'insert'
2055 for a in args:
2056 if a: s = s + (' ' + a)
2057 return s
2058def AtSelFirst():
2059 return 'sel.first'
2060def AtSelLast():
2061 return 'sel.last'
2062def At(x, y=None):
2063 if y is None:
2064 return '@%r' % (x,)
2065 else:
2066 return '@%r,%r' % (x, y)
2067
2068class Canvas(Widget):
2069 """Canvas widget to display graphical elements like lines or text."""
2070 def __init__(self, master=None, cnf={}, **kw):
2071 """Construct a canvas widget with the parent MASTER.
2072
2073 Valid resource names: background, bd, bg, borderwidth, closeenough,
2074 confine, cursor, height, highlightbackground, highlightcolor,
2075 highlightthickness, insertbackground, insertborderwidth,
2076 insertofftime, insertontime, insertwidth, offset, relief,
2077 scrollregion, selectbackground, selectborderwidth, selectforeground,
2078 state, takefocus, width, xscrollcommand, xscrollincrement,
2079 yscrollcommand, yscrollincrement."""
2080 Widget.__init__(self, master, 'canvas', cnf, kw)
2081 def addtag(self, *args):
2082 """Internal function."""
2083 self.tk.call((self._w, 'addtag') + args)
2084 def addtag_above(self, newtag, tagOrId):
2085 """Add tag NEWTAG to all items above TAGORID."""
2086 self.addtag(newtag, 'above', tagOrId)
2087 def addtag_all(self, newtag):
2088 """Add tag NEWTAG to all items."""
2089 self.addtag(newtag, 'all')
2090 def addtag_below(self, newtag, tagOrId):
2091 """Add tag NEWTAG to all items below TAGORID."""
2092 self.addtag(newtag, 'below', tagOrId)
2093 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2094 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2095 If several match take the top-most.
2096 All items closer than HALO are considered overlapping (all are
2097 closests). If START is specified the next below this tag is taken."""
2098 self.addtag(newtag, 'closest', x, y, halo, start)
2099 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2100 """Add tag NEWTAG to all items in the rectangle defined
2101 by X1,Y1,X2,Y2."""
2102 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2103 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2104 """Add tag NEWTAG to all items which overlap the rectangle
2105 defined by X1,Y1,X2,Y2."""
2106 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2107 def addtag_withtag(self, newtag, tagOrId):
2108 """Add tag NEWTAG to all items with TAGORID."""
2109 self.addtag(newtag, 'withtag', tagOrId)
2110 def bbox(self, *args):
2111 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2112 which encloses all items with tags specified as arguments."""
2113 return self._getints(
2114 self.tk.call((self._w, 'bbox') + args)) or None
2115 def tag_unbind(self, tagOrId, sequence, funcid=None):
2116 """Unbind for all items with TAGORID for event SEQUENCE the
2117 function identified with FUNCID."""
2118 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2119 if funcid:
2120 self.deletecommand(funcid)
2121 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2122 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
2123
2124 An additional boolean parameter ADD specifies whether FUNC will be
2125 called additionally to the other bound function or whether it will
2126 replace the previous function. See bind for the return value."""
2127 return self._bind((self._w, 'bind', tagOrId),
2128 sequence, func, add)
2129 def canvasx(self, screenx, gridspacing=None):
2130 """Return the canvas x coordinate of pixel position SCREENX rounded
2131 to nearest multiple of GRIDSPACING units."""
2132 return getdouble(self.tk.call(
2133 self._w, 'canvasx', screenx, gridspacing))
2134 def canvasy(self, screeny, gridspacing=None):
2135 """Return the canvas y coordinate of pixel position SCREENY rounded
2136 to nearest multiple of GRIDSPACING units."""
2137 return getdouble(self.tk.call(
2138 self._w, 'canvasy', screeny, gridspacing))
2139 def coords(self, *args):
2140 """Return a list of coordinates for the item given in ARGS."""
2141 # XXX Should use _flatten on args
2142 return map(getdouble,
2143 self.tk.splitlist(
2144 self.tk.call((self._w, 'coords') + args)))
2145 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2146 """Internal function."""
2147 args = _flatten(args)
2148 cnf = args[-1]
2149 if type(cnf) in (DictionaryType, TupleType):
2150 args = args[:-1]
2151 else:
2152 cnf = {}
2153 return getint(self.tk.call(
2154 self._w, 'create', itemType,
2155 *(args + self._options(cnf, kw))))
2156 def create_arc(self, *args, **kw):
2157 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2158 return self._create('arc', args, kw)
2159 def create_bitmap(self, *args, **kw):
2160 """Create bitmap with coordinates x1,y1."""
2161 return self._create('bitmap', args, kw)
2162 def create_image(self, *args, **kw):
2163 """Create image item with coordinates x1,y1."""
2164 return self._create('image', args, kw)
2165 def create_line(self, *args, **kw):
2166 """Create line with coordinates x1,y1,...,xn,yn."""
2167 return self._create('line', args, kw)
2168 def create_oval(self, *args, **kw):
2169 """Create oval with coordinates x1,y1,x2,y2."""
2170 return self._create('oval', args, kw)
2171 def create_polygon(self, *args, **kw):
2172 """Create polygon with coordinates x1,y1,...,xn,yn."""
2173 return self._create('polygon', args, kw)
2174 def create_rectangle(self, *args, **kw):
2175 """Create rectangle with coordinates x1,y1,x2,y2."""
2176 return self._create('rectangle', args, kw)
2177 def create_text(self, *args, **kw):
2178 """Create text with coordinates x1,y1."""
2179 return self._create('text', args, kw)
2180 def create_window(self, *args, **kw):
2181 """Create window with coordinates x1,y1,x2,y2."""
2182 return self._create('window', args, kw)
2183 def dchars(self, *args):
2184 """Delete characters of text items identified by tag or id in ARGS (possibly
2185 several times) from FIRST to LAST character (including)."""
2186 self.tk.call((self._w, 'dchars') + args)
2187 def delete(self, *args):
2188 """Delete items identified by all tag or ids contained in ARGS."""
2189 self.tk.call((self._w, 'delete') + args)
2190 def dtag(self, *args):
2191 """Delete tag or id given as last arguments in ARGS from items
2192 identified by first argument in ARGS."""
2193 self.tk.call((self._w, 'dtag') + args)
2194 def find(self, *args):
2195 """Internal function."""
2196 return self._getints(
2197 self.tk.call((self._w, 'find') + args)) or ()
2198 def find_above(self, tagOrId):
2199 """Return items above TAGORID."""
2200 return self.find('above', tagOrId)
2201 def find_all(self):
2202 """Return all items."""
2203 return self.find('all')
2204 def find_below(self, tagOrId):
2205 """Return all items below TAGORID."""
2206 return self.find('below', tagOrId)
2207 def find_closest(self, x, y, halo=None, start=None):
2208 """Return item which is closest to pixel at X, Y.
2209 If several match take the top-most.
2210 All items closer than HALO are considered overlapping (all are
2211 closests). If START is specified the next below this tag is taken."""
2212 return self.find('closest', x, y, halo, start)
2213 def find_enclosed(self, x1, y1, x2, y2):
2214 """Return all items in rectangle defined
2215 by X1,Y1,X2,Y2."""
2216 return self.find('enclosed', x1, y1, x2, y2)
2217 def find_overlapping(self, x1, y1, x2, y2):
2218 """Return all items which overlap the rectangle
2219 defined by X1,Y1,X2,Y2."""
2220 return self.find('overlapping', x1, y1, x2, y2)
2221 def find_withtag(self, tagOrId):
2222 """Return all items with TAGORID."""
2223 return self.find('withtag', tagOrId)
2224 def focus(self, *args):
2225 """Set focus to the first item specified in ARGS."""
2226 return self.tk.call((self._w, 'focus') + args)
2227 def gettags(self, *args):
2228 """Return tags associated with the first item specified in ARGS."""
2229 return self.tk.splitlist(
2230 self.tk.call((self._w, 'gettags') + args))
2231 def icursor(self, *args):
2232 """Set cursor at position POS in the item identified by TAGORID.
2233 In ARGS TAGORID must be first."""
2234 self.tk.call((self._w, 'icursor') + args)
2235 def index(self, *args):
2236 """Return position of cursor as integer in item specified in ARGS."""
2237 return getint(self.tk.call((self._w, 'index') + args))
2238 def insert(self, *args):
2239 """Insert TEXT in item TAGORID at position POS. ARGS must
2240 be TAGORID POS TEXT."""
2241 self.tk.call((self._w, 'insert') + args)
2242 def itemcget(self, tagOrId, option):
2243 """Return the resource value for an OPTION for item TAGORID."""
2244 return self.tk.call(
2245 (self._w, 'itemcget') + (tagOrId, '-'+option))
2246 def itemconfigure(self, tagOrId, cnf=None, **kw):
2247 """Configure resources of an item TAGORID.
2248
2249 The values for resources are specified as keyword
2250 arguments. To get an overview about
2251 the allowed keyword arguments call the method without arguments.
2252 """
2253 return self._configure(('itemconfigure', tagOrId), cnf, kw)
2254 itemconfig = itemconfigure
2255 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2256 # so the preferred name for them is tag_lower, tag_raise
2257 # (similar to tag_bind, and similar to the Text widget);
2258 # unfortunately can't delete the old ones yet (maybe in 1.6)
2259 def tag_lower(self, *args):
2260 """Lower an item TAGORID given in ARGS
2261 (optional below another item)."""
2262 self.tk.call((self._w, 'lower') + args)
2263 lower = tag_lower
2264 def move(self, *args):
2265 """Move an item TAGORID given in ARGS."""
2266 self.tk.call((self._w, 'move') + args)
2267 def postscript(self, cnf={}, **kw):
2268 """Print the contents of the canvas to a postscript
2269 file. Valid options: colormap, colormode, file, fontmap,
2270 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2271 rotate, witdh, x, y."""
2272 return self.tk.call((self._w, 'postscript') +
2273 self._options(cnf, kw))
2274 def tag_raise(self, *args):
2275 """Raise an item TAGORID given in ARGS
2276 (optional above another item)."""
2277 self.tk.call((self._w, 'raise') + args)
2278 lift = tkraise = tag_raise
2279 def scale(self, *args):
2280 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2281 self.tk.call((self._w, 'scale') + args)
2282 def scan_mark(self, x, y):
2283 """Remember the current X, Y coordinates."""
2284 self.tk.call(self._w, 'scan', 'mark', x, y)
2285 def scan_dragto(self, x, y, gain=10):
2286 """Adjust the view of the canvas to GAIN times the
2287 difference between X and Y and the coordinates given in
2288 scan_mark."""
2289 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
2290 def select_adjust(self, tagOrId, index):
2291 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2292 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2293 def select_clear(self):
2294 """Clear the selection if it is in this widget."""
2295 self.tk.call(self._w, 'select', 'clear')
2296 def select_from(self, tagOrId, index):
2297 """Set the fixed end of a selection in item TAGORID to INDEX."""
2298 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2299 def select_item(self):
2300 """Return the item which has the selection."""
2301 return self.tk.call(self._w, 'select', 'item') or None
2302 def select_to(self, tagOrId, index):
2303 """Set the variable end of a selection in item TAGORID to INDEX."""
2304 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2305 def type(self, tagOrId):
2306 """Return the type of the item TAGORID."""
2307 return self.tk.call(self._w, 'type', tagOrId) or None
2308 def xview(self, *args):
2309 """Query and change horizontal position of the view."""
2310 if not args:
2311 return self._getdoubles(self.tk.call(self._w, 'xview'))
2312 self.tk.call((self._w, 'xview') + args)
2313 def xview_moveto(self, fraction):
2314 """Adjusts the view in the window so that FRACTION of the
2315 total width of the canvas is off-screen to the left."""
2316 self.tk.call(self._w, 'xview', 'moveto', fraction)
2317 def xview_scroll(self, number, what):
2318 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2319 self.tk.call(self._w, 'xview', 'scroll', number, what)
2320 def yview(self, *args):
2321 """Query and change vertical position of the view."""
2322 if not args:
2323 return self._getdoubles(self.tk.call(self._w, 'yview'))
2324 self.tk.call((self._w, 'yview') + args)
2325 def yview_moveto(self, fraction):
2326 """Adjusts the view in the window so that FRACTION of the
2327 total height of the canvas is off-screen to the top."""
2328 self.tk.call(self._w, 'yview', 'moveto', fraction)
2329 def yview_scroll(self, number, what):
2330 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2331 self.tk.call(self._w, 'yview', 'scroll', number, what)
2332
2333class Checkbutton(Widget):
2334 """Checkbutton widget which is either in on- or off-state."""
2335 def __init__(self, master=None, cnf={}, **kw):
2336 """Construct a checkbutton widget with the parent MASTER.
2337
2338 Valid resource names: activebackground, activeforeground, anchor,
2339 background, bd, bg, bitmap, borderwidth, command, cursor,
2340 disabledforeground, fg, font, foreground, height,
2341 highlightbackground, highlightcolor, highlightthickness, image,
2342 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2343 selectcolor, selectimage, state, takefocus, text, textvariable,
2344 underline, variable, width, wraplength."""
2345 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2346 def deselect(self):
2347 """Put the button in off-state."""
2348 self.tk.call(self._w, 'deselect')
2349 def flash(self):
2350 """Flash the button."""
2351 self.tk.call(self._w, 'flash')
2352 def invoke(self):
2353 """Toggle the button and invoke a command if given as resource."""
2354 return self.tk.call(self._w, 'invoke')
2355 def select(self):
2356 """Put the button in on-state."""
2357 self.tk.call(self._w, 'select')
2358 def toggle(self):
2359 """Toggle the button."""
2360 self.tk.call(self._w, 'toggle')
2361
2362class Entry(Widget):
2363 """Entry widget which allows to display simple text."""
2364 def __init__(self, master=None, cnf={}, **kw):
2365 """Construct an entry widget with the parent MASTER.
2366
2367 Valid resource names: background, bd, bg, borderwidth, cursor,
2368 exportselection, fg, font, foreground, highlightbackground,
2369 highlightcolor, highlightthickness, insertbackground,
2370 insertborderwidth, insertofftime, insertontime, insertwidth,
2371 invalidcommand, invcmd, justify, relief, selectbackground,
2372 selectborderwidth, selectforeground, show, state, takefocus,
2373 textvariable, validate, validatecommand, vcmd, width,
2374 xscrollcommand."""
2375 Widget.__init__(self, master, 'entry', cnf, kw)
2376 def delete(self, first, last=None):
2377 """Delete text from FIRST to LAST (not included)."""
2378 self.tk.call(self._w, 'delete', first, last)
2379 def get(self):
2380 """Return the text."""
2381 return self.tk.call(self._w, 'get')
2382 def icursor(self, index):
2383 """Insert cursor at INDEX."""
2384 self.tk.call(self._w, 'icursor', index)
2385 def index(self, index):
2386 """Return position of cursor."""
2387 return getint(self.tk.call(
2388 self._w, 'index', index))
2389 def insert(self, index, string):
2390 """Insert STRING at INDEX."""
2391 self.tk.call(self._w, 'insert', index, string)
2392 def scan_mark(self, x):
2393 """Remember the current X, Y coordinates."""
2394 self.tk.call(self._w, 'scan', 'mark', x)
2395 def scan_dragto(self, x):
2396 """Adjust the view of the canvas to 10 times the
2397 difference between X and Y and the coordinates given in
2398 scan_mark."""
2399 self.tk.call(self._w, 'scan', 'dragto', x)
2400 def selection_adjust(self, index):
2401 """Adjust the end of the selection near the cursor to INDEX."""
2402 self.tk.call(self._w, 'selection', 'adjust', index)
2403 select_adjust = selection_adjust
2404 def selection_clear(self):
2405 """Clear the selection if it is in this widget."""
2406 self.tk.call(self._w, 'selection', 'clear')
2407 select_clear = selection_clear
2408 def selection_from(self, index):
2409 """Set the fixed end of a selection to INDEX."""
2410 self.tk.call(self._w, 'selection', 'from', index)
2411 select_from = selection_from
2412 def selection_present(self):
2413 """Return whether the widget has the selection."""
2414 return self.tk.getboolean(
2415 self.tk.call(self._w, 'selection', 'present'))
2416 select_present = selection_present
2417 def selection_range(self, start, end):
2418 """Set the selection from START to END (not included)."""
2419 self.tk.call(self._w, 'selection', 'range', start, end)
2420 select_range = selection_range
2421 def selection_to(self, index):
2422 """Set the variable end of a selection to INDEX."""
2423 self.tk.call(self._w, 'selection', 'to', index)
2424 select_to = selection_to
2425 def xview(self, index):
2426 """Query and change horizontal position of the view."""
2427 self.tk.call(self._w, 'xview', index)
2428 def xview_moveto(self, fraction):
2429 """Adjust the view in the window so that FRACTION of the
2430 total width of the entry is off-screen to the left."""
2431 self.tk.call(self._w, 'xview', 'moveto', fraction)
2432 def xview_scroll(self, number, what):
2433 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2434 self.tk.call(self._w, 'xview', 'scroll', number, what)
2435
2436class Frame(Widget):
2437 """Frame widget which may contain other widgets and can have a 3D border."""
2438 def __init__(self, master=None, cnf={}, **kw):
2439 """Construct a frame widget with the parent MASTER.
2440
2441 Valid resource names: background, bd, bg, borderwidth, class,
2442 colormap, container, cursor, height, highlightbackground,
2443 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2444 cnf = _cnfmerge((cnf, kw))
2445 extra = ()
2446 if cnf.has_key('class_'):
2447 extra = ('-class', cnf['class_'])
2448 del cnf['class_']
2449 elif cnf.has_key('class'):
2450 extra = ('-class', cnf['class'])
2451 del cnf['class']
2452 Widget.__init__(self, master, 'frame', cnf, {}, extra)
2453
2454class Label(Widget):
2455 """Label widget which can display text and bitmaps."""
2456 def __init__(self, master=None, cnf={}, **kw):
2457 """Construct a label widget with the parent MASTER.
2458
2459 STANDARD OPTIONS
2460
2461 activebackground, activeforeground, anchor,
2462 background, bitmap, borderwidth, cursor,
2463 disabledforeground, font, foreground,
2464 highlightbackground, highlightcolor,
2465 highlightthickness, image, justify,
2466 padx, pady, relief, takefocus, text,
2467 textvariable, underline, wraplength
2468
2469 WIDGET-SPECIFIC OPTIONS
2470
2471 height, state, width
2472
2473 """
2474 Widget.__init__(self, master, 'label', cnf, kw)
2475
2476class Listbox(Widget):
2477 """Listbox widget which can display a list of strings."""
2478 def __init__(self, master=None, cnf={}, **kw):
2479 """Construct a listbox widget with the parent MASTER.
2480
2481 Valid resource names: background, bd, bg, borderwidth, cursor,
2482 exportselection, fg, font, foreground, height, highlightbackground,
2483 highlightcolor, highlightthickness, relief, selectbackground,
2484 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2485 width, xscrollcommand, yscrollcommand, listvariable."""
2486 Widget.__init__(self, master, 'listbox', cnf, kw)
2487 def activate(self, index):
2488 """Activate item identified by INDEX."""
2489 self.tk.call(self._w, 'activate', index)
2490 def bbox(self, *args):
2491 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2492 which encloses the item identified by index in ARGS."""
2493 return self._getints(
2494 self.tk.call((self._w, 'bbox') + args)) or None
2495 def curselection(self):
2496 """Return list of indices of currently selected item."""
2497 # XXX Ought to apply self._getints()...
2498 return self.tk.splitlist(self.tk.call(
2499 self._w, 'curselection'))
2500 def delete(self, first, last=None):
2501 """Delete items from FIRST to LAST (not included)."""
2502 self.tk.call(self._w, 'delete', first, last)
2503 def get(self, first, last=None):
2504 """Get list of items from FIRST to LAST (not included)."""
2505 if last:
2506 return self.tk.splitlist(self.tk.call(
2507 self._w, 'get', first, last))
2508 else:
2509 return self.tk.call(self._w, 'get', first)
2510 def index(self, index):
2511 """Return index of item identified with INDEX."""
2512 i = self.tk.call(self._w, 'index', index)
2513 if i == 'none': return None
2514 return getint(i)
2515 def insert(self, index, *elements):
2516 """Insert ELEMENTS at INDEX."""
2517 self.tk.call((self._w, 'insert', index) + elements)
2518 def nearest(self, y):
2519 """Get index of item which is nearest to y coordinate Y."""
2520 return getint(self.tk.call(
2521 self._w, 'nearest', y))
2522 def scan_mark(self, x, y):
2523 """Remember the current X, Y coordinates."""
2524 self.tk.call(self._w, 'scan', 'mark', x, y)
2525 def scan_dragto(self, x, y):
2526 """Adjust the view of the listbox to 10 times the
2527 difference between X and Y and the coordinates given in
2528 scan_mark."""
2529 self.tk.call(self._w, 'scan', 'dragto', x, y)
2530 def see(self, index):
2531 """Scroll such that INDEX is visible."""
2532 self.tk.call(self._w, 'see', index)
2533 def selection_anchor(self, index):
2534 """Set the fixed end oft the selection to INDEX."""
2535 self.tk.call(self._w, 'selection', 'anchor', index)
2536 select_anchor = selection_anchor
2537 def selection_clear(self, first, last=None):
2538 """Clear the selection from FIRST to LAST (not included)."""
2539 self.tk.call(self._w,
2540 'selection', 'clear', first, last)
2541 select_clear = selection_clear
2542 def selection_includes(self, index):
2543 """Return 1 if INDEX is part of the selection."""
2544 return self.tk.getboolean(self.tk.call(
2545 self._w, 'selection', 'includes', index))
2546 select_includes = selection_includes
2547 def selection_set(self, first, last=None):
2548 """Set the selection from FIRST to LAST (not included) without
2549 changing the currently selected elements."""
2550 self.tk.call(self._w, 'selection', 'set', first, last)
2551 select_set = selection_set
2552 def size(self):
2553 """Return the number of elements in the listbox."""
2554 return getint(self.tk.call(self._w, 'size'))
2555 def xview(self, *what):
2556 """Query and change horizontal position of the view."""
2557 if not what:
2558 return self._getdoubles(self.tk.call(self._w, 'xview'))
2559 self.tk.call((self._w, 'xview') + what)
2560 def xview_moveto(self, fraction):
2561 """Adjust the view in the window so that FRACTION of the
2562 total width of the entry is off-screen to the left."""
2563 self.tk.call(self._w, 'xview', 'moveto', fraction)
2564 def xview_scroll(self, number, what):
2565 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2566 self.tk.call(self._w, 'xview', 'scroll', number, what)
2567 def yview(self, *what):
2568 """Query and change vertical position of the view."""
2569 if not what:
2570 return self._getdoubles(self.tk.call(self._w, 'yview'))
2571 self.tk.call((self._w, 'yview') + what)
2572 def yview_moveto(self, fraction):
2573 """Adjust the view in the window so that FRACTION of the
2574 total width of the entry is off-screen to the top."""
2575 self.tk.call(self._w, 'yview', 'moveto', fraction)
2576 def yview_scroll(self, number, what):
2577 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2578 self.tk.call(self._w, 'yview', 'scroll', number, what)
2579 def itemcget(self, index, option):
2580 """Return the resource value for an ITEM and an OPTION."""
2581 return self.tk.call(
2582 (self._w, 'itemcget') + (index, '-'+option))
2583 def itemconfigure(self, index, cnf=None, **kw):
2584 """Configure resources of an ITEM.
2585
2586 The values for resources are specified as keyword arguments.
2587 To get an overview about the allowed keyword arguments
2588 call the method without arguments.
2589 Valid resource names: background, bg, foreground, fg,
2590 selectbackground, selectforeground."""
2591 return self._configure(('itemconfigure', index), cnf, kw)
2592 itemconfig = itemconfigure
2593
2594class Menu(Widget):
2595 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2596 def __init__(self, master=None, cnf={}, **kw):
2597 """Construct menu widget with the parent MASTER.
2598
2599 Valid resource names: activebackground, activeborderwidth,
2600 activeforeground, background, bd, bg, borderwidth, cursor,
2601 disabledforeground, fg, font, foreground, postcommand, relief,
2602 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2603 Widget.__init__(self, master, 'menu', cnf, kw)
2604 def tk_bindForTraversal(self):
2605 pass # obsolete since Tk 4.0
2606 def tk_mbPost(self):
2607 self.tk.call('tk_mbPost', self._w)
2608 def tk_mbUnpost(self):
2609 self.tk.call('tk_mbUnpost')
2610 def tk_traverseToMenu(self, char):
2611 self.tk.call('tk_traverseToMenu', self._w, char)
2612 def tk_traverseWithinMenu(self, char):
2613 self.tk.call('tk_traverseWithinMenu', self._w, char)
2614 def tk_getMenuButtons(self):
2615 return self.tk.call('tk_getMenuButtons', self._w)
2616 def tk_nextMenu(self, count):
2617 self.tk.call('tk_nextMenu', count)
2618 def tk_nextMenuEntry(self, count):
2619 self.tk.call('tk_nextMenuEntry', count)
2620 def tk_invokeMenu(self):
2621 self.tk.call('tk_invokeMenu', self._w)
2622 def tk_firstMenu(self):
2623 self.tk.call('tk_firstMenu', self._w)
2624 def tk_mbButtonDown(self):
2625 self.tk.call('tk_mbButtonDown', self._w)
2626 def tk_popup(self, x, y, entry=""):
2627 """Post the menu at position X,Y with entry ENTRY."""
2628 self.tk.call('tk_popup', self._w, x, y, entry)
2629 def activate(self, index):
2630 """Activate entry at INDEX."""
2631 self.tk.call(self._w, 'activate', index)
2632 def add(self, itemType, cnf={}, **kw):
2633 """Internal function."""
2634 self.tk.call((self._w, 'add', itemType) +
2635 self._options(cnf, kw))
2636 def add_cascade(self, cnf={}, **kw):
2637 """Add hierarchical menu item."""
2638 self.add('cascade', cnf or kw)
2639 def add_checkbutton(self, cnf={}, **kw):
2640 """Add checkbutton menu item."""
2641 self.add('checkbutton', cnf or kw)
2642 def add_command(self, cnf={}, **kw):
2643 """Add command menu item."""
2644 self.add('command', cnf or kw)
2645 def add_radiobutton(self, cnf={}, **kw):
2646 """Addd radio menu item."""
2647 self.add('radiobutton', cnf or kw)
2648 def add_separator(self, cnf={}, **kw):
2649 """Add separator."""
2650 self.add('separator', cnf or kw)
2651 def insert(self, index, itemType, cnf={}, **kw):
2652 """Internal function."""
2653 self.tk.call((self._w, 'insert', index, itemType) +
2654 self._options(cnf, kw))
2655 def insert_cascade(self, index, cnf={}, **kw):
2656 """Add hierarchical menu item at INDEX."""
2657 self.insert(index, 'cascade', cnf or kw)
2658 def insert_checkbutton(self, index, cnf={}, **kw):
2659 """Add checkbutton menu item at INDEX."""
2660 self.insert(index, 'checkbutton', cnf or kw)
2661 def insert_command(self, index, cnf={}, **kw):
2662 """Add command menu item at INDEX."""
2663 self.insert(index, 'command', cnf or kw)
2664 def insert_radiobutton(self, index, cnf={}, **kw):
2665 """Addd radio menu item at INDEX."""
2666 self.insert(index, 'radiobutton', cnf or kw)
2667 def insert_separator(self, index, cnf={}, **kw):
2668 """Add separator at INDEX."""
2669 self.insert(index, 'separator', cnf or kw)
2670 def delete(self, index1, index2=None):
2671 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2672 self.tk.call(self._w, 'delete', index1, index2)
2673 def entrycget(self, index, option):
2674 """Return the resource value of an menu item for OPTION at INDEX."""
2675 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2676 def entryconfigure(self, index, cnf=None, **kw):
2677 """Configure a menu item at INDEX."""
2678 return self._configure(('entryconfigure', index), cnf, kw)
2679 entryconfig = entryconfigure
2680 def index(self, index):
2681 """Return the index of a menu item identified by INDEX."""
2682 i = self.tk.call(self._w, 'index', index)
2683 if i == 'none': return None
2684 return getint(i)
2685 def invoke(self, index):
2686 """Invoke a menu item identified by INDEX and execute
2687 the associated command."""
2688 return self.tk.call(self._w, 'invoke', index)
2689 def post(self, x, y):
2690 """Display a menu at position X,Y."""
2691 self.tk.call(self._w, 'post', x, y)
2692 def type(self, index):
2693 """Return the type of the menu item at INDEX."""
2694 return self.tk.call(self._w, 'type', index)
2695 def unpost(self):
2696 """Unmap a menu."""
2697 self.tk.call(self._w, 'unpost')
2698 def yposition(self, index):
2699 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2700 return getint(self.tk.call(
2701 self._w, 'yposition', index))
2702
2703class Menubutton(Widget):
2704 """Menubutton widget, obsolete since Tk8.0."""
2705 def __init__(self, master=None, cnf={}, **kw):
2706 Widget.__init__(self, master, 'menubutton', cnf, kw)
2707
2708class Message(Widget):
2709 """Message widget to display multiline text. Obsolete since Label does it too."""
2710 def __init__(self, master=None, cnf={}, **kw):
2711 Widget.__init__(self, master, 'message', cnf, kw)
2712
2713class Radiobutton(Widget):
2714 """Radiobutton widget which shows only one of several buttons in on-state."""
2715 def __init__(self, master=None, cnf={}, **kw):
2716 """Construct a radiobutton widget with the parent MASTER.
2717
2718 Valid resource names: activebackground, activeforeground, anchor,
2719 background, bd, bg, bitmap, borderwidth, command, cursor,
2720 disabledforeground, fg, font, foreground, height,
2721 highlightbackground, highlightcolor, highlightthickness, image,
2722 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2723 state, takefocus, text, textvariable, underline, value, variable,
2724 width, wraplength."""
2725 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2726 def deselect(self):
2727 """Put the button in off-state."""
2728
2729 self.tk.call(self._w, 'deselect')
2730 def flash(self):
2731 """Flash the button."""
2732 self.tk.call(self._w, 'flash')
2733 def invoke(self):
2734 """Toggle the button and invoke a command if given as resource."""
2735 return self.tk.call(self._w, 'invoke')
2736 def select(self):
2737 """Put the button in on-state."""
2738 self.tk.call(self._w, 'select')
2739
2740class Scale(Widget):
2741 """Scale widget which can display a numerical scale."""
2742 def __init__(self, master=None, cnf={}, **kw):
2743 """Construct a scale widget with the parent MASTER.
2744
2745 Valid resource names: activebackground, background, bigincrement, bd,
2746 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2747 highlightbackground, highlightcolor, highlightthickness, label,
2748 length, orient, relief, repeatdelay, repeatinterval, resolution,
2749 showvalue, sliderlength, sliderrelief, state, takefocus,
2750 tickinterval, to, troughcolor, variable, width."""
2751 Widget.__init__(self, master, 'scale', cnf, kw)
2752 def get(self):
2753 """Get the current value as integer or float."""
2754 value = self.tk.call(self._w, 'get')
2755 try:
2756 return getint(value)
2757 except ValueError:
2758 return getdouble(value)
2759 def set(self, value):
2760 """Set the value to VALUE."""
2761 self.tk.call(self._w, 'set', value)
2762 def coords(self, value=None):
2763 """Return a tuple (X,Y) of the point along the centerline of the
2764 trough that corresponds to VALUE or the current value if None is
2765 given."""
2766
2767 return self._getints(self.tk.call(self._w, 'coords', value))
2768 def identify(self, x, y):
2769 """Return where the point X,Y lies. Valid return values are "slider",
2770 "though1" and "though2"."""
2771 return self.tk.call(self._w, 'identify', x, y)
2772
2773class Scrollbar(Widget):
2774 """Scrollbar widget which displays a slider at a certain position."""
2775 def __init__(self, master=None, cnf={}, **kw):
2776 """Construct a scrollbar widget with the parent MASTER.
2777
2778 Valid resource names: activebackground, activerelief,
2779 background, bd, bg, borderwidth, command, cursor,
2780 elementborderwidth, highlightbackground,
2781 highlightcolor, highlightthickness, jump, orient,
2782 relief, repeatdelay, repeatinterval, takefocus,
2783 troughcolor, width."""
2784 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2785 def activate(self, index):
2786 """Display the element at INDEX with activebackground and activerelief.
2787 INDEX can be "arrow1","slider" or "arrow2"."""
2788 self.tk.call(self._w, 'activate', index)
2789 def delta(self, deltax, deltay):
2790 """Return the fractional change of the scrollbar setting if it
2791 would be moved by DELTAX or DELTAY pixels."""
2792 return getdouble(
2793 self.tk.call(self._w, 'delta', deltax, deltay))
2794 def fraction(self, x, y):
2795 """Return the fractional value which corresponds to a slider
2796 position of X,Y."""
2797 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2798 def identify(self, x, y):
2799 """Return the element under position X,Y as one of
2800 "arrow1","slider","arrow2" or ""."""
2801 return self.tk.call(self._w, 'identify', x, y)
2802 def get(self):
2803 """Return the current fractional values (upper and lower end)
2804 of the slider position."""
2805 return self._getdoubles(self.tk.call(self._w, 'get'))
2806 def set(self, *args):
2807 """Set the fractional values of the slider position (upper and
2808 lower ends as value between 0 and 1)."""
2809 self.tk.call((self._w, 'set') + args)
2810
2811
2812
2813class Text(Widget):
2814 """Text widget which can display text in various forms."""
2815 def __init__(self, master=None, cnf={}, **kw):
2816 """Construct a text widget with the parent MASTER.
2817
2818 STANDARD OPTIONS
2819
2820 background, borderwidth, cursor,
2821 exportselection, font, foreground,
2822 highlightbackground, highlightcolor,
2823 highlightthickness, insertbackground,
2824 insertborderwidth, insertofftime,
2825 insertontime, insertwidth, padx, pady,
2826 relief, selectbackground,
2827 selectborderwidth, selectforeground,
2828 setgrid, takefocus,
2829 xscrollcommand, yscrollcommand,
2830
2831 WIDGET-SPECIFIC OPTIONS
2832
2833 autoseparators, height, maxundo,
2834 spacing1, spacing2, spacing3,
2835 state, tabs, undo, width, wrap,
2836
2837 """
2838 Widget.__init__(self, master, 'text', cnf, kw)
2839 def bbox(self, *args):
2840 """Return a tuple of (x,y,width,height) which gives the bounding
2841 box of the visible part of the character at the index in ARGS."""
2842 return self._getints(
2843 self.tk.call((self._w, 'bbox') + args)) or None
2844 def tk_textSelectTo(self, index):
2845 self.tk.call('tk_textSelectTo', self._w, index)
2846 def tk_textBackspace(self):
2847 self.tk.call('tk_textBackspace', self._w)
2848 def tk_textIndexCloser(self, a, b, c):
2849 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2850 def tk_textResetAnchor(self, index):
2851 self.tk.call('tk_textResetAnchor', self._w, index)
2852 def compare(self, index1, op, index2):
2853 """Return whether between index INDEX1 and index INDEX2 the
2854 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2855 return self.tk.getboolean(self.tk.call(
2856 self._w, 'compare', index1, op, index2))
2857 def debug(self, boolean=None):
2858 """Turn on the internal consistency checks of the B-Tree inside the text
2859 widget according to BOOLEAN."""
2860 return self.tk.getboolean(self.tk.call(
2861 self._w, 'debug', boolean))
2862 def delete(self, index1, index2=None):
2863 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2864 self.tk.call(self._w, 'delete', index1, index2)
2865 def dlineinfo(self, index):
2866 """Return tuple (x,y,width,height,baseline) giving the bounding box
2867 and baseline position of the visible part of the line containing
2868 the character at INDEX."""
2869 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
2870 def dump(self, index1, index2=None, command=None, **kw):
2871 """Return the contents of the widget between index1 and index2.
2872
2873 The type of contents returned in filtered based on the keyword
2874 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2875 given and true, then the corresponding items are returned. The result
2876 is a list of triples of the form (key, value, index). If none of the
2877 keywords are true then 'all' is used by default.
2878
2879 If the 'command' argument is given, it is called once for each element
2880 of the list of triples, with the values of each triple serving as the
2881 arguments to the function. In this case the list is not returned."""
2882 args = []
2883 func_name = None
2884 result = None
2885 if not command:
2886 # Never call the dump command without the -command flag, since the
2887 # output could involve Tcl quoting and would be a pain to parse
2888 # right. Instead just set the command to build a list of triples
2889 # as if we had done the parsing.
2890 result = []
2891 def append_triple(key, value, index, result=result):
2892 result.append((key, value, index))
2893 command = append_triple
2894 try:
2895 if not isinstance(command, str):
2896 func_name = command = self._register(command)
2897 args += ["-command", command]
2898 for key in kw:
2899 if kw[key]: args.append("-" + key)
2900 args.append(index1)
2901 if index2:
2902 args.append(index2)
2903 self.tk.call(self._w, "dump", *args)
2904 return result
2905 finally:
2906 if func_name:
2907 self.deletecommand(func_name)
2908
2909 ## new in tk8.4
2910 def edit(self, *args):
2911 """Internal method
2912
2913 This method controls the undo mechanism and
2914 the modified flag. The exact behavior of the
2915 command depends on the option argument that
2916 follows the edit argument. The following forms
2917 of the command are currently supported:
2918
2919 edit_modified, edit_redo, edit_reset, edit_separator
2920 and edit_undo
2921
2922 """
2923 return self.tk.call(self._w, 'edit', *args)
2924
2925 def edit_modified(self, arg=None):
2926 """Get or Set the modified flag
2927
2928 If arg is not specified, returns the modified
2929 flag of the widget. The insert, delete, edit undo and
2930 edit redo commands or the user can set or clear the
2931 modified flag. If boolean is specified, sets the
2932 modified flag of the widget to arg.
2933 """
2934 return self.edit("modified", arg)
2935
2936 def edit_redo(self):
2937 """Redo the last undone edit
2938
2939 When the undo option is true, reapplies the last
2940 undone edits provided no other edits were done since
2941 then. Generates an error when the redo stack is empty.
2942 Does nothing when the undo option is false.
2943 """
2944 return self.edit("redo")
2945
2946 def edit_reset(self):
2947 """Clears the undo and redo stacks
2948 """
2949 return self.edit("reset")
2950
2951 def edit_separator(self):
2952 """Inserts a separator (boundary) on the undo stack.
2953
2954 Does nothing when the undo option is false
2955 """
2956 return self.edit("separator")
2957
2958 def edit_undo(self):
2959 """Undoes the last edit action
2960
2961 If the undo option is true. An edit action is defined
2962 as all the insert and delete commands that are recorded
2963 on the undo stack in between two separators. Generates
2964 an error when the undo stack is empty. Does nothing
2965 when the undo option is false
2966 """
2967 return self.edit("undo")
2968
2969 def get(self, index1, index2=None):
2970 """Return the text from INDEX1 to INDEX2 (not included)."""
2971 return self.tk.call(self._w, 'get', index1, index2)
2972 # (Image commands are new in 8.0)
2973 def image_cget(self, index, option):
2974 """Return the value of OPTION of an embedded image at INDEX."""
2975 if option[:1] != "-":
2976 option = "-" + option
2977 if option[-1:] == "_":
2978 option = option[:-1]
2979 return self.tk.call(self._w, "image", "cget", index, option)
2980 def image_configure(self, index, cnf=None, **kw):
2981 """Configure an embedded image at INDEX."""
2982 return self._configure(('image', 'configure', index), cnf, kw)
2983 def image_create(self, index, cnf={}, **kw):
2984 """Create an embedded image at INDEX."""
2985 return self.tk.call(
2986 self._w, "image", "create", index,
2987 *self._options(cnf, kw))
2988 def image_names(self):
2989 """Return all names of embedded images in this widget."""
2990 return self.tk.call(self._w, "image", "names")
2991 def index(self, index):
2992 """Return the index in the form line.char for INDEX."""
2993 return str(self.tk.call(self._w, 'index', index))
2994 def insert(self, index, chars, *args):
2995 """Insert CHARS before the characters at INDEX. An additional
2996 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2997 self.tk.call((self._w, 'insert', index, chars) + args)
2998 def mark_gravity(self, markName, direction=None):
2999 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3000 Return the current value if None is given for DIRECTION."""
3001 return self.tk.call(
3002 (self._w, 'mark', 'gravity', markName, direction))
3003 def mark_names(self):
3004 """Return all mark names."""
3005 return self.tk.splitlist(self.tk.call(
3006 self._w, 'mark', 'names'))
3007 def mark_set(self, markName, index):
3008 """Set mark MARKNAME before the character at INDEX."""
3009 self.tk.call(self._w, 'mark', 'set', markName, index)
3010 def mark_unset(self, *markNames):
3011 """Delete all marks in MARKNAMES."""
3012 self.tk.call((self._w, 'mark', 'unset') + markNames)
3013 def mark_next(self, index):
3014 """Return the name of the next mark after INDEX."""
3015 return self.tk.call(self._w, 'mark', 'next', index) or None
3016 def mark_previous(self, index):
3017 """Return the name of the previous mark before INDEX."""
3018 return self.tk.call(self._w, 'mark', 'previous', index) or None
3019 def scan_mark(self, x, y):
3020 """Remember the current X, Y coordinates."""
3021 self.tk.call(self._w, 'scan', 'mark', x, y)
3022 def scan_dragto(self, x, y):
3023 """Adjust the view of the text to 10 times the
3024 difference between X and Y and the coordinates given in
3025 scan_mark."""
3026 self.tk.call(self._w, 'scan', 'dragto', x, y)
3027 def search(self, pattern, index, stopindex=None,
3028 forwards=None, backwards=None, exact=None,
3029 regexp=None, nocase=None, count=None, elide=None):
3030 """Search PATTERN beginning from INDEX until STOPINDEX.
3031 Return the index of the first character of a match or an empty string."""
3032 args = [self._w, 'search']
3033 if forwards: args.append('-forwards')
3034 if backwards: args.append('-backwards')
3035 if exact: args.append('-exact')
3036 if regexp: args.append('-regexp')
3037 if nocase: args.append('-nocase')
3038 if elide: args.append('-elide')
3039 if count: args.append('-count'); args.append(count)
3040 if pattern[0] == '-': args.append('--')
3041 args.append(pattern)
3042 args.append(index)
3043 if stopindex: args.append(stopindex)
3044 return self.tk.call(tuple(args))
3045 def see(self, index):
3046 """Scroll such that the character at INDEX is visible."""
3047 self.tk.call(self._w, 'see', index)
3048 def tag_add(self, tagName, index1, *args):
3049 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3050 Additional pairs of indices may follow in ARGS."""
3051 self.tk.call(
3052 (self._w, 'tag', 'add', tagName, index1) + args)
3053 def tag_unbind(self, tagName, sequence, funcid=None):
3054 """Unbind for all characters with TAGNAME for event SEQUENCE the
3055 function identified with FUNCID."""
3056 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3057 if funcid:
3058 self.deletecommand(funcid)
3059 def tag_bind(self, tagName, sequence, func, add=None):
3060 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
3061
3062 An additional boolean parameter ADD specifies whether FUNC will be
3063 called additionally to the other bound function or whether it will
3064 replace the previous function. See bind for the return value."""
3065 return self._bind((self._w, 'tag', 'bind', tagName),
3066 sequence, func, add)
3067 def tag_cget(self, tagName, option):
3068 """Return the value of OPTION for tag TAGNAME."""
3069 if option[:1] != '-':
3070 option = '-' + option
3071 if option[-1:] == '_':
3072 option = option[:-1]
3073 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
3074 def tag_configure(self, tagName, cnf=None, **kw):
3075 """Configure a tag TAGNAME."""
3076 return self._configure(('tag', 'configure', tagName), cnf, kw)
3077 tag_config = tag_configure
3078 def tag_delete(self, *tagNames):
3079 """Delete all tags in TAGNAMES."""
3080 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3081 def tag_lower(self, tagName, belowThis=None):
3082 """Change the priority of tag TAGNAME such that it is lower
3083 than the priority of BELOWTHIS."""
3084 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3085 def tag_names(self, index=None):
3086 """Return a list of all tag names."""
3087 return self.tk.splitlist(
3088 self.tk.call(self._w, 'tag', 'names', index))
3089 def tag_nextrange(self, tagName, index1, index2=None):
3090 """Return a list of start and end index for the first sequence of
3091 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3092 The text is searched forward from INDEX1."""
3093 return self.tk.splitlist(self.tk.call(
3094 self._w, 'tag', 'nextrange', tagName, index1, index2))
3095 def tag_prevrange(self, tagName, index1, index2=None):
3096 """Return a list of start and end index for the first sequence of
3097 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3098 The text is searched backwards from INDEX1."""
3099 return self.tk.splitlist(self.tk.call(
3100 self._w, 'tag', 'prevrange', tagName, index1, index2))
3101 def tag_raise(self, tagName, aboveThis=None):
3102 """Change the priority of tag TAGNAME such that it is higher
3103 than the priority of ABOVETHIS."""
3104 self.tk.call(
3105 self._w, 'tag', 'raise', tagName, aboveThis)
3106 def tag_ranges(self, tagName):
3107 """Return a list of ranges of text which have tag TAGNAME."""
3108 return self.tk.splitlist(self.tk.call(
3109 self._w, 'tag', 'ranges', tagName))
3110 def tag_remove(self, tagName, index1, index2=None):
3111 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3112 self.tk.call(
3113 self._w, 'tag', 'remove', tagName, index1, index2)
3114 def window_cget(self, index, option):
3115 """Return the value of OPTION of an embedded window at INDEX."""
3116 if option[:1] != '-':
3117 option = '-' + option
3118 if option[-1:] == '_':
3119 option = option[:-1]
3120 return self.tk.call(self._w, 'window', 'cget', index, option)
3121 def window_configure(self, index, cnf=None, **kw):
3122 """Configure an embedded window at INDEX."""
3123 return self._configure(('window', 'configure', index), cnf, kw)
3124 window_config = window_configure
3125 def window_create(self, index, cnf={}, **kw):
3126 """Create a window at INDEX."""
3127 self.tk.call(
3128 (self._w, 'window', 'create', index)
3129 + self._options(cnf, kw))
3130 def window_names(self):
3131 """Return all names of embedded windows in this widget."""
3132 return self.tk.splitlist(
3133 self.tk.call(self._w, 'window', 'names'))
3134 def xview(self, *what):
3135 """Query and change horizontal position of the view."""
3136 if not what:
3137 return self._getdoubles(self.tk.call(self._w, 'xview'))
3138 self.tk.call((self._w, 'xview') + what)
3139 def xview_moveto(self, fraction):
3140 """Adjusts the view in the window so that FRACTION of the
3141 total width of the canvas is off-screen to the left."""
3142 self.tk.call(self._w, 'xview', 'moveto', fraction)
3143 def xview_scroll(self, number, what):
3144 """Shift the x-view according to NUMBER which is measured
3145 in "units" or "pages" (WHAT)."""
3146 self.tk.call(self._w, 'xview', 'scroll', number, what)
3147 def yview(self, *what):
3148 """Query and change vertical position of the view."""
3149 if not what:
3150 return self._getdoubles(self.tk.call(self._w, 'yview'))
3151 self.tk.call((self._w, 'yview') + what)
3152 def yview_moveto(self, fraction):
3153 """Adjusts the view in the window so that FRACTION of the
3154 total height of the canvas is off-screen to the top."""
3155 self.tk.call(self._w, 'yview', 'moveto', fraction)
3156 def yview_scroll(self, number, what):
3157 """Shift the y-view according to NUMBER which is measured
3158 in "units" or "pages" (WHAT)."""
3159 self.tk.call(self._w, 'yview', 'scroll', number, what)
3160 def yview_pickplace(self, *what):
3161 """Obsolete function, use see."""
3162 self.tk.call((self._w, 'yview', '-pickplace') + what)
3163
3164
3165class _setit:
3166 """Internal class. It wraps the command in the widget OptionMenu."""
3167 def __init__(self, var, value, callback=None):
3168 self.__value = value
3169 self.__var = var
3170 self.__callback = callback
3171 def __call__(self, *args):
3172 self.__var.set(self.__value)
3173 if self.__callback:
3174 self.__callback(self.__value, *args)
3175
3176class OptionMenu(Menubutton):
3177 """OptionMenu which allows the user to select a value from a menu."""
3178 def __init__(self, master, variable, value, *values, **kwargs):
3179 """Construct an optionmenu widget with the parent MASTER, with
3180 the resource textvariable set to VARIABLE, the initially selected
3181 value VALUE, the other menu values VALUES and an additional
3182 keyword argument command."""
3183 kw = {"borderwidth": 2, "textvariable": variable,
3184 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3185 "highlightthickness": 2}
3186 Widget.__init__(self, master, "menubutton", kw)
3187 self.widgetName = 'tk_optionMenu'
3188 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3189 self.menuname = menu._w
3190 # 'command' is the only supported keyword
3191 callback = kwargs.get('command')
3192 if kwargs.has_key('command'):
3193 del kwargs['command']
3194 if kwargs:
3195 raise TclError, 'unknown option -'+kwargs.keys()[0]
3196 menu.add_command(label=value,
3197 command=_setit(variable, value, callback))
3198 for v in values:
3199 menu.add_command(label=v,
3200 command=_setit(variable, v, callback))
3201 self["menu"] = menu
3202
3203 def __getitem__(self, name):
3204 if name == 'menu':
3205 return self.__menu
3206 return Widget.__getitem__(self, name)
3207
3208 def destroy(self):
3209 """Destroy this widget and the associated menu."""
3210 Menubutton.destroy(self)
3211 self.__menu = None
3212
3213class Image:
3214 """Base class for images."""
3215 _last_id = 0
3216 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3217 self.name = None
3218 if not master:
3219 master = _default_root
3220 if not master:
3221 raise RuntimeError, 'Too early to create image'
3222 self.tk = master.tk
3223 if not name:
3224 Image._last_id += 1
3225 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
3226 # The following is needed for systems where id(x)
3227 # can return a negative number, such as Linux/m68k:
3228 if name[0] == '-': name = '_' + name[1:]
3229 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3230 elif kw: cnf = kw
3231 options = ()
3232 for k, v in cnf.items():
3233 if callable(v):
3234 v = self._register(v)
3235 options = options + ('-'+k, v)
3236 self.tk.call(('image', 'create', imgtype, name,) + options)
3237 self.name = name
3238 def __str__(self): return self.name
3239 def __del__(self):
3240 if self.name:
3241 try:
3242 self.tk.call('image', 'delete', self.name)
3243 except TclError:
3244 # May happen if the root was destroyed
3245 pass
3246 def __setitem__(self, key, value):
3247 self.tk.call(self.name, 'configure', '-'+key, value)
3248 def __getitem__(self, key):
3249 return self.tk.call(self.name, 'configure', '-'+key)
3250 def configure(self, **kw):
3251 """Configure the image."""
3252 res = ()
3253 for k, v in _cnfmerge(kw).items():
3254 if v is not None:
3255 if k[-1] == '_': k = k[:-1]
3256 if callable(v):
3257 v = self._register(v)
3258 res = res + ('-'+k, v)
3259 self.tk.call((self.name, 'config') + res)
3260 config = configure
3261 def height(self):
3262 """Return the height of the image."""
3263 return getint(
3264 self.tk.call('image', 'height', self.name))
3265 def type(self):
3266 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3267 return self.tk.call('image', 'type', self.name)
3268 def width(self):
3269 """Return the width of the image."""
3270 return getint(
3271 self.tk.call('image', 'width', self.name))
3272
3273class PhotoImage(Image):
3274 """Widget which can display colored images in GIF, PPM/PGM format."""
3275 def __init__(self, name=None, cnf={}, master=None, **kw):
3276 """Create an image with NAME.
3277
3278 Valid resource names: data, format, file, gamma, height, palette,
3279 width."""
3280 Image.__init__(self, 'photo', name, cnf, master, **kw)
3281 def blank(self):
3282 """Display a transparent image."""
3283 self.tk.call(self.name, 'blank')
3284 def cget(self, option):
3285 """Return the value of OPTION."""
3286 return self.tk.call(self.name, 'cget', '-' + option)
3287 # XXX config
3288 def __getitem__(self, key):
3289 return self.tk.call(self.name, 'cget', '-' + key)
3290 # XXX copy -from, -to, ...?
3291 def copy(self):
3292 """Return a new PhotoImage with the same image as this widget."""
3293 destImage = PhotoImage()
3294 self.tk.call(destImage, 'copy', self.name)
3295 return destImage
3296 def zoom(self,x,y=''):
3297 """Return a new PhotoImage with the same image as this widget
3298 but zoom it with X and Y."""
3299 destImage = PhotoImage()
3300 if y=='': y=x
3301 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3302 return destImage
3303 def subsample(self,x,y=''):
3304 """Return a new PhotoImage based on the same image as this widget
3305 but use only every Xth or Yth pixel."""
3306 destImage = PhotoImage()
3307 if y=='': y=x
3308 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3309 return destImage
3310 def get(self, x, y):
3311 """Return the color (red, green, blue) of the pixel at X,Y."""
3312 return self.tk.call(self.name, 'get', x, y)
3313 def put(self, data, to=None):
3314 """Put row formated colors to image starting from
3315 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3316 args = (self.name, 'put', data)
3317 if to:
3318 if to[0] == '-to':
3319 to = to[1:]
3320 args = args + ('-to',) + tuple(to)
3321 self.tk.call(args)
3322 # XXX read
3323 def write(self, filename, format=None, from_coords=None):
3324 """Write image to file FILENAME in FORMAT starting from
3325 position FROM_COORDS."""
3326 args = (self.name, 'write', filename)
3327 if format:
3328 args = args + ('-format', format)
3329 if from_coords:
3330 args = args + ('-from',) + tuple(from_coords)
3331 self.tk.call(args)
3332
3333class BitmapImage(Image):
3334 """Widget which can display a bitmap."""
3335 def __init__(self, name=None, cnf={}, master=None, **kw):
3336 """Create a bitmap with NAME.
3337
3338 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3339 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
3340
3341def image_names(): return _default_root.tk.call('image', 'names')
3342def image_types(): return _default_root.tk.call('image', 'types')
3343
3344
3345class Spinbox(Widget):
3346 """spinbox widget."""
3347 def __init__(self, master=None, cnf={}, **kw):
3348 """Construct a spinbox widget with the parent MASTER.
3349
3350 STANDARD OPTIONS
3351
3352 activebackground, background, borderwidth,
3353 cursor, exportselection, font, foreground,
3354 highlightbackground, highlightcolor,
3355 highlightthickness, insertbackground,
3356 insertborderwidth, insertofftime,
3357 insertontime, insertwidth, justify, relief,
3358 repeatdelay, repeatinterval,
3359 selectbackground, selectborderwidth
3360 selectforeground, takefocus, textvariable
3361 xscrollcommand.
3362
3363 WIDGET-SPECIFIC OPTIONS
3364
3365 buttonbackground, buttoncursor,
3366 buttondownrelief, buttonuprelief,
3367 command, disabledbackground,
3368 disabledforeground, format, from,
3369 invalidcommand, increment,
3370 readonlybackground, state, to,
3371 validate, validatecommand values,
3372 width, wrap,
3373 """
3374 Widget.__init__(self, master, 'spinbox', cnf, kw)
3375
3376 def bbox(self, index):
3377 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3378 rectangle which encloses the character given by index.
3379
3380 The first two elements of the list give the x and y
3381 coordinates of the upper-left corner of the screen
3382 area covered by the character (in pixels relative
3383 to the widget) and the last two elements give the
3384 width and height of the character, in pixels. The
3385 bounding box may refer to a region outside the
3386 visible area of the window.
3387 """
3388 return self.tk.call(self._w, 'bbox', index)
3389
3390 def delete(self, first, last=None):
3391 """Delete one or more elements of the spinbox.
3392
3393 First is the index of the first character to delete,
3394 and last is the index of the character just after
3395 the last one to delete. If last isn't specified it
3396 defaults to first+1, i.e. a single character is
3397 deleted. This command returns an empty string.
3398 """
3399 return self.tk.call(self._w, 'delete', first, last)
3400
3401 def get(self):
3402 """Returns the spinbox's string"""
3403 return self.tk.call(self._w, 'get')
3404
3405 def icursor(self, index):
3406 """Alter the position of the insertion cursor.
3407
3408 The insertion cursor will be displayed just before
3409 the character given by index. Returns an empty string
3410 """
3411 return self.tk.call(self._w, 'icursor', index)
3412
3413 def identify(self, x, y):
3414 """Returns the name of the widget at position x, y
3415
3416 Return value is one of: none, buttondown, buttonup, entry
3417 """
3418 return self.tk.call(self._w, 'identify', x, y)
3419
3420 def index(self, index):
3421 """Returns the numerical index corresponding to index
3422 """
3423 return self.tk.call(self._w, 'index', index)
3424
3425 def insert(self, index, s):
3426 """Insert string s at index
3427
3428 Returns an empty string.
3429 """
3430 return self.tk.call(self._w, 'insert', index, s)
3431
3432 def invoke(self, element):
3433 """Causes the specified element to be invoked
3434
3435 The element could be buttondown or buttonup
3436 triggering the action associated with it.
3437 """
3438 return self.tk.call(self._w, 'invoke', element)
3439
3440 def scan(self, *args):
3441 """Internal function."""
3442 return self._getints(
3443 self.tk.call((self._w, 'scan') + args)) or ()
3444
3445 def scan_mark(self, x):
3446 """Records x and the current view in the spinbox window;
3447
3448 used in conjunction with later scan dragto commands.
3449 Typically this command is associated with a mouse button
3450 press in the widget. It returns an empty string.
3451 """
3452 return self.scan("mark", x)
3453
3454 def scan_dragto(self, x):
3455 """Compute the difference between the given x argument
3456 and the x argument to the last scan mark command
3457
3458 It then adjusts the view left or right by 10 times the
3459 difference in x-coordinates. This command is typically
3460 associated with mouse motion events in the widget, to
3461 produce the effect of dragging the spinbox at high speed
3462 through the window. The return value is an empty string.
3463 """
3464 return self.scan("dragto", x)
3465
3466 def selection(self, *args):
3467 """Internal function."""
3468 return self._getints(
3469 self.tk.call((self._w, 'selection') + args)) or ()
3470
3471 def selection_adjust(self, index):
3472 """Locate the end of the selection nearest to the character
3473 given by index,
3474
3475 Then adjust that end of the selection to be at index
3476 (i.e including but not going beyond index). The other
3477 end of the selection is made the anchor point for future
3478 select to commands. If the selection isn't currently in
3479 the spinbox, then a new selection is created to include
3480 the characters between index and the most recent selection
3481 anchor point, inclusive. Returns an empty string.
3482 """
3483 return self.selection("adjust", index)
3484
3485 def selection_clear(self):
3486 """Clear the selection
3487
3488 If the selection isn't in this widget then the
3489 command has no effect. Returns an empty string.
3490 """
3491 return self.selection("clear")
3492
3493 def selection_element(self, element=None):
3494 """Sets or gets the currently selected element.
3495
3496 If a spinbutton element is specified, it will be
3497 displayed depressed
3498 """
3499 return self.selection("element", element)
3500
3501###########################################################################
3502
3503class LabelFrame(Widget):
3504 """labelframe widget."""
3505 def __init__(self, master=None, cnf={}, **kw):
3506 """Construct a labelframe widget with the parent MASTER.
3507
3508 STANDARD OPTIONS
3509
3510 borderwidth, cursor, font, foreground,
3511 highlightbackground, highlightcolor,
3512 highlightthickness, padx, pady, relief,
3513 takefocus, text
3514
3515 WIDGET-SPECIFIC OPTIONS
3516
3517 background, class, colormap, container,
3518 height, labelanchor, labelwidget,
3519 visual, width
3520 """
3521 Widget.__init__(self, master, 'labelframe', cnf, kw)
3522
3523########################################################################
3524
3525class PanedWindow(Widget):
3526 """panedwindow widget."""
3527 def __init__(self, master=None, cnf={}, **kw):
3528 """Construct a panedwindow widget with the parent MASTER.
3529
3530 STANDARD OPTIONS
3531
3532 background, borderwidth, cursor, height,
3533 orient, relief, width
3534
3535 WIDGET-SPECIFIC OPTIONS
3536
3537 handlepad, handlesize, opaqueresize,
3538 sashcursor, sashpad, sashrelief,
3539 sashwidth, showhandle,
3540 """
3541 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3542
3543 def add(self, child, **kw):
3544 """Add a child widget to the panedwindow in a new pane.
3545
3546 The child argument is the name of the child widget
3547 followed by pairs of arguments that specify how to
3548 manage the windows. Options may have any of the values
3549 accepted by the configure subcommand.
3550 """
3551 self.tk.call((self._w, 'add', child) + self._options(kw))
3552
3553 def remove(self, child):
3554 """Remove the pane containing child from the panedwindow
3555
3556 All geometry management options for child will be forgotten.
3557 """
3558 self.tk.call(self._w, 'forget', child)
3559 forget=remove
3560
3561 def identify(self, x, y):
3562 """Identify the panedwindow component at point x, y
3563
3564 If the point is over a sash or a sash handle, the result
3565 is a two element list containing the index of the sash or
3566 handle, and a word indicating whether it is over a sash
3567 or a handle, such as {0 sash} or {2 handle}. If the point
3568 is over any other part of the panedwindow, the result is
3569 an empty list.
3570 """
3571 return self.tk.call(self._w, 'identify', x, y)
3572
3573 def proxy(self, *args):
3574 """Internal function."""
3575 return self._getints(
3576 self.tk.call((self._w, 'proxy') + args)) or ()
3577
3578 def proxy_coord(self):
3579 """Return the x and y pair of the most recent proxy location
3580 """
3581 return self.proxy("coord")
3582
3583 def proxy_forget(self):
3584 """Remove the proxy from the display.
3585 """
3586 return self.proxy("forget")
3587
3588 def proxy_place(self, x, y):
3589 """Place the proxy at the given x and y coordinates.
3590 """
3591 return self.proxy("place", x, y)
3592
3593 def sash(self, *args):
3594 """Internal function."""
3595 return self._getints(
3596 self.tk.call((self._w, 'sash') + args)) or ()
3597
3598 def sash_coord(self, index):
3599 """Return the current x and y pair for the sash given by index.
3600
3601 Index must be an integer between 0 and 1 less than the
3602 number of panes in the panedwindow. The coordinates given are
3603 those of the top left corner of the region containing the sash.
3604 pathName sash dragto index x y This command computes the
3605 difference between the given coordinates and the coordinates
3606 given to the last sash coord command for the given sash. It then
3607 moves that sash the computed difference. The return value is the
3608 empty string.
3609 """
3610 return self.sash("coord", index)
3611
3612 def sash_mark(self, index):
3613 """Records x and y for the sash given by index;
3614
3615 Used in conjunction with later dragto commands to move the sash.
3616 """
3617 return self.sash("mark", index)
3618
3619 def sash_place(self, index, x, y):
3620 """Place the sash given by index at the given coordinates
3621 """
3622 return self.sash("place", index, x, y)
3623
3624 def panecget(self, child, option):
3625 """Query a management option for window.
3626
3627 Option may be any value allowed by the paneconfigure subcommand
3628 """
3629 return self.tk.call(
3630 (self._w, 'panecget') + (child, '-'+option))
3631
3632 def paneconfigure(self, tagOrId, cnf=None, **kw):
3633 """Query or modify the management options for window.
3634
3635 If no option is specified, returns a list describing all
3636 of the available options for pathName. If option is
3637 specified with no value, then the command returns a list
3638 describing the one named option (this list will be identical
3639 to the corresponding sublist of the value returned if no
3640 option is specified). If one or more option-value pairs are
3641 specified, then the command modifies the given widget
3642 option(s) to have the given value(s); in this case the
3643 command returns an empty string. The following options
3644 are supported:
3645
3646 after window
3647 Insert the window after the window specified. window
3648 should be the name of a window already managed by pathName.
3649 before window
3650 Insert the window before the window specified. window
3651 should be the name of a window already managed by pathName.
3652 height size
3653 Specify a height for the window. The height will be the
3654 outer dimension of the window including its border, if
3655 any. If size is an empty string, or if -height is not
3656 specified, then the height requested internally by the
3657 window will be used initially; the height may later be
3658 adjusted by the movement of sashes in the panedwindow.
3659 Size may be any value accepted by Tk_GetPixels.
3660 minsize n
3661 Specifies that the size of the window cannot be made
3662 less than n. This constraint only affects the size of
3663 the widget in the paned dimension -- the x dimension
3664 for horizontal panedwindows, the y dimension for
3665 vertical panedwindows. May be any value accepted by
3666 Tk_GetPixels.
3667 padx n
3668 Specifies a non-negative value indicating how much
3669 extra space to leave on each side of the window in
3670 the X-direction. The value may have any of the forms
3671 accepted by Tk_GetPixels.
3672 pady n
3673 Specifies a non-negative value indicating how much
3674 extra space to leave on each side of the window in
3675 the Y-direction. The value may have any of the forms
3676 accepted by Tk_GetPixels.
3677 sticky style
3678 If a window's pane is larger than the requested
3679 dimensions of the window, this option may be used
3680 to position (or stretch) the window within its pane.
3681 Style is a string that contains zero or more of the
3682 characters n, s, e or w. The string can optionally
3683 contains spaces or commas, but they are ignored. Each
3684 letter refers to a side (north, south, east, or west)
3685 that the window will "stick" to. If both n and s
3686 (or e and w) are specified, the window will be
3687 stretched to fill the entire height (or width) of
3688 its cavity.
3689 width size
3690 Specify a width for the window. The width will be
3691 the outer dimension of the window including its
3692 border, if any. If size is an empty string, or
3693 if -width is not specified, then the width requested
3694 internally by the window will be used initially; the
3695 width may later be adjusted by the movement of sashes
3696 in the panedwindow. Size may be any value accepted by
3697 Tk_GetPixels.
3698
3699 """
3700 if cnf is None and not kw:
3701 cnf = {}
3702 for x in self.tk.split(
3703 self.tk.call(self._w,
3704 'paneconfigure', tagOrId)):
3705 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3706 return cnf
3707 if type(cnf) == StringType and not kw:
3708 x = self.tk.split(self.tk.call(
3709 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3710 return (x[0][1:],) + x[1:]
3711 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3712 self._options(cnf, kw))
3713 paneconfig = paneconfigure
3714
3715 def panes(self):
3716 """Returns an ordered list of the child panes."""
3717 return self.tk.call(self._w, 'panes')
3718
3719######################################################################
3720# Extensions:
3721
3722class Studbutton(Button):
3723 def __init__(self, master=None, cnf={}, **kw):
3724 Widget.__init__(self, master, 'studbutton', cnf, kw)
3725 self.bind('<Any-Enter>', self.tkButtonEnter)
3726 self.bind('<Any-Leave>', self.tkButtonLeave)
3727 self.bind('<1>', self.tkButtonDown)
3728 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3729
3730class Tributton(Button):
3731 def __init__(self, master=None, cnf={}, **kw):
3732 Widget.__init__(self, master, 'tributton', cnf, kw)
3733 self.bind('<Any-Enter>', self.tkButtonEnter)
3734 self.bind('<Any-Leave>', self.tkButtonLeave)
3735 self.bind('<1>', self.tkButtonDown)
3736 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3737 self['fg'] = self['bg']
3738 self['activebackground'] = self['bg']
3739
3740######################################################################
3741# Test:
3742
3743def _test():
3744 root = Tk()
3745 text = "This is Tcl/Tk version %s" % TclVersion
3746 if TclVersion >= 8.1:
3747 try:
3748 text = text + unicode("\nThis should be a cedilla: \347",
3749 "iso-8859-1")
3750 except NameError:
3751 pass # no unicode support
3752 label = Label(root, text=text)
3753 label.pack()
3754 test = Button(root, text="Click me!",
3755 command=lambda root=root: root.test.configure(
3756 text="[%s]" % root.test['text']))
3757 test.pack()
3758 root.test = test
3759 quit = Button(root, text="QUIT", command=root.destroy)
3760 quit.pack()
3761 # The following three commands are needed so the window pops
3762 # up on top on Windows...
3763 root.iconify()
3764 root.update()
3765 root.deiconify()
3766 root.mainloop()
3767
3768if __name__ == '__main__':
3769 _test()