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