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