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