1 """Wrapper functions for Tcl/Tk.
3 Tkinter provides classes which allow the display, positioning and
4 control of widgets. Toplevel widgets are Tk and Toplevel. Other
5 widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
6 Checkbutton, Scale, Listbox, Scrollbar, OptionMenu. Properties of the widgets are
7 specified with keyword arguments. Keyword arguments have the same
8 name as the corresponding resource under Tk.
10 Widgets are positioned with one of the geometry managers Place, Pack
11 or Grid. These managers can be called with methods place, pack, grid
12 available in every Widget.
14 Actions are bound to events by resources (e.g. keyword argument command) or
17 Example (Hello, World):
19 from Tkconstants import *
21 frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
22 frame.pack(fill=BOTH,expand=1)
23 label = Tkinter.Label(frame, text="Hello, World")
24 label.pack(fill=X, expand=1)
25 button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
26 button.pack(side=BOTTOM)
30 __version__
= "$Revision$"
33 if sys
.platform
== "win32":
34 import FixTk
# Attempt to configure Tcl/Tk without requiring PATH
35 import _tkinter
# If this fails your Python may not be configured for Tk
36 tkinter
= _tkinter
# b/w compat for export
37 TclError
= _tkinter
.TclError
39 from Tkconstants
import *
40 import string
; _string
= string
; del string
42 import MacOS
; _MacOS
= MacOS
; del MacOS
46 TkVersion
= _string
.atof(_tkinter
.TK_VERSION
)
47 TclVersion
= _string
.atof(_tkinter
.TCL_VERSION
)
49 READABLE
= _tkinter
.READABLE
50 WRITABLE
= _tkinter
.WRITABLE
51 EXCEPTION
= _tkinter
.EXCEPTION
53 # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
54 try: _tkinter
.createfilehandler
55 except AttributeError: _tkinter
.createfilehandler
= None
56 try: _tkinter
.deletefilehandler
57 except AttributeError: _tkinter
.deletefilehandler
= None
61 """Internal function."""
64 if type(item
) in (TupleType
, ListType
):
65 res
= res
+ _flatten(item
)
66 elif item
is not None:
70 try: _flatten
= _tkinter
._flatten
71 except AttributeError: pass
74 """Internal function."""
75 if type(cnfs
) is DictionaryType
:
77 elif type(cnfs
) in (NoneType
, StringType
):
81 for c
in _flatten(cnfs
):
84 except (AttributeError, TypeError), msg
:
85 print "_cnfmerge: fallback due to:", msg
86 for k
, v
in c
.items():
90 try: _cnfmerge
= _tkinter
._cnfmerge
91 except AttributeError: pass
94 """Container for the properties of an event.
96 Instances of this type are generated if one of the following events occurs:
98 KeyPress, KeyRelease - for keyboard events
99 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
100 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
101 Colormap, Gravity, Reparent, Property, Destroy, Activate,
102 Deactivate - for window events.
104 If a callback function for one of these events is registered
105 using bind, bind_all, bind_class, or tag_bind, the callback is
106 called with an Event as first argument. It will have the
107 following attributes (in braces are the event types for which
108 the attribute is valid):
110 serial - serial number of event
111 num - mouse button pressed (ButtonPress, ButtonRelease)
112 focus - whether the window has the focus (Enter, Leave)
113 height - height of the exposed window (Configure, Expose)
114 width - width of the exposed window (Configure, Expose)
115 keycode - keycode of the pressed key (KeyPress, KeyRelease)
116 state - state of the event as a number (ButtonPress, ButtonRelease,
117 Enter, KeyPress, KeyRelease,
119 state - state as a string (Visibility)
120 time - when the event occurred
121 x - x-position of the mouse
122 y - y-position of the mouse
123 x_root - x-position of the mouse on the screen
124 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
125 y_root - y-position of the mouse on the screen
126 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
127 char - pressed character (KeyPress, KeyRelease)
128 send_event - see X/Windows documentation
129 keysym - keysym of the the event as a string (KeyPress, KeyRelease)
130 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
131 type - type of the event as a number
132 widget - widget in which the event occurred
133 delta - delta of wheel movement (MouseWheel)
137 _support_default_root
= 1
141 """Inhibit setting of default root window.
143 Call this function to inhibit that the first instance of
144 Tk is used for windows without an explicit parent window.
146 global _support_default_root
147 _support_default_root
= 0
153 """Internal function."""
157 """Internal function. Calling it will throw the exception SystemExit."""
158 raise SystemExit, code
162 """Internal class. Base class to define value holders for e.g. buttons."""
164 def __init__(self
, master
=None):
165 """Construct a variable with an optional MASTER as master widget.
166 The variable is named PY_VAR_number in Tcl.
170 master
= _default_root
171 self
._master
= master
173 self
._name
= 'PY_VAR' + `_varnum`
174 _varnum
= _varnum
+ 1
175 self
.set(self
._default
)
177 """Unset the variable in Tcl."""
178 self
._tk
.globalunsetvar(self
._name
)
180 """Return the name of the variable in Tcl."""
182 def set(self
, value
):
183 """Set the variable to VALUE."""
184 return self
._tk
.globalsetvar(self
._name
, value
)
185 def trace_variable(self
, mode
, callback
):
186 """Define a trace callback for the variable.
188 MODE is one of "r", "w", "u" for read, write, undefine.
189 CALLBACK must be a function which is called when
190 the variable is read, written or undefined.
192 Return the name of the callback.
194 cbname
= self
._master
._register
(callback
)
195 self
._tk
.call("trace", "variable", self
._name
, mode
, cbname
)
197 trace
= trace_variable
198 def trace_vdelete(self
, mode
, cbname
):
199 """Delete the trace callback for a variable.
201 MODE is one of "r", "w", "u" for read, write, undefine.
202 CBNAME is the name of the callback returned from trace_variable or trace.
204 self
._tk
.call("trace", "vdelete", self
._name
, mode
, cbname
)
205 self
._master
.deletecommand(cbname
)
206 def trace_vinfo(self
):
207 """Return all trace callback information."""
208 return map(self
._tk
.split
, self
._tk
.splitlist(
209 self
._tk
.call("trace", "vinfo", self
._name
)))
211 class StringVar(Variable
):
212 """Value holder for strings variables."""
214 def __init__(self
, master
=None):
215 """Construct a string variable.
217 MASTER can be given as master widget."""
218 Variable
.__init
__(self
, master
)
221 """Return value of variable as string."""
222 return self
._tk
.globalgetvar(self
._name
)
224 class IntVar(Variable
):
225 """Value holder for integer variables."""
227 def __init__(self
, master
=None):
228 """Construct an integer variable.
230 MASTER can be given as master widget."""
231 Variable
.__init
__(self
, master
)
234 """Return the value of the variable as an integer."""
235 return getint(self
._tk
.globalgetvar(self
._name
))
237 class DoubleVar(Variable
):
238 """Value holder for float variables."""
240 def __init__(self
, master
=None):
241 """Construct a float variable.
243 MASTER can be given as a master widget."""
244 Variable
.__init
__(self
, master
)
247 """Return the value of the variable as a float."""
248 return getdouble(self
._tk
.globalgetvar(self
._name
))
250 class BooleanVar(Variable
):
251 """Value holder for boolean variables."""
253 def __init__(self
, master
=None):
254 """Construct a boolean variable.
256 MASTER can be given as a master widget."""
257 Variable
.__init
__(self
, master
)
260 """Return the value of the variable as 0 or 1."""
261 return self
._tk
.getboolean(self
._tk
.globalgetvar(self
._name
))
264 """Run the main loop of Tcl."""
265 _default_root
.tk
.mainloop(n
)
272 """Convert true and false to integer values 1 and 0."""
273 return _default_root
.tk
.getboolean(s
)
275 # Methods defined on both toplevel and interior widgets
279 Base class which defines methods common for interior widgets."""
284 """Internal function.
286 Delete all Tcl commands created for
287 this widget in the Tcl interpreter."""
288 if self
._tclCommands
is not None:
289 for name
in self
._tclCommands
:
290 #print '- Tkinter: deleted command', name
291 self
.tk
.deletecommand(name
)
292 self
._tclCommands
= None
293 def deletecommand(self
, name
):
294 """Internal function.
296 Delete the Tcl command provided in NAME."""
297 #print '- Tkinter: deleted command', name
298 self
.tk
.deletecommand(name
)
300 self
._tclCommands
.remove(name
)
303 def tk_strictMotif(self
, boolean
=None):
304 """Set Tcl internal variable, whether the look and feel
305 should adhere to Motif.
307 A parameter of 1 means adhere to Motif (e.g. no color
308 change if mouse passes over slider).
309 Returns the set value."""
310 return self
.tk
.getboolean(self
.tk
.call(
311 'set', 'tk_strictMotif', boolean
))
313 """Change the color scheme to light brown as used in Tk 3.6 and before."""
314 self
.tk
.call('tk_bisque')
315 def tk_setPalette(self
, *args
, **kw
):
316 """Set a new color scheme for all widget elements.
318 A single color as argument will cause that all colors of Tk
319 widget elements are derived from this.
320 Alternatively several keyword parameters and its associated
321 colors can be given. The following keywords are valid:
322 activeBackground, foreground, selectColor,
323 activeForeground, highlightBackground, selectBackground,
324 background, highlightColor, selectForeground,
325 disabledForeground, insertBackground, troughColor."""
326 self
.tk
.call(('tk_setPalette',)
327 + _flatten(args
) + _flatten(kw
.items()))
328 def tk_menuBar(self
, *args
):
329 """Do not use. Needed in Tk 3.6 and earlier."""
330 pass # obsolete since Tk 4.0
331 def wait_variable(self
, name
='PY_VAR'):
332 """Wait until the variable is modified.
334 A parameter of type IntVar, StringVar, DoubleVar or
335 BooleanVar must be given."""
336 self
.tk
.call('tkwait', 'variable', name
)
337 waitvar
= wait_variable
# XXX b/w compat
338 def wait_window(self
, window
=None):
339 """Wait until a WIDGET is destroyed.
341 If no parameter is given self is used."""
344 self
.tk
.call('tkwait', 'window', window
._w
)
345 def wait_visibility(self
, window
=None):
346 """Wait until the visibility of a WIDGET changes
349 If no parameter is given self is used."""
352 self
.tk
.call('tkwait', 'visibility', window
._w
)
353 def setvar(self
, name
='PY_VAR', value
='1'):
354 """Set Tcl variable NAME to VALUE."""
355 self
.tk
.setvar(name
, value
)
356 def getvar(self
, name
='PY_VAR'):
357 """Return value of Tcl variable NAME."""
358 return self
.tk
.getvar(name
)
361 def getboolean(self
, s
):
362 """Return 0 or 1 for Tcl boolean values true and false given as parameter."""
363 return self
.tk
.getboolean(s
)
365 """Direct input focus to this widget.
367 If the application currently does not have the focus
368 this widget will get the focus if the application gets
369 the focus through the window manager."""
370 self
.tk
.call('focus', self
._w
)
371 focus
= focus_set
# XXX b/w compat?
372 def focus_force(self
):
373 """Direct input focus to this widget even if the
374 application does not have the focus. Use with
376 self
.tk
.call('focus', '-force', self
._w
)
378 """Return the widget which has currently the focus in the
381 Use focus_displayof to allow working with several
382 displays. Return None if application does not have
384 name
= self
.tk
.call('focus')
385 if name
== 'none' or not name
: return None
386 return self
._nametowidget
(name
)
387 def focus_displayof(self
):
388 """Return the widget which has currently the focus on the
389 display where this widget is located.
391 Return None if the application does not have the focus."""
392 name
= self
.tk
.call('focus', '-displayof', self
._w
)
393 if name
== 'none' or not name
: return None
394 return self
._nametowidget
(name
)
395 def focus_lastfor(self
):
396 """Return the widget which would have the focus if top level
397 for this widget gets the focus from the window manager."""
398 name
= self
.tk
.call('focus', '-lastfor', self
._w
)
399 if name
== 'none' or not name
: return None
400 return self
._nametowidget
(name
)
401 def tk_focusFollowsMouse(self
):
402 """The widget under mouse will get automatically focus. Can not
403 be disabled easily."""
404 self
.tk
.call('tk_focusFollowsMouse')
405 def tk_focusNext(self
):
406 """Return the next widget in the focus order which follows
407 widget which has currently the focus.
409 The focus order first goes to the next child, then to
410 the children of the child recursively and then to the
411 next sibling which is higher in the stacking order. A
412 widget is omitted if it has the takefocus resource set
414 name
= self
.tk
.call('tk_focusNext', self
._w
)
415 if not name
: return None
416 return self
._nametowidget
(name
)
417 def tk_focusPrev(self
):
418 """Return previous widget in the focus order. See tk_focusNext for details."""
419 name
= self
.tk
.call('tk_focusPrev', self
._w
)
420 if not name
: return None
421 return self
._nametowidget
(name
)
422 def after(self
, ms
, func
=None, *args
):
423 """Call function once after given time.
425 MS specifies the time in milliseconds. FUNC gives the
426 function which shall be called. Additional parameters
427 are given as parameters to the function call. Return
428 identifier to cancel scheduling with after_cancel."""
430 # I'd rather use time.sleep(ms*0.001)
431 self
.tk
.call('after', ms
)
433 # XXX Disgusting hack to clean up after calling func
435 def callit(func
=func
, args
=args
, self
=self
, tmp
=tmp
):
440 self
.deletecommand(tmp
[0])
443 name
= self
._register
(callit
)
445 return self
.tk
.call('after', ms
, name
)
446 def after_idle(self
, func
, *args
):
447 """Call FUNC once if the Tcl main loop has no event to
450 Return an identifier to cancel the scheduling with
452 return apply(self
.after
, ('idle', func
) + args
)
453 def after_cancel(self
, id):
454 """Cancel scheduling of function identified with ID.
456 Identifier returned by after or after_idle must be
457 given as first parameter."""
458 self
.tk
.call('after', 'cancel', id)
459 def bell(self
, displayof
=0):
460 """Ring a display's bell."""
461 self
.tk
.call(('bell',) + self
._displayof
(displayof
))
462 # Clipboard handling:
463 def clipboard_clear(self
, **kw
):
464 """Clear the data in the Tk clipboard.
466 A widget specified for the optional displayof keyword
467 argument specifies the target display."""
468 if not kw
.has_key('displayof'): kw
['displayof'] = self
._w
469 self
.tk
.call(('clipboard', 'clear') + self
._options
(kw
))
470 def clipboard_append(self
, string
, **kw
):
471 """Append STRING to the Tk clipboard.
473 A widget specified at the optional displayof keyword
474 argument specifies the target display. The clipboard
475 can be retrieved with selection_get."""
476 if not kw
.has_key('displayof'): kw
['displayof'] = self
._w
477 self
.tk
.call(('clipboard', 'append') + self
._options
(kw
)
479 # XXX grab current w/o window argument
480 def grab_current(self
):
481 """Return widget which has currently the grab in this application
483 name
= self
.tk
.call('grab', 'current', self
._w
)
484 if not name
: return None
485 return self
._nametowidget
(name
)
486 def grab_release(self
):
487 """Release grab for this widget if currently set."""
488 self
.tk
.call('grab', 'release', self
._w
)
490 """Set grab for this widget.
492 A grab directs all events to this and descendant
493 widgets in the application."""
494 self
.tk
.call('grab', 'set', self
._w
)
495 def grab_set_global(self
):
496 """Set global grab for this widget.
498 A global grab directs all events to this and
499 descendant widgets on the display. Use with caution -
500 other applications do not get events anymore."""
501 self
.tk
.call('grab', 'set', '-global', self
._w
)
502 def grab_status(self
):
503 """Return None, "local" or "global" if this widget has
504 no, a local or a global grab."""
505 status
= self
.tk
.call('grab', 'status', self
._w
)
506 if status
== 'none': status
= None
508 def lower(self
, belowThis
=None):
509 """Lower this widget in the stacking order."""
510 self
.tk
.call('lower', self
._w
, belowThis
)
511 def option_add(self
, pattern
, value
, priority
= None):
512 """Set a VALUE (second parameter) for an option
513 PATTERN (first parameter).
515 An optional third parameter gives the numeric priority
517 self
.tk
.call('option', 'add', pattern
, value
, priority
)
518 def option_clear(self
):
519 """Clear the option database.
521 It will be reloaded if option_add is called."""
522 self
.tk
.call('option', 'clear')
523 def option_get(self
, name
, className
):
524 """Return the value for an option NAME for this widget
527 Values with higher priority override lower values."""
528 return self
.tk
.call('option', 'get', self
._w
, name
, className
)
529 def option_readfile(self
, fileName
, priority
= None):
530 """Read file FILENAME into the option database.
532 An optional second parameter gives the numeric
534 self
.tk
.call('option', 'readfile', fileName
, priority
)
535 def selection_clear(self
, **kw
):
536 """Clear the current X selection."""
537 if not kw
.has_key('displayof'): kw
['displayof'] = self
._w
538 self
.tk
.call(('selection', 'clear') + self
._options
(kw
))
539 def selection_get(self
, **kw
):
540 """Return the contents of the current X selection.
542 A keyword parameter selection specifies the name of
543 the selection and defaults to PRIMARY. A keyword
544 parameter displayof specifies a widget on the display
546 if not kw
.has_key('displayof'): kw
['displayof'] = self
._w
547 return self
.tk
.call(('selection', 'get') + self
._options
(kw
))
548 def selection_handle(self
, command
, **kw
):
549 """Specify a function COMMAND to call if the X
550 selection owned by this widget is queried by another
553 This function must return the contents of the
554 selection. The function will be called with the
555 arguments OFFSET and LENGTH which allows the chunking
556 of very long selections. The following keyword
557 parameters can be provided:
558 selection - name of the selection (default PRIMARY),
559 type - type of the selection (e.g. STRING, FILE_NAME)."""
560 name
= self
._register
(command
)
561 self
.tk
.call(('selection', 'handle') + self
._options
(kw
)
563 def selection_own(self
, **kw
):
564 """Become owner of X selection.
566 A keyword parameter selection specifies the name of
567 the selection (default PRIMARY)."""
568 self
.tk
.call(('selection', 'own') +
569 self
._options
(kw
) + (self
._w
,))
570 def selection_own_get(self
, **kw
):
571 """Return owner of X selection.
573 The following keyword parameter can
575 selection - name of the selection (default PRIMARY),
576 type - type of the selection (e.g. STRING, FILE_NAME)."""
577 if not kw
.has_key('displayof'): kw
['displayof'] = self
._w
578 name
= self
.tk
.call(('selection', 'own') + self
._options
(kw
))
579 if not name
: return None
580 return self
._nametowidget
(name
)
581 def send(self
, interp
, cmd
, *args
):
582 """Send Tcl command CMD to different interpreter INTERP to be executed."""
583 return self
.tk
.call(('send', interp
, cmd
) + args
)
584 def lower(self
, belowThis
=None):
585 """Lower this widget in the stacking order."""
586 self
.tk
.call('lower', self
._w
, belowThis
)
587 def tkraise(self
, aboveThis
=None):
588 """Raise this widget in the stacking order."""
589 self
.tk
.call('raise', self
._w
, aboveThis
)
591 def colormodel(self
, value
=None):
592 """Useless. Not implemented in Tk."""
593 return self
.tk
.call('tk', 'colormodel', self
._w
, value
)
594 def winfo_atom(self
, name
, displayof
=0):
595 """Return integer which represents atom NAME."""
596 args
= ('winfo', 'atom') + self
._displayof
(displayof
) + (name
,)
597 return getint(self
.tk
.call(args
))
598 def winfo_atomname(self
, id, displayof
=0):
599 """Return name of atom with identifier ID."""
600 args
= ('winfo', 'atomname') \
601 + self
._displayof
(displayof
) + (id,)
602 return self
.tk
.call(args
)
603 def winfo_cells(self
):
604 """Return number of cells in the colormap for this widget."""
606 self
.tk
.call('winfo', 'cells', self
._w
))
607 def winfo_children(self
):
608 """Return a list of all widgets which are children of this widget."""
609 return map(self
._nametowidget
,
610 self
.tk
.splitlist(self
.tk
.call(
611 'winfo', 'children', self
._w
)))
612 def winfo_class(self
):
613 """Return window class name of this widget."""
614 return self
.tk
.call('winfo', 'class', self
._w
)
615 def winfo_colormapfull(self
):
616 """Return true if at the last color request the colormap was full."""
617 return self
.tk
.getboolean(
618 self
.tk
.call('winfo', 'colormapfull', self
._w
))
619 def winfo_containing(self
, rootX
, rootY
, displayof
=0):
620 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
621 args
= ('winfo', 'containing') \
622 + self
._displayof
(displayof
) + (rootX
, rootY
)
623 name
= self
.tk
.call(args
)
624 if not name
: return None
625 return self
._nametowidget
(name
)
626 def winfo_depth(self
):
627 """Return the number of bits per pixel."""
628 return getint(self
.tk
.call('winfo', 'depth', self
._w
))
629 def winfo_exists(self
):
630 """Return true if this widget exists."""
632 self
.tk
.call('winfo', 'exists', self
._w
))
633 def winfo_fpixels(self
, number
):
634 """Return the number of pixels for the given distance NUMBER
635 (e.g. "3c") as float."""
636 return getdouble(self
.tk
.call(
637 'winfo', 'fpixels', self
._w
, number
))
638 def winfo_geometry(self
):
639 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
640 return self
.tk
.call('winfo', 'geometry', self
._w
)
641 def winfo_height(self
):
642 """Return height of this widget."""
644 self
.tk
.call('winfo', 'height', self
._w
))
646 """Return identifier ID for this widget."""
647 return self
.tk
.getint(
648 self
.tk
.call('winfo', 'id', self
._w
))
649 def winfo_interps(self
, displayof
=0):
650 """Return the name of all Tcl interpreters for this display."""
651 args
= ('winfo', 'interps') + self
._displayof
(displayof
)
652 return self
.tk
.splitlist(self
.tk
.call(args
))
653 def winfo_ismapped(self
):
654 """Return true if this widget is mapped."""
656 self
.tk
.call('winfo', 'ismapped', self
._w
))
657 def winfo_manager(self
):
658 """Return the window mananger name for this widget."""
659 return self
.tk
.call('winfo', 'manager', self
._w
)
660 def winfo_name(self
):
661 """Return the name of this widget."""
662 return self
.tk
.call('winfo', 'name', self
._w
)
663 def winfo_parent(self
):
664 """Return the name of the parent of this widget."""
665 return self
.tk
.call('winfo', 'parent', self
._w
)
666 def winfo_pathname(self
, id, displayof
=0):
667 """Return the pathname of the widget given by ID."""
668 args
= ('winfo', 'pathname') \
669 + self
._displayof
(displayof
) + (id,)
670 return self
.tk
.call(args
)
671 def winfo_pixels(self
, number
):
672 """Rounded integer value of winfo_fpixels."""
674 self
.tk
.call('winfo', 'pixels', self
._w
, number
))
675 def winfo_pointerx(self
):
676 """Return the x coordinate of the pointer on the root window."""
678 self
.tk
.call('winfo', 'pointerx', self
._w
))
679 def winfo_pointerxy(self
):
680 """Return a tuple of x and y coordinates of the pointer on the root window."""
681 return self
._getints
(
682 self
.tk
.call('winfo', 'pointerxy', self
._w
))
683 def winfo_pointery(self
):
684 """Return the y coordinate of the pointer on the root window."""
686 self
.tk
.call('winfo', 'pointery', self
._w
))
687 def winfo_reqheight(self
):
688 """Return requested height of this widget."""
690 self
.tk
.call('winfo', 'reqheight', self
._w
))
691 def winfo_reqwidth(self
):
692 """Return requested width of this widget."""
694 self
.tk
.call('winfo', 'reqwidth', self
._w
))
695 def winfo_rgb(self
, color
):
696 """Return tuple of decimal values for red, green, blue for
697 COLOR in this widget."""
698 return self
._getints
(
699 self
.tk
.call('winfo', 'rgb', self
._w
, color
))
700 def winfo_rootx(self
):
701 """Return x coordinate of upper left corner of this widget on the
704 self
.tk
.call('winfo', 'rootx', self
._w
))
705 def winfo_rooty(self
):
706 """Return y coordinate of upper left corner of this widget on the
709 self
.tk
.call('winfo', 'rooty', self
._w
))
710 def winfo_screen(self
):
711 """Return the screen name of this widget."""
712 return self
.tk
.call('winfo', 'screen', self
._w
)
713 def winfo_screencells(self
):
714 """Return the number of the cells in the colormap of the screen
717 self
.tk
.call('winfo', 'screencells', self
._w
))
718 def winfo_screendepth(self
):
719 """Return the number of bits per pixel of the root window of the
720 screen of this widget."""
722 self
.tk
.call('winfo', 'screendepth', self
._w
))
723 def winfo_screenheight(self
):
724 """Return the number of pixels of the height of the screen of this widget
727 self
.tk
.call('winfo', 'screenheight', self
._w
))
728 def winfo_screenmmheight(self
):
729 """Return the number of pixels of the height of the screen of
730 this widget in mm."""
732 self
.tk
.call('winfo', 'screenmmheight', self
._w
))
733 def winfo_screenmmwidth(self
):
734 """Return the number of pixels of the width of the screen of
735 this widget in mm."""
737 self
.tk
.call('winfo', 'screenmmwidth', self
._w
))
738 def winfo_screenvisual(self
):
739 """Return one of the strings directcolor, grayscale, pseudocolor,
740 staticcolor, staticgray, or truecolor for the default
741 colormodel of this screen."""
742 return self
.tk
.call('winfo', 'screenvisual', self
._w
)
743 def winfo_screenwidth(self
):
744 """Return the number of pixels of the width of the screen of
745 this widget in pixel."""
747 self
.tk
.call('winfo', 'screenwidth', self
._w
))
748 def winfo_server(self
):
749 """Return information of the X-Server of the screen of this widget in
750 the form "XmajorRminor vendor vendorVersion"."""
751 return self
.tk
.call('winfo', 'server', self
._w
)
752 def winfo_toplevel(self
):
753 """Return the toplevel widget of this widget."""
754 return self
._nametowidget
(self
.tk
.call(
755 'winfo', 'toplevel', self
._w
))
756 def winfo_viewable(self
):
757 """Return true if the widget and all its higher ancestors are mapped."""
759 self
.tk
.call('winfo', 'viewable', self
._w
))
760 def winfo_visual(self
):
761 """Return one of the strings directcolor, grayscale, pseudocolor,
762 staticcolor, staticgray, or truecolor for the
763 colormodel of this widget."""
764 return self
.tk
.call('winfo', 'visual', self
._w
)
765 def winfo_visualid(self
):
766 """Return the X identifier for the visual for this widget."""
767 return self
.tk
.call('winfo', 'visualid', self
._w
)
768 def winfo_visualsavailable(self
, includeids
=0):
769 """Return a list of all visuals available for the screen
772 Each item in the list consists of a visual name (see winfo_visual), a
773 depth and if INCLUDEIDS=1 is given also the X identifier."""
774 data
= self
.tk
.split(
775 self
.tk
.call('winfo', 'visualsavailable', self
._w
,
776 includeids
and 'includeids' or None))
777 if type(data
) is StringType
:
778 data
= [self
.tk
.split(data
)]
779 return map(self
.__winfo
_parseitem
, data
)
780 def __winfo_parseitem(self
, t
):
781 """Internal function."""
782 return t
[:1] + tuple(map(self
.__winfo
_getint
, t
[1:]))
783 def __winfo_getint(self
, x
):
784 """Internal function."""
785 return _string
.atoi(x
, 0)
786 def winfo_vrootheight(self
):
787 """Return the height of the virtual root window associated with this
788 widget in pixels. If there is no virtual root window return the
789 height of the screen."""
791 self
.tk
.call('winfo', 'vrootheight', self
._w
))
792 def winfo_vrootwidth(self
):
793 """Return the width of the virtual root window associated with this
794 widget in pixel. If there is no virtual root window return the
795 width of the screen."""
797 self
.tk
.call('winfo', 'vrootwidth', self
._w
))
798 def winfo_vrootx(self
):
799 """Return the x offset of the virtual root relative to the root
800 window of the screen of this widget."""
802 self
.tk
.call('winfo', 'vrootx', self
._w
))
803 def winfo_vrooty(self
):
804 """Return the y offset of the virtual root relative to the root
805 window of the screen of this widget."""
807 self
.tk
.call('winfo', 'vrooty', self
._w
))
808 def winfo_width(self
):
809 """Return the width of this widget."""
811 self
.tk
.call('winfo', 'width', self
._w
))
813 """Return the x coordinate of the upper left corner of this widget
816 self
.tk
.call('winfo', 'x', self
._w
))
818 """Return the y coordinate of the upper left corner of this widget
821 self
.tk
.call('winfo', 'y', self
._w
))
823 """Enter event loop until all pending events have been processed by Tcl."""
824 self
.tk
.call('update')
825 def update_idletasks(self
):
826 """Enter event loop until all idle callbacks have been called. This
827 will update the display of windows but not process events caused by
829 self
.tk
.call('update', 'idletasks')
830 def bindtags(self
, tagList
=None):
831 """Set or get the list of bindtags for this widget.
833 With no argument return the list of all bindtags associated with
834 this widget. With a list of strings as argument the bindtags are
835 set to this list. The bindtags determine in which order events are
836 processed (see bind)."""
838 return self
.tk
.splitlist(
839 self
.tk
.call('bindtags', self
._w
))
841 self
.tk
.call('bindtags', self
._w
, tagList
)
842 def _bind(self
, what
, sequence
, func
, add
, needcleanup
=1):
843 """Internal function."""
844 if type(func
) is StringType
:
845 self
.tk
.call(what
+ (sequence
, func
))
847 funcid
= self
._register
(func
, self
._substitute
,
849 cmd
= ('%sif {"[%s %s]" == "break"} break\n'
853 _string
.join(self
._subst
_format
)))
854 self
.tk
.call(what
+ (sequence
, cmd
))
857 return self
.tk
.call(what
+ (sequence
,))
859 return self
.tk
.splitlist(self
.tk
.call(what
))
860 def bind(self
, sequence
=None, func
=None, add
=None):
861 """Bind to this widget at event SEQUENCE a call to function FUNC.
863 SEQUENCE is a string of concatenated event
864 patterns. An event pattern is of the form
865 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
866 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
867 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
868 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
869 Mod1, M1. TYPE is one of Activate, Enter, Map,
870 ButtonPress, Button, Expose, Motion, ButtonRelease
871 FocusIn, MouseWheel, Circulate, FocusOut, Property,
872 Colormap, Gravity Reparent, Configure, KeyPress, Key,
873 Unmap, Deactivate, KeyRelease Visibility, Destroy,
874 Leave and DETAIL is the button number for ButtonPress,
875 ButtonRelease and DETAIL is the Keysym for KeyPress and
876 KeyRelease. Examples are
877 <Control-Button-1> for pressing Control and mouse button 1 or
878 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
879 An event pattern can also be a virtual event of the form
880 <<AString>> where AString can be arbitrary. This
881 event can be generated by event_generate.
882 If events are concatenated they must appear shortly
885 FUNC will be called if the event sequence occurs with an
886 instance of Event as argument. If the return value of FUNC is
887 "break" no further bound function is invoked.
889 An additional boolean parameter ADD specifies whether FUNC will
890 be called additionally to the other bound function or whether
891 it will replace the previous function.
893 Bind will return an identifier to allow deletion of the bound function with
894 unbind without memory leak.
896 If FUNC or SEQUENCE is omitted the bound function or list
897 of bound events are returned."""
899 return self
._bind
(('bind', self
._w
), sequence
, func
, add
)
900 def unbind(self
, sequence
, funcid
=None):
901 """Unbind for this widget for event SEQUENCE the
902 function identified with FUNCID."""
903 self
.tk
.call('bind', self
._w
, sequence
, '')
905 self
.deletecommand(funcid
)
906 def bind_all(self
, sequence
=None, func
=None, add
=None):
907 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
908 An additional boolean parameter ADD specifies whether FUNC will
909 be called additionally to the other bound function or whether
910 it will replace the previous function. See bind for the return value."""
911 return self
._bind
(('bind', 'all'), sequence
, func
, add
, 0)
912 def unbind_all(self
, sequence
):
913 """Unbind for all widgets for event SEQUENCE all functions."""
914 self
.tk
.call('bind', 'all' , sequence
, '')
915 def bind_class(self
, className
, sequence
=None, func
=None, add
=None):
917 """Bind to widgets with bindtag CLASSNAME at event
918 SEQUENCE a call of function FUNC. An additional
919 boolean parameter ADD specifies whether FUNC will be
920 called additionally to the other bound function or
921 whether it will replace the previous function. See bind for
924 return self
._bind
(('bind', className
), sequence
, func
, add
, 0)
925 def unbind_class(self
, className
, sequence
):
926 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
928 self
.tk
.call('bind', className
, sequence
, '')
929 def mainloop(self
, n
=0):
930 """Call the mainloop of Tk."""
933 """Quit the Tcl interpreter. All widgets will be destroyed."""
935 def _getints(self
, string
):
936 """Internal function."""
938 return tuple(map(getint
, self
.tk
.splitlist(string
)))
939 def _getdoubles(self
, string
):
940 """Internal function."""
942 return tuple(map(getdouble
, self
.tk
.splitlist(string
)))
943 def _getboolean(self
, string
):
944 """Internal function."""
946 return self
.tk
.getboolean(string
)
947 def _displayof(self
, displayof
):
948 """Internal function."""
950 return ('-displayof', displayof
)
951 if displayof
is None:
952 return ('-displayof', self
._w
)
954 def _options(self
, cnf
, kw
= None):
955 """Internal function."""
957 cnf
= _cnfmerge((cnf
, kw
))
961 for k
, v
in cnf
.items():
963 if k
[-1] == '_': k
= k
[:-1]
965 v
= self
._register
(v
)
966 res
= res
+ ('-'+k
, v
)
968 def nametowidget(self
, name
):
969 """Return the Tkinter instance of a widget identified by
970 its Tcl name NAME."""
979 name
, tail
= name
[:i
], name
[i
+1:]
985 _nametowidget
= nametowidget
986 def _register(self
, func
, subst
=None, needcleanup
=1):
987 """Return a newly created Tcl function. If this
988 function is called, the Python function FUNC will
989 be executed. An optional function SUBST can
990 be given which will be executed before FUNC."""
991 f
= CallWrapper(func
, subst
, self
).__call
__
995 except AttributeError:
998 name
= name
+ func
.__name
__
999 except AttributeError:
1001 self
.tk
.createcommand(name
, f
)
1003 if self
._tclCommands
is None:
1004 self
._tclCommands
= []
1005 self
._tclCommands
.append(name
)
1006 #print '+ Tkinter created command', name
1008 register
= _register
1010 """Internal function."""
1012 while w
.master
: w
= w
.master
1014 _subst_format
= ('%#', '%b', '%f', '%h', '%k',
1015 '%s', '%t', '%w', '%x', '%y',
1016 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1017 def _substitute(self
, *args
):
1018 """Internal function."""
1019 if len(args
) != len(self
._subst
_format
): return args
1020 getboolean
= self
.tk
.getboolean
1022 nsign
, b
, f
, h
, k
, s
, t
, w
, x
, y
, A
, E
, K
, N
, W
, T
, X
, Y
, D
= args
1023 # Missing: (a, c, d, m, o, v, B, R)
1025 e
.serial
= getint(nsign
)
1027 try: e
.focus
= getboolean(f
)
1028 except TclError
: pass
1029 e
.height
= getint(h
)
1030 e
.keycode
= getint(k
)
1031 # For Visibility events, event state is a string and
1042 try: e
.send_event
= getboolean(E
)
1043 except TclError
: pass
1045 e
.keysym_num
= getint(N
)
1048 e
.widget
= self
._nametowidget
(W
)
1051 e
.x_root
= getint(X
)
1052 e
.y_root
= getint(Y
)
1058 def _report_exception(self
):
1059 """Internal function."""
1061 exc
, val
, tb
= sys
.exc_type
, sys
.exc_value
, sys
.exc_traceback
1063 root
.report_callback_exception(exc
, val
, tb
)
1064 # These used to be defined in Widget:
1065 def configure(self
, cnf
=None, **kw
):
1066 """Configure resources of a widget.
1068 The values for resources are specified as keyword
1069 arguments. To get an overview about
1070 the allowed keyword arguments call the method keys.
1072 # XXX ought to generalize this so tag_config etc. can use it
1074 cnf
= _cnfmerge((cnf
, kw
))
1076 cnf
= _cnfmerge(cnf
)
1079 for x
in self
.tk
.split(
1080 self
.tk
.call(self
._w
, 'configure')):
1081 cnf
[x
[0][1:]] = (x
[0][1:],) + x
[1:]
1083 if type(cnf
) is StringType
:
1084 x
= self
.tk
.split(self
.tk
.call(
1085 self
._w
, 'configure', '-'+cnf
))
1086 return (x
[0][1:],) + x
[1:]
1087 self
.tk
.call((self
._w
, 'configure')
1088 + self
._options
(cnf
))
1090 def cget(self
, key
):
1091 """Return the resource value for a KEY given as string."""
1092 return self
.tk
.call(self
._w
, 'cget', '-' + key
)
1094 def __setitem__(self
, key
, value
):
1095 self
.configure({key
: value
})
1097 """Return a list of all resource names of this widget."""
1098 return map(lambda x
: x
[0][1:],
1099 self
.tk
.split(self
.tk
.call(self
._w
, 'configure')))
1101 """Return the window path name of this widget."""
1103 # Pack methods that apply to the master
1104 _noarg_
= ['_noarg_']
1105 def pack_propagate(self
, flag
=_noarg_
):
1106 """Set or get the status for propagation of geometry information.
1108 A boolean argument specifies whether the geometry information
1109 of the slaves will determine the size of this widget. If no argument
1110 is given the current setting will be returned.
1112 if flag
is Misc
._noarg
_:
1113 return self
._getboolean
(self
.tk
.call(
1114 'pack', 'propagate', self
._w
))
1116 self
.tk
.call('pack', 'propagate', self
._w
, flag
)
1117 propagate
= pack_propagate
1118 def pack_slaves(self
):
1119 """Return a list of all slaves of this widget
1120 in its packing order."""
1121 return map(self
._nametowidget
,
1123 self
.tk
.call('pack', 'slaves', self
._w
)))
1124 slaves
= pack_slaves
1125 # Place method that applies to the master
1126 def place_slaves(self
):
1127 """Return a list of all slaves of this widget
1128 in its packing order."""
1129 return map(self
._nametowidget
,
1132 'place', 'slaves', self
._w
)))
1133 # Grid methods that apply to the master
1134 def grid_bbox(self
, column
=None, row
=None, col2
=None, row2
=None):
1135 """Return a tuple of integer coordinates for the bounding
1136 box of this widget controlled by the geometry manager grid.
1138 If COLUMN, ROW is given the bounding box applies from
1139 the cell with row and column 0 to the specified
1140 cell. If COL2 and ROW2 are given the bounding box
1141 starts at that cell.
1143 The returned integers specify the offset of the upper left
1144 corner in the master widget and the width and height.
1146 args
= ('grid', 'bbox', self
._w
)
1147 if column
is not None and row
is not None:
1148 args
= args
+ (column
, row
)
1149 if col2
is not None and row2
is not None:
1150 args
= args
+ (col2
, row2
)
1151 return self
._getints
(apply(self
.tk
.call
, args
)) or None
1154 def _grid_configure(self
, command
, index
, cnf
, kw
):
1155 """Internal function."""
1156 if type(cnf
) is StringType
and not kw
:
1163 options
= self
._options
(cnf
, kw
)
1165 res
= self
.tk
.call('grid',
1166 command
, self
._w
, index
)
1167 words
= self
.tk
.splitlist(res
)
1169 for i
in range(0, len(words
), 2):
1175 value
= getdouble(value
)
1177 value
= getint(value
)
1181 ('grid', command
, self
._w
, index
)
1183 if len(options
) == 1:
1184 if not res
: return None
1185 # In Tk 7.5, -width can be a float
1186 if '.' in res
: return getdouble(res
)
1188 def grid_columnconfigure(self
, index
, cnf
={}, **kw
):
1189 """Configure column INDEX of a grid.
1191 Valid resources are minsize (minimum size of the column),
1192 weight (how much does additional space propagate to this column)
1193 and pad (how much space to let additionally)."""
1194 return self
._grid
_configure
('columnconfigure', index
, cnf
, kw
)
1195 columnconfigure
= grid_columnconfigure
1196 def grid_propagate(self
, flag
=_noarg_
):
1197 """Set or get the status for propagation of geometry information.
1199 A boolean argument specifies whether the geometry information
1200 of the slaves will determine the size of this widget. If no argument
1201 is given, the current setting will be returned.
1203 if flag
is Misc
._noarg
_:
1204 return self
._getboolean
(self
.tk
.call(
1205 'grid', 'propagate', self
._w
))
1207 self
.tk
.call('grid', 'propagate', self
._w
, flag
)
1208 def grid_rowconfigure(self
, index
, cnf
={}, **kw
):
1209 """Configure row INDEX of a grid.
1211 Valid resources are minsize (minimum size of the row),
1212 weight (how much does additional space propagate to this row)
1213 and pad (how much space to let additionally)."""
1214 return self
._grid
_configure
('rowconfigure', index
, cnf
, kw
)
1215 rowconfigure
= grid_rowconfigure
1216 def grid_size(self
):
1217 """Return a tuple of the number of column and rows in the grid."""
1218 return self
._getints
(
1219 self
.tk
.call('grid', 'size', self
._w
)) or None
1221 def grid_slaves(self
, row
=None, column
=None):
1222 """Return a list of all slaves of this widget
1223 in its packing order."""
1226 args
= args
+ ('-row', row
)
1227 if column
is not None:
1228 args
= args
+ ('-column', column
)
1229 return map(self
._nametowidget
,
1230 self
.tk
.splitlist(self
.tk
.call(
1231 ('grid', 'slaves', self
._w
) + args
)))
1233 # Support for the "event" command, new in Tk 4.2.
1236 def event_add(self
, virtual
, *sequences
):
1237 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1238 to an event SEQUENCE such that the virtual event is triggered
1239 whenever SEQUENCE occurs."""
1240 args
= ('event', 'add', virtual
) + sequences
1243 def event_delete(self
, virtual
, *sequences
):
1244 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1245 args
= ('event', 'delete', virtual
) + sequences
1248 def event_generate(self
, sequence
, **kw
):
1249 """Generate an event SEQUENCE. Additional
1250 keyword arguments specify parameter of the event
1251 (e.g. x, y, rootx, rooty)."""
1252 args
= ('event', 'generate', self
._w
, sequence
)
1253 for k
, v
in kw
.items():
1254 args
= args
+ ('-%s' % k
, str(v
))
1257 def event_info(self
, virtual
=None):
1258 """Return a list of all virtual events or the information
1259 about the SEQUENCE bound to the virtual event VIRTUAL."""
1260 return self
.tk
.splitlist(
1261 self
.tk
.call('event', 'info', virtual
))
1263 # Image related commands
1265 def image_names(self
):
1266 """Return a list of all existing image names."""
1267 return self
.tk
.call('image', 'names')
1269 def image_types(self
):
1270 """Return a list of all available image types (e.g. phote bitmap)."""
1271 return self
.tk
.call('image', 'types')
1275 """Internal class. Stores function to call when some user
1276 defined Tcl function is called e.g. after an event occurred."""
1277 def __init__(self
, func
, subst
, widget
):
1278 """Store FUNC, SUBST and WIDGET as members."""
1281 self
.widget
= widget
1282 def __call__(self
, *args
):
1283 """Apply first function SUBST to arguments, than FUNC."""
1286 args
= apply(self
.subst
, args
)
1287 return apply(self
.func
, args
)
1288 except SystemExit, msg
:
1289 raise SystemExit, msg
1291 self
.widget
._report
_exception
()
1295 """Provides functions for the communication with the window manager."""
1297 minNumer
=None, minDenom
=None,
1298 maxNumer
=None, maxDenom
=None):
1299 """Instruct the window manager to set the aspect ratio (width/height)
1300 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1301 of the actual values if no argument is given."""
1302 return self
._getints
(
1303 self
.tk
.call('wm', 'aspect', self
._w
,
1305 maxNumer
, maxDenom
))
1307 def wm_client(self
, name
=None):
1308 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1310 return self
.tk
.call('wm', 'client', self
._w
, name
)
1312 def wm_colormapwindows(self
, *wlist
):
1313 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1314 of this widget. This list contains windows whose colormaps differ from their
1315 parents. Return current list of widgets if WLIST is empty."""
1317 wlist
= (wlist
,) # Tk needs a list of windows here
1318 args
= ('wm', 'colormapwindows', self
._w
) + wlist
1319 return map(self
._nametowidget
, self
.tk
.call(args
))
1320 colormapwindows
= wm_colormapwindows
1321 def wm_command(self
, value
=None):
1322 """Store VALUE in WM_COMMAND property. It is the command
1323 which shall be used to invoke the application. Return current
1324 command if VALUE is None."""
1325 return self
.tk
.call('wm', 'command', self
._w
, value
)
1326 command
= wm_command
1327 def wm_deiconify(self
):
1328 """Deiconify this widget. If it was never mapped it will not be mapped.
1329 On Windows it will raise this widget and give it the focus."""
1330 return self
.tk
.call('wm', 'deiconify', self
._w
)
1331 deiconify
= wm_deiconify
1332 def wm_focusmodel(self
, model
=None):
1333 """Set focus model to MODEL. "active" means that this widget will claim
1334 the focus itself, "passive" means that the window manager shall give
1335 the focus. Return current focus model if MODEL is None."""
1336 return self
.tk
.call('wm', 'focusmodel', self
._w
, model
)
1337 focusmodel
= wm_focusmodel
1339 """Return identifier for decorative frame of this widget if present."""
1340 return self
.tk
.call('wm', 'frame', self
._w
)
1342 def wm_geometry(self
, newGeometry
=None):
1343 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1344 current value if None is given."""
1345 return self
.tk
.call('wm', 'geometry', self
._w
, newGeometry
)
1346 geometry
= wm_geometry
1348 baseWidth
=None, baseHeight
=None,
1349 widthInc
=None, heightInc
=None):
1350 """Instruct the window manager that this widget shall only be
1351 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1352 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1353 number of grid units requested in Tk_GeometryRequest."""
1354 return self
._getints
(self
.tk
.call(
1355 'wm', 'grid', self
._w
,
1356 baseWidth
, baseHeight
, widthInc
, heightInc
))
1358 def wm_group(self
, pathName
=None):
1359 """Set the group leader widgets for related widgets to PATHNAME. Return
1360 the group leader of this widget if None is given."""
1361 return self
.tk
.call('wm', 'group', self
._w
, pathName
)
1363 def wm_iconbitmap(self
, bitmap
=None):
1364 """Set bitmap for the iconified widget to BITMAP. Return
1365 the bitmap if None is given."""
1366 return self
.tk
.call('wm', 'iconbitmap', self
._w
, bitmap
)
1367 iconbitmap
= wm_iconbitmap
1368 def wm_iconify(self
):
1369 """Display widget as icon."""
1370 return self
.tk
.call('wm', 'iconify', self
._w
)
1371 iconify
= wm_iconify
1372 def wm_iconmask(self
, bitmap
=None):
1373 """Set mask for the icon bitmap of this widget. Return the
1374 mask if None is given."""
1375 return self
.tk
.call('wm', 'iconmask', self
._w
, bitmap
)
1376 iconmask
= wm_iconmask
1377 def wm_iconname(self
, newName
=None):
1378 """Set the name of the icon for this widget. Return the name if
1380 return self
.tk
.call('wm', 'iconname', self
._w
, newName
)
1381 iconname
= wm_iconname
1382 def wm_iconposition(self
, x
=None, y
=None):
1383 """Set the position of the icon of this widget to X and Y. Return
1384 a tuple of the current values of X and X if None is given."""
1385 return self
._getints
(self
.tk
.call(
1386 'wm', 'iconposition', self
._w
, x
, y
))
1387 iconposition
= wm_iconposition
1388 def wm_iconwindow(self
, pathName
=None):
1389 """Set widget PATHNAME to be displayed instead of icon. Return the current
1390 value if None is given."""
1391 return self
.tk
.call('wm', 'iconwindow', self
._w
, pathName
)
1392 iconwindow
= wm_iconwindow
1393 def wm_maxsize(self
, width
=None, height
=None):
1394 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1395 the values are given in grid units. Return the current values if None
1397 return self
._getints
(self
.tk
.call(
1398 'wm', 'maxsize', self
._w
, width
, height
))
1399 maxsize
= wm_maxsize
1400 def wm_minsize(self
, width
=None, height
=None):
1401 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1402 the values are given in grid units. Return the current values if None
1404 return self
._getints
(self
.tk
.call(
1405 'wm', 'minsize', self
._w
, width
, height
))
1406 minsize
= wm_minsize
1407 def wm_overrideredirect(self
, boolean
=None):
1408 """Instruct the window manager to ignore this widget
1409 if BOOLEAN is given with 1. Return the current value if None
1411 return self
._getboolean
(self
.tk
.call(
1412 'wm', 'overrideredirect', self
._w
, boolean
))
1413 overrideredirect
= wm_overrideredirect
1414 def wm_positionfrom(self
, who
=None):
1415 """Instruct the window manager that the position of this widget shall
1416 be defined by the user if WHO is "user", and by its own policy if WHO is
1418 return self
.tk
.call('wm', 'positionfrom', self
._w
, who
)
1419 positionfrom
= wm_positionfrom
1420 def wm_protocol(self
, name
=None, func
=None):
1421 """Bind function FUNC to command NAME for this widget.
1422 Return the function bound to NAME if None is given. NAME could be
1423 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1425 command
= self
._register
(func
)
1428 return self
.tk
.call(
1429 'wm', 'protocol', self
._w
, name
, command
)
1430 protocol
= wm_protocol
1431 def wm_resizable(self
, width
=None, height
=None):
1432 """Instruct the window manager whether this width can be resized
1433 in WIDTH or HEIGHT. Both values are boolean values."""
1434 return self
.tk
.call('wm', 'resizable', self
._w
, width
, height
)
1435 resizable
= wm_resizable
1436 def wm_sizefrom(self
, who
=None):
1437 """Instruct the window manager that the size of this widget shall
1438 be defined by the user if WHO is "user", and by its own policy if WHO is
1440 return self
.tk
.call('wm', 'sizefrom', self
._w
, who
)
1441 sizefrom
= wm_sizefrom
1442 def wm_state(self
, newstate
=None):
1443 """Query or set the state of this widget as one of normal, icon,
1444 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1445 return self
.tk
.call('wm', 'state', self
._w
, newstate
)
1447 def wm_title(self
, string
=None):
1448 """Set the title of this widget."""
1449 return self
.tk
.call('wm', 'title', self
._w
, string
)
1451 def wm_transient(self
, master
=None):
1452 """Instruct the window manager that this widget is transient
1453 with regard to widget MASTER."""
1454 return self
.tk
.call('wm', 'transient', self
._w
, master
)
1455 transient
= wm_transient
1456 def wm_withdraw(self
):
1457 """Withdraw this widget from the screen such that it is unmapped
1458 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1459 return self
.tk
.call('wm', 'withdraw', self
._w
)
1460 withdraw
= wm_withdraw
1464 """Toplevel widget of Tk which represents mostly the main window
1465 of an appliation. It has an associated Tcl interpreter."""
1467 def __init__(self
, screenName
=None, baseName
=None, className
='Tk'):
1468 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1469 be created. BASENAME will be used for the identification of the profile file (see
1471 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1472 is the name of the widget class."""
1473 global _default_root
1476 if baseName
is None:
1478 baseName
= os
.path
.basename(sys
.argv
[0])
1479 baseName
, ext
= os
.path
.splitext(baseName
)
1480 if ext
not in ('.py', '.pyc', '.pyo'):
1481 baseName
= baseName
+ ext
1482 self
.tk
= _tkinter
.create(screenName
, baseName
, className
)
1484 # Disable event scanning except for Command-Period
1485 _MacOS
.SchedParams(1, 0)
1486 # Work around nasty MacTk bug
1487 # XXX Is this one still needed?
1489 # Version sanity checks
1490 tk_version
= self
.tk
.getvar('tk_version')
1491 if tk_version
!= _tkinter
.TK_VERSION
:
1492 raise RuntimeError, \
1493 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1494 % (_tkinter
.TK_VERSION
, tk_version
)
1495 tcl_version
= self
.tk
.getvar('tcl_version')
1496 if tcl_version
!= _tkinter
.TCL_VERSION
:
1497 raise RuntimeError, \
1498 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1499 % (_tkinter
.TCL_VERSION
, tcl_version
)
1501 raise RuntimeError, \
1502 "Tk 4.0 or higher is required; found Tk %s" \
1504 self
.tk
.createcommand('tkerror', _tkerror
)
1505 self
.tk
.createcommand('exit', _exit
)
1506 self
.readprofile(baseName
, className
)
1507 if _support_default_root
and not _default_root
:
1508 _default_root
= self
1509 self
.protocol("WM_DELETE_WINDOW", self
.destroy
)
1511 """Destroy this and all descendants widgets. This will
1512 end the application of this Tcl interpreter."""
1513 for c
in self
.children
.values(): c
.destroy()
1514 self
.tk
.call('destroy', self
._w
)
1516 global _default_root
1517 if _support_default_root
and _default_root
is self
:
1518 _default_root
= None
1519 def readprofile(self
, baseName
, className
):
1520 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1521 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1522 such a file exists in the home directory."""
1524 if os
.environ
.has_key('HOME'): home
= os
.environ
['HOME']
1525 else: home
= os
.curdir
1526 class_tcl
= os
.path
.join(home
, '.%s.tcl' % className
)
1527 class_py
= os
.path
.join(home
, '.%s.py' % className
)
1528 base_tcl
= os
.path
.join(home
, '.%s.tcl' % baseName
)
1529 base_py
= os
.path
.join(home
, '.%s.py' % baseName
)
1530 dir = {'self': self
}
1531 exec 'from Tkinter import *' in dir
1532 if os
.path
.isfile(class_tcl
):
1533 self
.tk
.call('source', class_tcl
)
1534 if os
.path
.isfile(class_py
):
1535 execfile(class_py
, dir)
1536 if os
.path
.isfile(base_tcl
):
1537 self
.tk
.call('source', base_tcl
)
1538 if os
.path
.isfile(base_py
):
1539 execfile(base_py
, dir)
1540 def report_callback_exception(self
, exc
, val
, tb
):
1541 """Internal function. It reports exception on sys.stderr."""
1542 import traceback
, sys
1543 sys
.stderr
.write("Exception in Tkinter callback\n")
1545 sys
.last_value
= val
1546 sys
.last_traceback
= tb
1547 traceback
.print_exception(exc
, val
, tb
)
1549 # Ideally, the classes Pack, Place and Grid disappear, the
1550 # pack/place/grid methods are defined on the Widget class, and
1551 # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1552 # ...), with pack(), place() and grid() being short for
1553 # pack_configure(), place_configure() and grid_columnconfigure(), and
1554 # forget() being short for pack_forget(). As a practical matter, I'm
1555 # afraid that there is too much code out there that may be using the
1556 # Pack, Place or Grid class, so I leave them intact -- but only as
1557 # backwards compatibility features. Also note that those methods that
1558 # take a master as argument (e.g. pack_propagate) have been moved to
1559 # the Misc class (which now incorporates all methods common between
1560 # toplevel and interior widgets). Again, for compatibility, these are
1561 # copied into the Pack, Place or Grid class.
1564 """Geometry manager Pack.
1566 Base class to use the methods pack_* in every widget."""
1567 def pack_configure(self
, cnf
={}, **kw
):
1568 """Pack a widget in the parent widget. Use as options:
1569 after=widget - pack it after you have packed widget
1570 anchor=NSEW (or subset) - position widget according to
1572 before=widget - pack it before you will pack widget
1573 expand=1 or 0 - expand widget if parent size grows
1574 fill=NONE or X or Y or BOTH - fill widget if widget grows
1575 in=master - use master to contain this widget
1576 ipadx=amount - add internal padding in x direction
1577 ipady=amount - add internal padding in y direction
1578 padx=amount - add padding in x direction
1579 pady=amount - add padding in y direction
1580 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1583 ('pack', 'configure', self
._w
)
1584 + self
._options
(cnf
, kw
))
1585 pack
= configure
= config
= pack_configure
1586 def pack_forget(self
):
1587 """Unmap this widget and do not use it for the packing order."""
1588 self
.tk
.call('pack', 'forget', self
._w
)
1589 forget
= pack_forget
1590 def pack_info(self
):
1591 """Return information about the packing options
1593 words
= self
.tk
.splitlist(
1594 self
.tk
.call('pack', 'info', self
._w
))
1596 for i
in range(0, len(words
), 2):
1599 if value
[:1] == '.':
1600 value
= self
._nametowidget
(value
)
1604 propagate
= pack_propagate
= Misc
.pack_propagate
1605 slaves
= pack_slaves
= Misc
.pack_slaves
1608 """Geometry manager Place.
1610 Base class to use the methods place_* in every widget."""
1611 def place_configure(self
, cnf
={}, **kw
):
1612 """Place a widget in the parent widget. Use as options:
1613 in=master - master relative to which the widget is placed.
1614 x=amount - locate anchor of this widget at position x of master
1615 y=amount - locate anchor of this widget at position y of master
1616 relx=amount - locate anchor of this widget between 0.0 and 1.0
1617 relative to width of master (1.0 is right edge)
1618 rely=amount - locate anchor of this widget between 0.0 and 1.0
1619 relative to height of master (1.0 is bottom edge)
1620 anchor=NSEW (or subset) - position anchor according to given direction
1621 width=amount - width of this widget in pixel
1622 height=amount - height of this widget in pixel
1623 relwidth=amount - width of this widget between 0.0 and 1.0
1624 relative to width of master (1.0 is the same width
1626 relheight=amount - height of this widget between 0.0 and 1.0
1627 relative to height of master (1.0 is the same
1628 height as the master)
1629 bordermode="inside" or "outside" - whether to take border width of master widget
1637 ('place', 'configure', self
._w
)
1638 + self
._options
(cnf
, kw
))
1639 place
= configure
= config
= place_configure
1640 def place_forget(self
):
1641 """Unmap this widget."""
1642 self
.tk
.call('place', 'forget', self
._w
)
1643 forget
= place_forget
1644 def place_info(self
):
1645 """Return information about the placing options
1647 words
= self
.tk
.splitlist(
1648 self
.tk
.call('place', 'info', self
._w
))
1650 for i
in range(0, len(words
), 2):
1653 if value
[:1] == '.':
1654 value
= self
._nametowidget
(value
)
1658 slaves
= place_slaves
= Misc
.place_slaves
1661 """Geometry manager Grid.
1663 Base class to use the methods grid_* in every widget."""
1664 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1665 def grid_configure(self
, cnf
={}, **kw
):
1666 """Position a widget in the parent widget in a grid. Use as options:
1667 column=number - use cell identified with given column (starting with 0)
1668 columnspan=number - this widget will span several columns
1669 in=master - use master to contain this widget
1670 ipadx=amount - add internal padding in x direction
1671 ipady=amount - add internal padding in y direction
1672 padx=amount - add padding in x direction
1673 pady=amount - add padding in y direction
1674 row=number - use cell identified with given row (starting with 0)
1675 rowspan=number - this widget will span several rows
1676 sticky=NSEW - if cell is larger on which sides will this
1677 widget stick to the cell boundary
1680 ('grid', 'configure', self
._w
)
1681 + self
._options
(cnf
, kw
))
1682 grid
= configure
= config
= grid_configure
1683 bbox
= grid_bbox
= Misc
.grid_bbox
1684 columnconfigure
= grid_columnconfigure
= Misc
.grid_columnconfigure
1685 def grid_forget(self
):
1686 """Unmap this widget."""
1687 self
.tk
.call('grid', 'forget', self
._w
)
1688 forget
= grid_forget
1689 def grid_remove(self
):
1690 """Unmap this widget but remember the grid options."""
1691 self
.tk
.call('grid', 'remove', self
._w
)
1692 def grid_info(self
):
1693 """Return information about the options
1694 for positioning this widget in a grid."""
1695 words
= self
.tk
.splitlist(
1696 self
.tk
.call('grid', 'info', self
._w
))
1698 for i
in range(0, len(words
), 2):
1701 if value
[:1] == '.':
1702 value
= self
._nametowidget
(value
)
1706 def grid_location(self
, x
, y
):
1707 """Return a tuple of column and row which identify the cell
1708 at which the pixel at position X and Y inside the master
1709 widget is located."""
1710 return self
._getints
(
1712 'grid', 'location', self
._w
, x
, y
)) or None
1713 location
= grid_location
1714 propagate
= grid_propagate
= Misc
.grid_propagate
1715 rowconfigure
= grid_rowconfigure
= Misc
.grid_rowconfigure
1716 size
= grid_size
= Misc
.grid_size
1717 slaves
= grid_slaves
= Misc
.grid_slaves
1719 class BaseWidget(Misc
):
1720 """Internal class."""
1721 def _setup(self
, master
, cnf
):
1722 """Internal function. Sets up information about children."""
1723 if _support_default_root
:
1724 global _default_root
1726 if not _default_root
:
1727 _default_root
= Tk()
1728 master
= _default_root
1729 self
.master
= master
1732 if cnf
.has_key('name'):
1739 self
._w
= '.' + name
1741 self
._w
= master
._w
+ '.' + name
1743 if self
.master
.children
.has_key(self
._name
):
1744 self
.master
.children
[self
._name
].destroy()
1745 self
.master
.children
[self
._name
] = self
1746 def __init__(self
, master
, widgetName
, cnf
={}, kw
={}, extra
=()):
1747 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1748 and appropriate options."""
1750 cnf
= _cnfmerge((cnf
, kw
))
1751 self
.widgetName
= widgetName
1752 BaseWidget
._setup
(self
, master
, cnf
)
1754 for k
in cnf
.keys():
1755 if type(k
) is ClassType
:
1756 classes
.append((k
, cnf
[k
]))
1759 (widgetName
, self
._w
) + extra
+ self
._options
(cnf
))
1760 for k
, v
in classes
:
1761 k
.configure(self
, v
)
1763 """Destroy this and all descendants widgets."""
1764 for c
in self
.children
.values(): c
.destroy()
1765 if self
.master
.children
.has_key(self
._name
):
1766 del self
.master
.children
[self
._name
]
1767 self
.tk
.call('destroy', self
._w
)
1769 def _do(self
, name
, args
=()):
1770 # XXX Obsolete -- better use self.tk.call directly!
1771 return self
.tk
.call((self
._w
, name
) + args
)
1773 class Widget(BaseWidget
, Pack
, Place
, Grid
):
1776 Base class for a widget which can be positioned with the geometry managers
1777 Pack, Place or Grid."""
1780 class Toplevel(BaseWidget
, Wm
):
1781 """Toplevel widget, e.g. for dialogs."""
1782 def __init__(self
, master
=None, cnf
={}, **kw
):
1783 """Construct a toplevel widget with the parent MASTER.
1785 Valid resource names: background, bd, bg, borderwidth, class,
1786 colormap, container, cursor, height, highlightbackground,
1787 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1788 use, visual, width."""
1790 cnf
= _cnfmerge((cnf
, kw
))
1792 for wmkey
in ['screen', 'class_', 'class', 'visual',
1794 if cnf
.has_key(wmkey
):
1796 # TBD: a hack needed because some keys
1797 # are not valid as keyword arguments
1798 if wmkey
[-1] == '_': opt
= '-'+wmkey
[:-1]
1799 else: opt
= '-'+wmkey
1800 extra
= extra
+ (opt
, val
)
1802 BaseWidget
.__init
__(self
, master
, 'toplevel', cnf
, {}, extra
)
1804 self
.iconname(root
.iconname())
1805 self
.title(root
.title())
1806 self
.protocol("WM_DELETE_WINDOW", self
.destroy
)
1808 class Button(Widget
):
1809 """Button widget."""
1810 def __init__(self
, master
=None, cnf
={}, **kw
):
1811 """Construct a button widget with the parent MASTER.
1813 Valid resource names: activebackground, activeforeground, anchor,
1814 background, bd, bg, bitmap, borderwidth, command, cursor, default,
1815 disabledforeground, fg, font, foreground, height,
1816 highlightbackground, highlightcolor, highlightthickness, image,
1817 justify, padx, pady, relief, state, takefocus, text, textvariable,
1818 underline, width, wraplength."""
1819 Widget
.__init
__(self
, master
, 'button', cnf
, kw
)
1820 def tkButtonEnter(self
, *dummy
):
1821 self
.tk
.call('tkButtonEnter', self
._w
)
1822 def tkButtonLeave(self
, *dummy
):
1823 self
.tk
.call('tkButtonLeave', self
._w
)
1824 def tkButtonDown(self
, *dummy
):
1825 self
.tk
.call('tkButtonDown', self
._w
)
1826 def tkButtonUp(self
, *dummy
):
1827 self
.tk
.call('tkButtonUp', self
._w
)
1828 def tkButtonInvoke(self
, *dummy
):
1829 self
.tk
.call('tkButtonInvoke', self
._w
)
1831 self
.tk
.call(self
._w
, 'flash')
1833 return self
.tk
.call(self
._w
, 'invoke')
1836 # XXX I don't like these -- take them away
1839 def AtInsert(*args
):
1842 if a
: s
= s
+ (' ' + a
)
1852 return '@' + `x`
+ ',' + `y`
1854 class Canvas(Widget
):
1855 """Canvas widget to display graphical elements like lines or text."""
1856 def __init__(self
, master
=None, cnf
={}, **kw
):
1857 """Construct a canvas widget with the parent MASTER.
1859 Valid resource names: background, bd, bg, borderwidth, closeenough,
1860 confine, cursor, height, highlightbackground, highlightcolor,
1861 highlightthickness, insertbackground, insertborderwidth,
1862 insertofftime, insertontime, insertwidth, offset, relief,
1863 scrollregion, selectbackground, selectborderwidth, selectforeground,
1864 state, takefocus, width, xscrollcommand, xscrollincrement,
1865 yscrollcommand, yscrollincrement."""
1866 Widget
.__init
__(self
, master
, 'canvas', cnf
, kw
)
1867 def addtag(self
, *args
):
1868 """Internal function."""
1869 self
.tk
.call((self
._w
, 'addtag') + args
)
1870 def addtag_above(self
, newtag
, tagOrId
):
1871 """Add tag NEWTAG to all items above TAGORID."""
1872 self
.addtag(newtag
, 'above', tagOrId
)
1873 def addtag_all(self
, newtag
):
1874 """Add tag NEWTAG to all items."""
1875 self
.addtag(newtag
, 'all')
1876 def addtag_below(self
, newtag
, tagOrId
):
1877 """Add tag NEWTAG to all items below TAGORID."""
1878 self
.addtag(newtag
, 'below', tagOrId
)
1879 def addtag_closest(self
, newtag
, x
, y
, halo
=None, start
=None):
1880 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1881 If several match take the top-most.
1882 All items closer than HALO are considered overlapping (all are
1883 closests). If START is specified the next below this tag is taken."""
1884 self
.addtag(newtag
, 'closest', x
, y
, halo
, start
)
1885 def addtag_enclosed(self
, newtag
, x1
, y1
, x2
, y2
):
1886 """Add tag NEWTAG to all items in the rectangle defined
1888 self
.addtag(newtag
, 'enclosed', x1
, y1
, x2
, y2
)
1889 def addtag_overlapping(self
, newtag
, x1
, y1
, x2
, y2
):
1890 """Add tag NEWTAG to all items which overlap the rectangle
1891 defined by X1,Y1,X2,Y2."""
1892 self
.addtag(newtag
, 'overlapping', x1
, y1
, x2
, y2
)
1893 def addtag_withtag(self
, newtag
, tagOrId
):
1894 """Add tag NEWTAG to all items with TAGORID."""
1895 self
.addtag(newtag
, 'withtag', tagOrId
)
1896 def bbox(self
, *args
):
1897 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1898 which encloses all items with tags specified as arguments."""
1899 return self
._getints
(
1900 self
.tk
.call((self
._w
, 'bbox') + args
)) or None
1901 def tag_unbind(self
, tagOrId
, sequence
, funcid
=None):
1902 """Unbind for all items with TAGORID for event SEQUENCE the
1903 function identified with FUNCID."""
1904 self
.tk
.call(self
._w
, 'bind', tagOrId
, sequence
, '')
1906 self
.deletecommand(funcid
)
1907 def tag_bind(self
, tagOrId
, sequence
=None, func
=None, add
=None):
1908 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
1910 An additional boolean parameter ADD specifies whether FUNC will be
1911 called additionally to the other bound function or whether it will
1912 replace the previous function. See bind for the return value."""
1913 return self
._bind
((self
._w
, 'bind', tagOrId
),
1914 sequence
, func
, add
)
1915 def canvasx(self
, screenx
, gridspacing
=None):
1916 """Return the canvas x coordinate of pixel position SCREENX rounded
1917 to nearest multiple of GRIDSPACING units."""
1918 return getdouble(self
.tk
.call(
1919 self
._w
, 'canvasx', screenx
, gridspacing
))
1920 def canvasy(self
, screeny
, gridspacing
=None):
1921 """Return the canvas y coordinate of pixel position SCREENY rounded
1922 to nearest multiple of GRIDSPACING units."""
1923 return getdouble(self
.tk
.call(
1924 self
._w
, 'canvasy', screeny
, gridspacing
))
1925 def coords(self
, *args
):
1926 """Return a list of coordinates for the item given in ARGS."""
1927 # XXX Should use _flatten on args
1928 return map(getdouble
,
1930 self
.tk
.call((self
._w
, 'coords') + args
)))
1931 def _create(self
, itemType
, args
, kw
): # Args: (val, val, ..., cnf={})
1932 """Internal function."""
1933 args
= _flatten(args
)
1935 if type(cnf
) in (DictionaryType
, TupleType
):
1939 return getint(apply(
1941 (self
._w
, 'create', itemType
)
1942 + args
+ self
._options
(cnf
, kw
)))
1943 def create_arc(self
, *args
, **kw
):
1944 """Create arc shaped region with coordinates x1,y1,x2,y2."""
1945 return self
._create
('arc', args
, kw
)
1946 def create_bitmap(self
, *args
, **kw
):
1947 """Create bitmap with coordinates x1,y1."""
1948 return self
._create
('bitmap', args
, kw
)
1949 def create_image(self
, *args
, **kw
):
1950 """Create image item with coordinates x1,y1."""
1951 return self
._create
('image', args
, kw
)
1952 def create_line(self
, *args
, **kw
):
1953 """Create line with coordinates x1,y1,...,xn,yn."""
1954 return self
._create
('line', args
, kw
)
1955 def create_oval(self
, *args
, **kw
):
1956 """Create oval with coordinates x1,y1,x2,y2."""
1957 return self
._create
('oval', args
, kw
)
1958 def create_polygon(self
, *args
, **kw
):
1959 """Create polygon with coordinates x1,y1,...,xn,yn."""
1960 return self
._create
('polygon', args
, kw
)
1961 def create_rectangle(self
, *args
, **kw
):
1962 """Create rectangle with coordinates x1,y1,x2,y2."""
1963 return self
._create
('rectangle', args
, kw
)
1964 def create_text(self
, *args
, **kw
):
1965 """Create text with coordinates x1,y1."""
1966 return self
._create
('text', args
, kw
)
1967 def create_window(self
, *args
, **kw
):
1968 """Create window with coordinates x1,y1,x2,y2."""
1969 return self
._create
('window', args
, kw
)
1970 def dchars(self
, *args
):
1971 """Delete characters of text items identified by tag or id in ARGS (possibly
1972 several times) from FIRST to LAST character (including)."""
1973 self
.tk
.call((self
._w
, 'dchars') + args
)
1974 def delete(self
, *args
):
1975 """Delete items identified by all tag or ids contained in ARGS."""
1976 self
.tk
.call((self
._w
, 'delete') + args
)
1977 def dtag(self
, *args
):
1978 """Delete tag or id given as last arguments in ARGS from items
1979 identified by first argument in ARGS."""
1980 self
.tk
.call((self
._w
, 'dtag') + args
)
1981 def find(self
, *args
):
1982 """Internal function."""
1983 return self
._getints
(
1984 self
.tk
.call((self
._w
, 'find') + args
)) or ()
1985 def find_above(self
, tagOrId
):
1986 """Return items above TAGORID."""
1987 return self
.find('above', tagOrId
)
1989 """Return all items."""
1990 return self
.find('all')
1991 def find_below(self
, tagOrId
):
1992 """Return all items below TAGORID."""
1993 return self
.find('below', tagOrId
)
1994 def find_closest(self
, x
, y
, halo
=None, start
=None):
1995 """Return item which is closest to pixel at X, Y.
1996 If several match take the top-most.
1997 All items closer than HALO are considered overlapping (all are
1998 closests). If START is specified the next below this tag is taken."""
1999 return self
.find('closest', x
, y
, halo
, start
)
2000 def find_enclosed(self
, x1
, y1
, x2
, y2
):
2001 """Return all items in rectangle defined
2003 return self
.find('enclosed', x1
, y1
, x2
, y2
)
2004 def find_overlapping(self
, x1
, y1
, x2
, y2
):
2005 """Return all items which overlap the rectangle
2006 defined by X1,Y1,X2,Y2."""
2007 return self
.find('overlapping', x1
, y1
, x2
, y2
)
2008 def find_withtag(self
, tagOrId
):
2009 """Return all items with TAGORID."""
2010 return self
.find('withtag', tagOrId
)
2011 def focus(self
, *args
):
2012 """Set focus to the first item specified in ARGS."""
2013 return self
.tk
.call((self
._w
, 'focus') + args
)
2014 def gettags(self
, *args
):
2015 """Return tags associated with the first item specified in ARGS."""
2016 return self
.tk
.splitlist(
2017 self
.tk
.call((self
._w
, 'gettags') + args
))
2018 def icursor(self
, *args
):
2019 """Set cursor at position POS in the item identified by TAGORID.
2020 In ARGS TAGORID must be first."""
2021 self
.tk
.call((self
._w
, 'icursor') + args
)
2022 def index(self
, *args
):
2023 """Return position of cursor as integer in item specified in ARGS."""
2024 return getint(self
.tk
.call((self
._w
, 'index') + args
))
2025 def insert(self
, *args
):
2026 """Insert TEXT in item TAGORID at position POS. ARGS must
2027 be TAGORID POS TEXT."""
2028 self
.tk
.call((self
._w
, 'insert') + args
)
2029 def itemcget(self
, tagOrId
, option
):
2030 """Return the resource value for an OPTION for item TAGORID."""
2031 return self
.tk
.call(
2032 (self
._w
, 'itemcget') + (tagOrId
, '-'+option
))
2033 def itemconfigure(self
, tagOrId
, cnf
=None, **kw
):
2034 """Configure resources of an item TAGORID.
2036 The values for resources are specified as keyword
2037 arguments. To get an overview about
2038 the allowed keyword arguments call the method without arguments.
2040 if cnf
is None and not kw
:
2042 for x
in self
.tk
.split(
2043 self
.tk
.call(self
._w
,
2044 'itemconfigure', tagOrId
)):
2045 cnf
[x
[0][1:]] = (x
[0][1:],) + x
[1:]
2047 if type(cnf
) == StringType
and not kw
:
2048 x
= self
.tk
.split(self
.tk
.call(
2049 self
._w
, 'itemconfigure', tagOrId
, '-'+cnf
))
2050 return (x
[0][1:],) + x
[1:]
2051 self
.tk
.call((self
._w
, 'itemconfigure', tagOrId
) +
2052 self
._options
(cnf
, kw
))
2053 itemconfig
= itemconfigure
2054 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2055 # so the preferred name for them is tag_lower, tag_raise
2056 # (similar to tag_bind, and similar to the Text widget);
2057 # unfortunately can't delete the old ones yet (maybe in 1.6)
2058 def tag_lower(self
, *args
):
2059 """Lower an item TAGORID given in ARGS
2060 (optional below another item)."""
2061 self
.tk
.call((self
._w
, 'lower') + args
)
2063 def move(self
, *args
):
2064 """Move an item TAGORID given in ARGS."""
2065 self
.tk
.call((self
._w
, 'move') + args
)
2066 def postscript(self
, cnf
={}, **kw
):
2067 """Print the contents of the canvas to a postscript
2068 file. Valid options: colormap, colormode, file, fontmap,
2069 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2070 rotate, witdh, x, y."""
2071 return self
.tk
.call((self
._w
, 'postscript') +
2072 self
._options
(cnf
, kw
))
2073 def tag_raise(self
, *args
):
2074 """Raise an item TAGORID given in ARGS
2075 (optional above another item)."""
2076 self
.tk
.call((self
._w
, 'raise') + args
)
2077 lift
= tkraise
= tag_raise
2078 def scale(self
, *args
):
2079 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2080 self
.tk
.call((self
._w
, 'scale') + args
)
2081 def scan_mark(self
, x
, y
):
2082 """Remember the current X, Y coordinates."""
2083 self
.tk
.call(self
._w
, 'scan', 'mark', x
, y
)
2084 def scan_dragto(self
, x
, y
):
2085 """Adjust the view of the canvas to 10 times the
2086 difference between X and Y and the coordinates given in
2088 self
.tk
.call(self
._w
, 'scan', 'dragto', x
, y
)
2089 def select_adjust(self
, tagOrId
, index
):
2090 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2091 self
.tk
.call(self
._w
, 'select', 'adjust', tagOrId
, index
)
2092 def select_clear(self
):
2093 """Clear the selection if it is in this widget."""
2094 self
.tk
.call(self
._w
, 'select', 'clear')
2095 def select_from(self
, tagOrId
, index
):
2096 """Set the fixed end of a selection in item TAGORID to INDEX."""
2097 self
.tk
.call(self
._w
, 'select', 'from', tagOrId
, index
)
2098 def select_item(self
):
2099 """Return the item which has the selection."""
2100 self
.tk
.call(self
._w
, 'select', 'item')
2101 def select_to(self
, tagOrId
, index
):
2102 """Set the variable end of a selection in item TAGORID to INDEX."""
2103 self
.tk
.call(self
._w
, 'select', 'to', tagOrId
, index
)
2104 def type(self
, tagOrId
):
2105 """Return the type of the item TAGORID."""
2106 return self
.tk
.call(self
._w
, 'type', tagOrId
) or None
2107 def xview(self
, *args
):
2108 """Query and change horizontal position of the view."""
2110 return self
._getdoubles
(self
.tk
.call(self
._w
, 'xview'))
2111 self
.tk
.call((self
._w
, 'xview') + args
)
2112 def xview_moveto(self
, fraction
):
2113 """Adjusts the view in the window so that FRACTION of the
2114 total width of the canvas is off-screen to the left."""
2115 self
.tk
.call(self
._w
, 'xview', 'moveto', fraction
)
2116 def xview_scroll(self
, number
, what
):
2117 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2118 self
.tk
.call(self
._w
, 'xview', 'scroll', number
, what
)
2119 def yview(self
, *args
):
2120 """Query and change vertical position of the view."""
2122 return self
._getdoubles
(self
.tk
.call(self
._w
, 'yview'))
2123 self
.tk
.call((self
._w
, 'yview') + args
)
2124 def yview_moveto(self
, fraction
):
2125 """Adjusts the view in the window so that FRACTION of the
2126 total height of the canvas is off-screen to the top."""
2127 self
.tk
.call(self
._w
, 'yview', 'moveto', fraction
)
2128 def yview_scroll(self
, number
, what
):
2129 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2130 self
.tk
.call(self
._w
, 'yview', 'scroll', number
, what
)
2132 class Checkbutton(Widget
):
2133 """Checkbutton widget which is either in on- or off-state."""
2134 def __init__(self
, master
=None, cnf
={}, **kw
):
2135 """Construct a checkbutton widget with the parent MASTER.
2137 Valid resource names: activebackground, activeforeground, anchor,
2138 background, bd, bg, bitmap, borderwidth, command, cursor,
2139 disabledforeground, fg, font, foreground, height,
2140 highlightbackground, highlightcolor, highlightthickness, image,
2141 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2142 selectcolor, selectimage, state, takefocus, text, textvariable,
2143 underline, variable, width, wraplength."""
2144 Widget
.__init
__(self
, master
, 'checkbutton', cnf
, kw
)
2146 """Put the button in off-state."""
2147 self
.tk
.call(self
._w
, 'deselect')
2149 """Flash the button."""
2150 self
.tk
.call(self
._w
, 'flash')
2152 """Toggle the button and invoke a command if given as resource."""
2153 return self
.tk
.call(self
._w
, 'invoke')
2155 """Put the button in on-state."""
2156 self
.tk
.call(self
._w
, 'select')
2158 """Toggle the button."""
2159 self
.tk
.call(self
._w
, 'toggle')
2161 class Entry(Widget
):
2162 """Entry widget which allows to display simple text."""
2163 def __init__(self
, master
=None, cnf
={}, **kw
):
2164 """Construct an entry widget with the parent MASTER.
2166 Valid resource names: background, bd, bg, borderwidth, cursor,
2167 exportselection, fg, font, foreground, highlightbackground,
2168 highlightcolor, highlightthickness, insertbackground,
2169 insertborderwidth, insertofftime, insertontime, insertwidth,
2170 invalidcommand, invcmd, justify, relief, selectbackground,
2171 selectborderwidth, selectforeground, show, state, takefocus,
2172 textvariable, validate, validatecommand, vcmd, width,
2174 Widget
.__init
__(self
, master
, 'entry', cnf
, kw
)
2175 def delete(self
, first
, last
=None):
2176 """Delete text from FIRST to LAST (not included)."""
2177 self
.tk
.call(self
._w
, 'delete', first
, last
)
2179 """Return the text."""
2180 return self
.tk
.call(self
._w
, 'get')
2181 def icursor(self
, index
):
2182 """Insert cursor at INDEX."""
2183 self
.tk
.call(self
._w
, 'icursor', index
)
2184 def index(self
, index
):
2185 """Return position of cursor."""
2186 return getint(self
.tk
.call(
2187 self
._w
, 'index', index
))
2188 def insert(self
, index
, string
):
2189 """Insert STRING at INDEX."""
2190 self
.tk
.call(self
._w
, 'insert', index
, string
)
2191 def scan_mark(self
, x
):
2192 """Remember the current X, Y coordinates."""
2193 self
.tk
.call(self
._w
, 'scan', 'mark', x
)
2194 def scan_dragto(self
, x
):
2195 """Adjust the view of the canvas to 10 times the
2196 difference between X and Y and the coordinates given in
2198 self
.tk
.call(self
._w
, 'scan', 'dragto', x
)
2199 def selection_adjust(self
, index
):
2200 """Adjust the end of the selection near the cursor to INDEX."""
2201 self
.tk
.call(self
._w
, 'selection', 'adjust', index
)
2202 select_adjust
= selection_adjust
2203 def selection_clear(self
):
2204 """Clear the selection if it is in this widget."""
2205 self
.tk
.call(self
._w
, 'selection', 'clear')
2206 select_clear
= selection_clear
2207 def selection_from(self
, index
):
2208 """Set the fixed end of a selection to INDEX."""
2209 self
.tk
.call(self
._w
, 'selection', 'from', index
)
2210 select_from
= selection_from
2211 def selection_present(self
):
2212 """Return whether the widget has the selection."""
2213 return self
.tk
.getboolean(
2214 self
.tk
.call(self
._w
, 'selection', 'present'))
2215 select_present
= selection_present
2216 def selection_range(self
, start
, end
):
2217 """Set the selection from START to END (not included)."""
2218 self
.tk
.call(self
._w
, 'selection', 'range', start
, end
)
2219 select_range
= selection_range
2220 def selection_to(self
, index
):
2221 """Set the variable end of a selection to INDEX."""
2222 self
.tk
.call(self
._w
, 'selection', 'to', index
)
2223 select_to
= selection_to
2224 def xview(self
, index
):
2225 """Query and change horizontal position of the view."""
2226 self
.tk
.call(self
._w
, 'xview', index
)
2227 def xview_moveto(self
, fraction
):
2228 """Adjust the view in the window so that FRACTION of the
2229 total width of the entry is off-screen to the left."""
2230 self
.tk
.call(self
._w
, 'xview', 'moveto', fraction
)
2231 def xview_scroll(self
, number
, what
):
2232 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2233 self
.tk
.call(self
._w
, 'xview', 'scroll', number
, what
)
2235 class Frame(Widget
):
2236 """Frame widget which may contain other widgets and can have a 3D border."""
2237 def __init__(self
, master
=None, cnf
={}, **kw
):
2238 """Construct a frame widget with the parent MASTER.
2240 Valid resource names: background, bd, bg, borderwidth, class,
2241 colormap, container, cursor, height, highlightbackground,
2242 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2243 cnf
= _cnfmerge((cnf
, kw
))
2245 if cnf
.has_key('class_'):
2246 extra
= ('-class', cnf
['class_'])
2248 elif cnf
.has_key('class'):
2249 extra
= ('-class', cnf
['class'])
2251 Widget
.__init
__(self
, master
, 'frame', cnf
, {}, extra
)
2253 class Label(Widget
):
2254 """Label widget which can display text and bitmaps."""
2255 def __init__(self
, master
=None, cnf
={}, **kw
):
2256 """Construct a label widget with the parent MASTER.
2258 Valid resource names: anchor, background, bd, bg, bitmap,
2259 borderwidth, cursor, fg, font, foreground, height,
2260 highlightbackground, highlightcolor, highlightthickness, image,
2261 justify, padx, pady, relief, takefocus, text, textvariable,
2262 underline, width, wraplength."""
2263 Widget
.__init
__(self
, master
, 'label', cnf
, kw
)
2265 class Listbox(Widget
):
2266 """Listbox widget which can display a list of strings."""
2267 def __init__(self
, master
=None, cnf
={}, **kw
):
2268 """Construct a listbox widget with the parent MASTER.
2270 Valid resource names: background, bd, bg, borderwidth, cursor,
2271 exportselection, fg, font, foreground, height, highlightbackground,
2272 highlightcolor, highlightthickness, relief, selectbackground,
2273 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2274 width, xscrollcommand, yscrollcommand, listvariable."""
2275 Widget
.__init
__(self
, master
, 'listbox', cnf
, kw
)
2276 def activate(self
, index
):
2277 """Activate item identified by INDEX."""
2278 self
.tk
.call(self
._w
, 'activate', index
)
2279 def bbox(self
, *args
):
2280 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2281 which encloses the item identified by index in ARGS."""
2282 return self
._getints
(
2283 self
.tk
.call((self
._w
, 'bbox') + args
)) or None
2284 def curselection(self
):
2285 """Return list of indices of currently selected item."""
2286 # XXX Ought to apply self._getints()...
2287 return self
.tk
.splitlist(self
.tk
.call(
2288 self
._w
, 'curselection'))
2289 def delete(self
, first
, last
=None):
2290 """Delete items from FIRST to LAST (not included)."""
2291 self
.tk
.call(self
._w
, 'delete', first
, last
)
2292 def get(self
, first
, last
=None):
2293 """Get list of items from FIRST to LAST (not included)."""
2295 return self
.tk
.splitlist(self
.tk
.call(
2296 self
._w
, 'get', first
, last
))
2298 return self
.tk
.call(self
._w
, 'get', first
)
2299 def index(self
, index
):
2300 """Return index of item identified with INDEX."""
2301 i
= self
.tk
.call(self
._w
, 'index', index
)
2302 if i
== 'none': return None
2304 def insert(self
, index
, *elements
):
2305 """Insert ELEMENTS at INDEX."""
2306 self
.tk
.call((self
._w
, 'insert', index
) + elements
)
2307 def nearest(self
, y
):
2308 """Get index of item which is nearest to y coordinate Y."""
2309 return getint(self
.tk
.call(
2310 self
._w
, 'nearest', y
))
2311 def scan_mark(self
, x
, y
):
2312 """Remember the current X, Y coordinates."""
2313 self
.tk
.call(self
._w
, 'scan', 'mark', x
, y
)
2314 def scan_dragto(self
, x
, y
):
2315 """Adjust the view of the listbox to 10 times the
2316 difference between X and Y and the coordinates given in
2318 self
.tk
.call(self
._w
, 'scan', 'dragto', x
, y
)
2319 def see(self
, index
):
2320 """Scroll such that INDEX is visible."""
2321 self
.tk
.call(self
._w
, 'see', index
)
2322 def selection_anchor(self
, index
):
2323 """Set the fixed end oft the selection to INDEX."""
2324 self
.tk
.call(self
._w
, 'selection', 'anchor', index
)
2325 select_anchor
= selection_anchor
2326 def selection_clear(self
, first
, last
=None):
2327 """Clear the selection from FIRST to LAST (not included)."""
2328 self
.tk
.call(self
._w
,
2329 'selection', 'clear', first
, last
)
2330 select_clear
= selection_clear
2331 def selection_includes(self
, index
):
2332 """Return 1 if INDEX is part of the selection."""
2333 return self
.tk
.getboolean(self
.tk
.call(
2334 self
._w
, 'selection', 'includes', index
))
2335 select_includes
= selection_includes
2336 def selection_set(self
, first
, last
=None):
2337 """Set the selection from FIRST to LAST (not included) without
2338 changing the currently selected elements."""
2339 self
.tk
.call(self
._w
, 'selection', 'set', first
, last
)
2340 select_set
= selection_set
2342 """Return the number of elements in the listbox."""
2343 return getint(self
.tk
.call(self
._w
, 'size'))
2344 def xview(self
, *what
):
2345 """Query and change horizontal position of the view."""
2347 return self
._getdoubles
(self
.tk
.call(self
._w
, 'xview'))
2348 self
.tk
.call((self
._w
, 'xview') + what
)
2349 def xview_moveto(self
, fraction
):
2350 """Adjust the view in the window so that FRACTION of the
2351 total width of the entry is off-screen to the left."""
2352 self
.tk
.call(self
._w
, 'xview', 'moveto', fraction
)
2353 def xview_scroll(self
, number
, what
):
2354 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2355 self
.tk
.call(self
._w
, 'xview', 'scroll', number
, what
)
2356 def yview(self
, *what
):
2357 """Query and change vertical position of the view."""
2359 return self
._getdoubles
(self
.tk
.call(self
._w
, 'yview'))
2360 self
.tk
.call((self
._w
, 'yview') + what
)
2361 def yview_moveto(self
, fraction
):
2362 """Adjust the view in the window so that FRACTION of the
2363 total width of the entry is off-screen to the top."""
2364 self
.tk
.call(self
._w
, 'yview', 'moveto', fraction
)
2365 def yview_scroll(self
, number
, what
):
2366 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2367 self
.tk
.call(self
._w
, 'yview', 'scroll', number
, what
)
2370 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2371 def __init__(self
, master
=None, cnf
={}, **kw
):
2372 """Construct menu widget with the parent MASTER.
2374 Valid resource names: activebackground, activeborderwidth,
2375 activeforeground, background, bd, bg, borderwidth, cursor,
2376 disabledforeground, fg, font, foreground, postcommand, relief,
2377 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2378 Widget
.__init
__(self
, master
, 'menu', cnf
, kw
)
2379 def tk_bindForTraversal(self
):
2380 pass # obsolete since Tk 4.0
2381 def tk_mbPost(self
):
2382 self
.tk
.call('tk_mbPost', self
._w
)
2383 def tk_mbUnpost(self
):
2384 self
.tk
.call('tk_mbUnpost')
2385 def tk_traverseToMenu(self
, char
):
2386 self
.tk
.call('tk_traverseToMenu', self
._w
, char
)
2387 def tk_traverseWithinMenu(self
, char
):
2388 self
.tk
.call('tk_traverseWithinMenu', self
._w
, char
)
2389 def tk_getMenuButtons(self
):
2390 return self
.tk
.call('tk_getMenuButtons', self
._w
)
2391 def tk_nextMenu(self
, count
):
2392 self
.tk
.call('tk_nextMenu', count
)
2393 def tk_nextMenuEntry(self
, count
):
2394 self
.tk
.call('tk_nextMenuEntry', count
)
2395 def tk_invokeMenu(self
):
2396 self
.tk
.call('tk_invokeMenu', self
._w
)
2397 def tk_firstMenu(self
):
2398 self
.tk
.call('tk_firstMenu', self
._w
)
2399 def tk_mbButtonDown(self
):
2400 self
.tk
.call('tk_mbButtonDown', self
._w
)
2401 def tk_popup(self
, x
, y
, entry
=""):
2402 """Post the menu at position X,Y with entry ENTRY."""
2403 self
.tk
.call('tk_popup', self
._w
, x
, y
, entry
)
2404 def activate(self
, index
):
2405 """Activate entry at INDEX."""
2406 self
.tk
.call(self
._w
, 'activate', index
)
2407 def add(self
, itemType
, cnf
={}, **kw
):
2408 """Internal function."""
2409 self
.tk
.call((self
._w
, 'add', itemType
) +
2410 self
._options
(cnf
, kw
))
2411 def add_cascade(self
, cnf
={}, **kw
):
2412 """Add hierarchical menu item."""
2413 self
.add('cascade', cnf
or kw
)
2414 def add_checkbutton(self
, cnf
={}, **kw
):
2415 """Add checkbutton menu item."""
2416 self
.add('checkbutton', cnf
or kw
)
2417 def add_command(self
, cnf
={}, **kw
):
2418 """Add command menu item."""
2419 self
.add('command', cnf
or kw
)
2420 def add_radiobutton(self
, cnf
={}, **kw
):
2421 """Addd radio menu item."""
2422 self
.add('radiobutton', cnf
or kw
)
2423 def add_separator(self
, cnf
={}, **kw
):
2424 """Add separator."""
2425 self
.add('separator', cnf
or kw
)
2426 def insert(self
, index
, itemType
, cnf
={}, **kw
):
2427 """Internal function."""
2428 self
.tk
.call((self
._w
, 'insert', index
, itemType
) +
2429 self
._options
(cnf
, kw
))
2430 def insert_cascade(self
, index
, cnf
={}, **kw
):
2431 """Add hierarchical menu item at INDEX."""
2432 self
.insert(index
, 'cascade', cnf
or kw
)
2433 def insert_checkbutton(self
, index
, cnf
={}, **kw
):
2434 """Add checkbutton menu item at INDEX."""
2435 self
.insert(index
, 'checkbutton', cnf
or kw
)
2436 def insert_command(self
, index
, cnf
={}, **kw
):
2437 """Add command menu item at INDEX."""
2438 self
.insert(index
, 'command', cnf
or kw
)
2439 def insert_radiobutton(self
, index
, cnf
={}, **kw
):
2440 """Addd radio menu item at INDEX."""
2441 self
.insert(index
, 'radiobutton', cnf
or kw
)
2442 def insert_separator(self
, index
, cnf
={}, **kw
):
2443 """Add separator at INDEX."""
2444 self
.insert(index
, 'separator', cnf
or kw
)
2445 def delete(self
, index1
, index2
=None):
2446 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2447 self
.tk
.call(self
._w
, 'delete', index1
, index2
)
2448 def entrycget(self
, index
, option
):
2449 """Return the resource value of an menu item for OPTION at INDEX."""
2450 return self
.tk
.call(self
._w
, 'entrycget', index
, '-' + option
)
2451 def entryconfigure(self
, index
, cnf
=None, **kw
):
2452 """Configure a menu item at INDEX."""
2453 if cnf
is None and not kw
:
2455 for x
in self
.tk
.split(self
.tk
.call(
2456 (self
._w
, 'entryconfigure', index
))):
2457 cnf
[x
[0][1:]] = (x
[0][1:],) + x
[1:]
2459 if type(cnf
) == StringType
and not kw
:
2460 x
= self
.tk
.split(self
.tk
.call(
2461 (self
._w
, 'entryconfigure', index
, '-'+cnf
)))
2462 return (x
[0][1:],) + x
[1:]
2463 self
.tk
.call((self
._w
, 'entryconfigure', index
)
2464 + self
._options
(cnf
, kw
))
2465 entryconfig
= entryconfigure
2466 def index(self
, index
):
2467 """Return the index of a menu item identified by INDEX."""
2468 i
= self
.tk
.call(self
._w
, 'index', index
)
2469 if i
== 'none': return None
2471 def invoke(self
, index
):
2472 """Invoke a menu item identified by INDEX and execute
2473 the associated command."""
2474 return self
.tk
.call(self
._w
, 'invoke', index
)
2475 def post(self
, x
, y
):
2476 """Display a menu at position X,Y."""
2477 self
.tk
.call(self
._w
, 'post', x
, y
)
2478 def type(self
, index
):
2479 """Return the type of the menu item at INDEX."""
2480 return self
.tk
.call(self
._w
, 'type', index
)
2483 self
.tk
.call(self
._w
, 'unpost')
2484 def yposition(self
, index
):
2485 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2486 return getint(self
.tk
.call(
2487 self
._w
, 'yposition', index
))
2489 class Menubutton(Widget
):
2490 """Menubutton widget, obsolete since Tk8.0."""
2491 def __init__(self
, master
=None, cnf
={}, **kw
):
2492 Widget
.__init
__(self
, master
, 'menubutton', cnf
, kw
)
2494 class Message(Widget
):
2495 """Message widget to display multiline text. Obsolete since Label does it too."""
2496 def __init__(self
, master
=None, cnf
={}, **kw
):
2497 Widget
.__init
__(self
, master
, 'message', cnf
, kw
)
2499 class Radiobutton(Widget
):
2500 """Radiobutton widget which shows only one of several buttons in on-state."""
2501 def __init__(self
, master
=None, cnf
={}, **kw
):
2502 """Construct a radiobutton widget with the parent MASTER.
2504 Valid resource names: activebackground, activeforeground, anchor,
2505 background, bd, bg, bitmap, borderwidth, command, cursor,
2506 disabledforeground, fg, font, foreground, height,
2507 highlightbackground, highlightcolor, highlightthickness, image,
2508 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2509 state, takefocus, text, textvariable, underline, value, variable,
2510 width, wraplength."""
2511 Widget
.__init
__(self
, master
, 'radiobutton', cnf
, kw
)
2513 """Put the button in off-state."""
2515 self
.tk
.call(self
._w
, 'deselect')
2517 """Flash the button."""
2518 self
.tk
.call(self
._w
, 'flash')
2520 """Toggle the button and invoke a command if given as resource."""
2521 return self
.tk
.call(self
._w
, 'invoke')
2523 """Put the button in on-state."""
2524 self
.tk
.call(self
._w
, 'select')
2526 class Scale(Widget
):
2527 """Scale widget which can display a numerical scale."""
2528 def __init__(self
, master
=None, cnf
={}, **kw
):
2529 """Construct a scale widget with the parent MASTER.
2531 Valid resource names: activebackground, background, bigincrement, bd,
2532 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2533 highlightbackground, highlightcolor, highlightthickness, label,
2534 length, orient, relief, repeatdelay, repeatinterval, resolution,
2535 showvalue, sliderlength, sliderrelief, state, takefocus,
2536 tickinterval, to, troughcolor, variable, width."""
2537 Widget
.__init
__(self
, master
, 'scale', cnf
, kw
)
2539 """Get the current value as integer or float."""
2540 value
= self
.tk
.call(self
._w
, 'get')
2542 return getint(value
)
2544 return getdouble(value
)
2545 def set(self
, value
):
2546 """Set the value to VALUE."""
2547 self
.tk
.call(self
._w
, 'set', value
)
2548 def coords(self
, value
=None):
2549 """Return a tuple (X,Y) of the point along the centerline of the
2550 trough that corresponds to VALUE or the current value if None is
2553 return self
._getints
(self
.tk
.call(self
._w
, 'coords', value
))
2554 def identify(self
, x
, y
):
2555 """Return where the point X,Y lies. Valid return values are "slider",
2556 "though1" and "though2"."""
2557 return self
.tk
.call(self
._w
, 'identify', x
, y
)
2559 class Scrollbar(Widget
):
2560 """Scrollbar widget which displays a slider at a certain position."""
2561 def __init__(self
, master
=None, cnf
={}, **kw
):
2562 """Construct a scrollbar widget with the parent MASTER.
2564 Valid resource names: activebackground, activerelief,
2565 background, bd, bg, borderwidth, command, cursor,
2566 elementborderwidth, highlightbackground,
2567 highlightcolor, highlightthickness, jump, orient,
2568 relief, repeatdelay, repeatinterval, takefocus,
2569 troughcolor, width."""
2570 Widget
.__init
__(self
, master
, 'scrollbar', cnf
, kw
)
2571 def activate(self
, index
):
2572 """Display the element at INDEX with activebackground and activerelief.
2573 INDEX can be "arrow1","slider" or "arrow2"."""
2574 self
.tk
.call(self
._w
, 'activate', index
)
2575 def delta(self
, deltax
, deltay
):
2576 """Return the fractional change of the scrollbar setting if it
2577 would be moved by DELTAX or DELTAY pixels."""
2579 self
.tk
.call(self
._w
, 'delta', deltax
, deltay
))
2580 def fraction(self
, x
, y
):
2581 """Return the fractional value which corresponds to a slider
2583 return getdouble(self
.tk
.call(self
._w
, 'fraction', x
, y
))
2584 def identify(self
, x
, y
):
2585 """Return the element under position X,Y as one of
2586 "arrow1","slider","arrow2" or ""."""
2587 return self
.tk
.call(self
._w
, 'identify', x
, y
)
2589 """Return the current fractional values (upper and lower end)
2590 of the slider position."""
2591 return self
._getdoubles
(self
.tk
.call(self
._w
, 'get'))
2592 def set(self
, *args
):
2593 """Set the fractional values of the slider position (upper and
2594 lower ends as value between 0 and 1)."""
2595 self
.tk
.call((self
._w
, 'set') + args
)
2598 """Text widget which can display text in various forms."""
2600 def __init__(self
, master
=None, cnf
={}, **kw
):
2601 """Construct a text widget with the parent MASTER.
2603 Valid resource names: background, bd, bg, borderwidth, cursor,
2604 exportselection, fg, font, foreground, height,
2605 highlightbackground, highlightcolor, highlightthickness,
2606 insertbackground, insertborderwidth, insertofftime,
2607 insertontime, insertwidth, padx, pady, relief,
2608 selectbackground, selectborderwidth, selectforeground,
2609 setgrid, spacing1, spacing2, spacing3, state, tabs, takefocus,
2610 width, wrap, xscrollcommand, yscrollcommand."""
2611 Widget
.__init
__(self
, master
, 'text', cnf
, kw
)
2612 def bbox(self
, *args
):
2613 """Return a tuple of (x,y,width,height) which gives the bounding
2614 box of the visible part of the character at the index in ARGS."""
2615 return self
._getints
(
2616 self
.tk
.call((self
._w
, 'bbox') + args
)) or None
2617 def tk_textSelectTo(self
, index
):
2618 self
.tk
.call('tk_textSelectTo', self
._w
, index
)
2619 def tk_textBackspace(self
):
2620 self
.tk
.call('tk_textBackspace', self
._w
)
2621 def tk_textIndexCloser(self
, a
, b
, c
):
2622 self
.tk
.call('tk_textIndexCloser', self
._w
, a
, b
, c
)
2623 def tk_textResetAnchor(self
, index
):
2624 self
.tk
.call('tk_textResetAnchor', self
._w
, index
)
2625 def compare(self
, index1
, op
, index2
):
2626 """Return whether between index INDEX1 and index INDEX2 the
2627 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2628 return self
.tk
.getboolean(self
.tk
.call(
2629 self
._w
, 'compare', index1
, op
, index2
))
2630 def debug(self
, boolean
=None):
2631 """Turn on the internal consistency checks of the B-Tree inside the text
2632 widget according to BOOLEAN."""
2633 return self
.tk
.getboolean(self
.tk
.call(
2634 self
._w
, 'debug', boolean
))
2635 def delete(self
, index1
, index2
=None):
2636 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2637 self
.tk
.call(self
._w
, 'delete', index1
, index2
)
2638 def dlineinfo(self
, index
):
2639 """Return tuple (x,y,width,height,baseline) giving the bounding box
2640 and baseline position of the visible part of the line containing
2641 the character at INDEX."""
2642 return self
._getints
(self
.tk
.call(self
._w
, 'dlineinfo', index
))
2643 def get(self
, index1
, index2
=None):
2644 """Return the text from INDEX1 to INDEX2 (not included)."""
2645 return self
.tk
.call(self
._w
, 'get', index1
, index2
)
2646 # (Image commands are new in 8.0)
2647 def image_cget(self
, index
, option
):
2648 """Return the value of OPTION of an embedded image at INDEX."""
2649 if option
[:1] != "-":
2650 option
= "-" + option
2651 if option
[-1:] == "_":
2652 option
= option
[:-1]
2653 return self
.tk
.call(self
._w
, "image", "cget", index
, option
)
2654 def image_configure(self
, index
, cnf
={}, **kw
):
2655 """Configure an embedded image at INDEX."""
2656 if not cnf
and not kw
:
2658 for x
in self
.tk
.split(
2660 self
._w
, "image", "configure", index
)):
2661 cnf
[x
[0][1:]] = (x
[0][1:],) + x
[1:]
2664 (self
._w
, "image", "configure", index
)
2665 + self
._options
(cnf
, kw
))
2666 def image_create(self
, index
, cnf
={}, **kw
):
2667 """Create an embedded image at INDEX."""
2668 return apply(self
.tk
.call
,
2669 (self
._w
, "image", "create", index
)
2670 + self
._options
(cnf
, kw
))
2671 def image_names(self
):
2672 """Return all names of embedded images in this widget."""
2673 return self
.tk
.call(self
._w
, "image", "names")
2674 def index(self
, index
):
2675 """Return the index in the form line.char for INDEX."""
2676 return self
.tk
.call(self
._w
, 'index', index
)
2677 def insert(self
, index
, chars
, *args
):
2678 """Insert CHARS before the characters at INDEX. An additional
2679 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2680 self
.tk
.call((self
._w
, 'insert', index
, chars
) + args
)
2681 def mark_gravity(self
, markName
, direction
=None):
2682 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2683 Return the current value if None is given for DIRECTION."""
2684 return self
.tk
.call(
2685 (self
._w
, 'mark', 'gravity', markName
, direction
))
2686 def mark_names(self
):
2687 """Return all mark names."""
2688 return self
.tk
.splitlist(self
.tk
.call(
2689 self
._w
, 'mark', 'names'))
2690 def mark_set(self
, markName
, index
):
2691 """Set mark MARKNAME before the character at INDEX."""
2692 self
.tk
.call(self
._w
, 'mark', 'set', markName
, index
)
2693 def mark_unset(self
, *markNames
):
2694 """Delete all marks in MARKNAMES."""
2695 self
.tk
.call((self
._w
, 'mark', 'unset') + markNames
)
2696 def mark_next(self
, index
):
2697 """Return the name of the next mark after INDEX."""
2698 return self
.tk
.call(self
._w
, 'mark', 'next', index
) or None
2699 def mark_previous(self
, index
):
2700 """Return the name of the previous mark before INDEX."""
2701 return self
.tk
.call(self
._w
, 'mark', 'previous', index
) or None
2702 def scan_mark(self
, x
, y
):
2703 """Remember the current X, Y coordinates."""
2704 self
.tk
.call(self
._w
, 'scan', 'mark', x
, y
)
2705 def scan_dragto(self
, x
, y
):
2706 """Adjust the view of the text to 10 times the
2707 difference between X and Y and the coordinates given in
2709 self
.tk
.call(self
._w
, 'scan', 'dragto', x
, y
)
2710 def search(self
, pattern
, index
, stopindex
=None,
2711 forwards
=None, backwards
=None, exact
=None,
2712 regexp
=None, nocase
=None, count
=None):
2713 """Search PATTERN beginning from INDEX until STOPINDEX.
2714 Return the index of the first character of a match or an empty string."""
2715 args
= [self
._w
, 'search']
2716 if forwards
: args
.append('-forwards')
2717 if backwards
: args
.append('-backwards')
2718 if exact
: args
.append('-exact')
2719 if regexp
: args
.append('-regexp')
2720 if nocase
: args
.append('-nocase')
2721 if count
: args
.append('-count'); args
.append(count
)
2722 if pattern
[0] == '-': args
.append('--')
2723 args
.append(pattern
)
2725 if stopindex
: args
.append(stopindex
)
2726 return self
.tk
.call(tuple(args
))
2727 def see(self
, index
):
2728 """Scroll such that the character at INDEX is visible."""
2729 self
.tk
.call(self
._w
, 'see', index
)
2730 def tag_add(self
, tagName
, index1
, *args
):
2731 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2732 Additional pairs of indices may follow in ARGS."""
2734 (self
._w
, 'tag', 'add', tagName
, index1
) + args
)
2735 def tag_unbind(self
, tagName
, sequence
, funcid
=None):
2736 """Unbind for all characters with TAGNAME for event SEQUENCE the
2737 function identified with FUNCID."""
2738 self
.tk
.call(self
._w
, 'tag', 'bind', tagName
, sequence
, '')
2740 self
.deletecommand(funcid
)
2741 def tag_bind(self
, tagName
, sequence
, func
, add
=None):
2742 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
2744 An additional boolean parameter ADD specifies whether FUNC will be
2745 called additionally to the other bound function or whether it will
2746 replace the previous function. See bind for the return value."""
2747 return self
._bind
((self
._w
, 'tag', 'bind', tagName
),
2748 sequence
, func
, add
)
2749 def tag_cget(self
, tagName
, option
):
2750 """Return the value of OPTION for tag TAGNAME."""
2751 if option
[:1] != '-':
2752 option
= '-' + option
2753 if option
[-1:] == '_':
2754 option
= option
[:-1]
2755 return self
.tk
.call(self
._w
, 'tag', 'cget', tagName
, option
)
2756 def tag_configure(self
, tagName
, cnf
={}, **kw
):
2757 """Configure a tag TAGNAME."""
2758 if type(cnf
) == StringType
:
2759 x
= self
.tk
.split(self
.tk
.call(
2760 self
._w
, 'tag', 'configure', tagName
, '-'+cnf
))
2761 return (x
[0][1:],) + x
[1:]
2763 (self
._w
, 'tag', 'configure', tagName
)
2764 + self
._options
(cnf
, kw
))
2765 tag_config
= tag_configure
2766 def tag_delete(self
, *tagNames
):
2767 """Delete all tags in TAGNAMES."""
2768 self
.tk
.call((self
._w
, 'tag', 'delete') + tagNames
)
2769 def tag_lower(self
, tagName
, belowThis
=None):
2770 """Change the priority of tag TAGNAME such that it is lower
2771 than the priority of BELOWTHIS."""
2772 self
.tk
.call(self
._w
, 'tag', 'lower', tagName
, belowThis
)
2773 def tag_names(self
, index
=None):
2774 """Return a list of all tag names."""
2775 return self
.tk
.splitlist(
2776 self
.tk
.call(self
._w
, 'tag', 'names', index
))
2777 def tag_nextrange(self
, tagName
, index1
, index2
=None):
2778 """Return a list of start and end index for the first sequence of
2779 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2780 The text is searched forward from INDEX1."""
2781 return self
.tk
.splitlist(self
.tk
.call(
2782 self
._w
, 'tag', 'nextrange', tagName
, index1
, index2
))
2783 def tag_prevrange(self
, tagName
, index1
, index2
=None):
2784 """Return a list of start and end index for the first sequence of
2785 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2786 The text is searched backwards from INDEX1."""
2787 return self
.tk
.splitlist(self
.tk
.call(
2788 self
._w
, 'tag', 'prevrange', tagName
, index1
, index2
))
2789 def tag_raise(self
, tagName
, aboveThis
=None):
2790 """Change the priority of tag TAGNAME such that it is higher
2791 than the priority of ABOVETHIS."""
2793 self
._w
, 'tag', 'raise', tagName
, aboveThis
)
2794 def tag_ranges(self
, tagName
):
2795 """Return a list of ranges of text which have tag TAGNAME."""
2796 return self
.tk
.splitlist(self
.tk
.call(
2797 self
._w
, 'tag', 'ranges', tagName
))
2798 def tag_remove(self
, tagName
, index1
, index2
=None):
2799 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2801 self
._w
, 'tag', 'remove', tagName
, index1
, index2
)
2802 def window_cget(self
, index
, option
):
2803 """Return the value of OPTION of an embedded window at INDEX."""
2804 if option
[:1] != '-':
2805 option
= '-' + option
2806 if option
[-1:] == '_':
2807 option
= option
[:-1]
2808 return self
.tk
.call(self
._w
, 'window', 'cget', index
, option
)
2809 def window_configure(self
, index
, cnf
={}, **kw
):
2810 """Configure an embedded window at INDEX."""
2811 if type(cnf
) == StringType
:
2812 x
= self
.tk
.split(self
.tk
.call(
2813 self
._w
, 'window', 'configure',
2815 return (x
[0][1:],) + x
[1:]
2817 (self
._w
, 'window', 'configure', index
)
2818 + self
._options
(cnf
, kw
))
2819 window_config
= window_configure
2820 def window_create(self
, index
, cnf
={}, **kw
):
2821 """Create a window at INDEX."""
2823 (self
._w
, 'window', 'create', index
)
2824 + self
._options
(cnf
, kw
))
2825 def window_names(self
):
2826 """Return all names of embedded windows in this widget."""
2827 return self
.tk
.splitlist(
2828 self
.tk
.call(self
._w
, 'window', 'names'))
2829 def xview(self
, *what
):
2830 """Query and change horizontal position of the view."""
2832 return self
._getdoubles
(self
.tk
.call(self
._w
, 'xview'))
2833 self
.tk
.call((self
._w
, 'xview') + what
)
2834 def xview_moveto(self
, fraction
):
2835 """Adjusts the view in the window so that FRACTION of the
2836 total width of the canvas is off-screen to the left."""
2837 self
.tk
.call(self
._w
, 'xview', 'moveto', fraction
)
2838 def xview_scroll(self
, number
, what
):
2839 """Shift the x-view according to NUMBER which is measured
2840 in "units" or "pages" (WHAT)."""
2841 self
.tk
.call(self
._w
, 'xview', 'scroll', number
, what
)
2842 def yview(self
, *what
):
2843 """Query and change vertical position of the view."""
2845 return self
._getdoubles
(self
.tk
.call(self
._w
, 'yview'))
2846 self
.tk
.call((self
._w
, 'yview') + what
)
2847 def yview_moveto(self
, fraction
):
2848 """Adjusts the view in the window so that FRACTION of the
2849 total height of the canvas is off-screen to the top."""
2850 self
.tk
.call(self
._w
, 'yview', 'moveto', fraction
)
2851 def yview_scroll(self
, number
, what
):
2852 """Shift the y-view according to NUMBER which is measured
2853 in "units" or "pages" (WHAT)."""
2854 self
.tk
.call(self
._w
, 'yview', 'scroll', number
, what
)
2855 def yview_pickplace(self
, *what
):
2856 """Obsolete function, use see."""
2857 self
.tk
.call((self
._w
, 'yview', '-pickplace') + what
)
2860 """Internal class. It wraps the command in the widget OptionMenu."""
2861 def __init__(self
, var
, value
, callback
=None):
2862 self
.__value
= value
2864 self
.__callback
= callback
2865 def __call__(self
, *args
):
2866 self
.__var
.set(self
.__value
)
2868 apply(self
.__callback
, (self
.__value
,)+args
)
2870 class OptionMenu(Menubutton
):
2871 """OptionMenu which allows the user to select a value from a menu."""
2872 def __init__(self
, master
, variable
, value
, *values
, **kwargs
):
2873 """Construct an optionmenu widget with the parent MASTER, with
2874 the resource textvariable set to VARIABLE, the initially selected
2875 value VALUE, the other menu values VALUES and an additional
2876 keyword argument command."""
2877 kw
= {"borderwidth": 2, "textvariable": variable
,
2878 "indicatoron": 1, "relief": RAISED
, "anchor": "c",
2879 "highlightthickness": 2}
2880 Widget
.__init
__(self
, master
, "menubutton", kw
)
2881 self
.widgetName
= 'tk_optionMenu'
2882 menu
= self
.__menu
= Menu(self
, name
="menu", tearoff
=0)
2883 self
.menuname
= menu
._w
2884 # 'command' is the only supported keyword
2885 callback
= kwargs
.get('command')
2886 if kwargs
.has_key('command'):
2887 del kwargs
['command']
2889 raise TclError
, 'unknown option -'+kwargs
.keys()[0]
2890 menu
.add_command(label
=value
,
2891 command
=_setit(variable
, value
, callback
))
2893 menu
.add_command(label
=v
,
2894 command
=_setit(variable
, v
, callback
))
2897 def __getitem__(self
, name
):
2900 return Widget
.__getitem
__(self
, name
)
2903 """Destroy this widget and the associated menu."""
2904 Menubutton
.destroy(self
)
2908 """Base class for images."""
2910 def __init__(self
, imgtype
, name
=None, cnf
={}, master
=None, **kw
):
2913 master
= _default_root
2915 raise RuntimeError, 'Too early to create image'
2919 name
= "pyimage" +`Image
._last
_id`
# tk itself would use image<x>
2920 # The following is needed for systems where id(x)
2921 # can return a negative number, such as Linux/m68k:
2922 if name
[0] == '-': name
= '_' + name
[1:]
2923 if kw
and cnf
: cnf
= _cnfmerge((cnf
, kw
))
2926 for k
, v
in cnf
.items():
2928 v
= self
._register
(v
)
2929 options
= options
+ ('-'+k
, v
)
2930 self
.tk
.call(('image', 'create', imgtype
, name
,) + options
)
2932 def __str__(self
): return self
.name
2936 self
.tk
.call('image', 'delete', self
.name
)
2938 # May happen if the root was destroyed
2940 def __setitem__(self
, key
, value
):
2941 self
.tk
.call(self
.name
, 'configure', '-'+key
, value
)
2942 def __getitem__(self
, key
):
2943 return self
.tk
.call(self
.name
, 'configure', '-'+key
)
2944 def configure(self
, **kw
):
2945 """Configure the image."""
2947 for k
, v
in _cnfmerge(kw
).items():
2949 if k
[-1] == '_': k
= k
[:-1]
2951 v
= self
._register
(v
)
2952 res
= res
+ ('-'+k
, v
)
2953 self
.tk
.call((self
.name
, 'config') + res
)
2956 """Return the height of the image."""
2958 self
.tk
.call('image', 'height', self
.name
))
2960 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
2961 return self
.tk
.call('image', 'type', self
.name
)
2963 """Return the width of the image."""
2965 self
.tk
.call('image', 'width', self
.name
))
2967 class PhotoImage(Image
):
2968 """Widget which can display colored images in GIF, PPM/PGM format."""
2969 def __init__(self
, name
=None, cnf
={}, master
=None, **kw
):
2970 """Create an image with NAME.
2972 Valid resource names: data, format, file, gamma, height, palette,
2974 apply(Image
.__init
__, (self
, 'photo', name
, cnf
, master
), kw
)
2976 """Display a transparent image."""
2977 self
.tk
.call(self
.name
, 'blank')
2978 def cget(self
, option
):
2979 """Return the value of OPTION."""
2980 return self
.tk
.call(self
.name
, 'cget', '-' + option
)
2982 def __getitem__(self
, key
):
2983 return self
.tk
.call(self
.name
, 'cget', '-' + key
)
2984 # XXX copy -from, -to, ...?
2986 """Return a new PhotoImage with the same image as this widget."""
2987 destImage
= PhotoImage()
2988 self
.tk
.call(destImage
, 'copy', self
.name
)
2990 def zoom(self
,x
,y
=''):
2991 """Return a new PhotoImage with the same image as this widget
2992 but zoom it with X and Y."""
2993 destImage
= PhotoImage()
2995 self
.tk
.call(destImage
, 'copy', self
.name
, '-zoom',x
,y
)
2997 def subsample(self
,x
,y
=''):
2998 """Return a new PhotoImage based on the same image as this widget
2999 but use only every Xth or Yth pixel."""
3000 destImage
= PhotoImage()
3002 self
.tk
.call(destImage
, 'copy', self
.name
, '-subsample',x
,y
)
3004 def get(self
, x
, y
):
3005 """Return the color (red, green, blue) of the pixel at X,Y."""
3006 return self
.tk
.call(self
.name
, 'get', x
, y
)
3007 def put(self
, data
, to
=None):
3008 """Put row formated colors to image starting from
3009 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3010 args
= (self
.name
, 'put', data
)
3014 args
= args
+ ('-to',) + tuple(to
)
3017 def write(self
, filename
, format
=None, from_coords
=None):
3018 """Write image to file FILENAME in FORMAT starting from
3019 position FROM_COORDS."""
3020 args
= (self
.name
, 'write', filename
)
3022 args
= args
+ ('-format', format
)
3024 args
= args
+ ('-from',) + tuple(from_coords
)
3027 class BitmapImage(Image
):
3028 """Widget which can display a bitmap."""
3029 def __init__(self
, name
=None, cnf
={}, master
=None, **kw
):
3030 """Create a bitmap with NAME.
3032 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3033 apply(Image
.__init
__, (self
, 'bitmap', name
, cnf
, master
), kw
)
3035 def image_names(): return _default_root
.tk
.call('image', 'names')
3036 def image_types(): return _default_root
.tk
.call('image', 'types')
3038 ######################################################################
3041 class Studbutton(Button
):
3042 def __init__(self
, master
=None, cnf
={}, **kw
):
3043 Widget
.__init
__(self
, master
, 'studbutton', cnf
, kw
)
3044 self
.bind('<Any-Enter>', self
.tkButtonEnter
)
3045 self
.bind('<Any-Leave>', self
.tkButtonLeave
)
3046 self
.bind('<1>', self
.tkButtonDown
)
3047 self
.bind('<ButtonRelease-1>', self
.tkButtonUp
)
3049 class Tributton(Button
):
3050 def __init__(self
, master
=None, cnf
={}, **kw
):
3051 Widget
.__init
__(self
, master
, 'tributton', cnf
, kw
)
3052 self
.bind('<Any-Enter>', self
.tkButtonEnter
)
3053 self
.bind('<Any-Leave>', self
.tkButtonLeave
)
3054 self
.bind('<1>', self
.tkButtonDown
)
3055 self
.bind('<ButtonRelease-1>', self
.tkButtonUp
)
3056 self
['fg'] = self
['bg']
3057 self
['activebackground'] = self
['bg']
3059 ######################################################################
3064 text
= "This is Tcl/Tk version %s" % TclVersion
3065 if TclVersion
>= 8.1:
3067 text
= text
+ unicode("\nThis should be a cedilla: \347",
3070 pass # no unicode support
3071 label
= Label(root
, text
=text
)
3073 test
= Button(root
, text
="Click me!",
3074 command
=lambda root
=root
: root
.test
.configure(
3075 text
="[%s]" % root
.test
['text']))
3078 quit
= Button(root
, text
="QUIT", command
=root
.destroy
)
3080 # The following three commands are needed so the window pops
3081 # up on top on Windows...
3087 if __name__
== '__main__':