blob: cec31fd9ab12bd2eabfb78303c336e47d9420e22 [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()
Antoine Pitrou7dddec42012-12-09 14:46:18 +01001712 if not sys.flags.ignore_environment:
1713 # Issue #16248: Honor the -E flag to avoid code injection.
1714 self.readprofile(baseName, className)
Georg Brandl33cece02008-05-20 06:58:21 +00001715 def loadtk(self):
1716 if not self._tkloaded:
1717 self.tk.loadtk()
1718 self._loadtk()
1719 def _loadtk(self):
1720 self._tkloaded = 1
1721 global _default_root
Georg Brandl33cece02008-05-20 06:58:21 +00001722 # Version sanity checks
1723 tk_version = self.tk.getvar('tk_version')
1724 if tk_version != _tkinter.TK_VERSION:
1725 raise RuntimeError, \
1726 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1727 % (_tkinter.TK_VERSION, tk_version)
1728 # Under unknown circumstances, tcl_version gets coerced to float
1729 tcl_version = str(self.tk.getvar('tcl_version'))
1730 if tcl_version != _tkinter.TCL_VERSION:
1731 raise RuntimeError, \
1732 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1733 % (_tkinter.TCL_VERSION, tcl_version)
1734 if TkVersion < 4.0:
1735 raise RuntimeError, \
1736 "Tk 4.0 or higher is required; found Tk %s" \
1737 % str(TkVersion)
1738 # Create and register the tkerror and exit commands
1739 # We need to inline parts of _register here, _ register
1740 # would register differently-named commands.
1741 if self._tclCommands is None:
1742 self._tclCommands = []
1743 self.tk.createcommand('tkerror', _tkerror)
1744 self.tk.createcommand('exit', _exit)
1745 self._tclCommands.append('tkerror')
1746 self._tclCommands.append('exit')
1747 if _support_default_root and not _default_root:
1748 _default_root = self
1749 self.protocol("WM_DELETE_WINDOW", self.destroy)
1750 def destroy(self):
1751 """Destroy this and all descendants widgets. This will
1752 end the application of this Tcl interpreter."""
1753 for c in self.children.values(): c.destroy()
1754 self.tk.call('destroy', self._w)
1755 Misc.destroy(self)
1756 global _default_root
1757 if _support_default_root and _default_root is self:
1758 _default_root = None
1759 def readprofile(self, baseName, className):
1760 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1761 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1762 such a file exists in the home directory."""
1763 import os
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00001764 if 'HOME' in os.environ: home = os.environ['HOME']
Georg Brandl33cece02008-05-20 06:58:21 +00001765 else: home = os.curdir
1766 class_tcl = os.path.join(home, '.%s.tcl' % className)
1767 class_py = os.path.join(home, '.%s.py' % className)
1768 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1769 base_py = os.path.join(home, '.%s.py' % baseName)
1770 dir = {'self': self}
Georg Brandl6634bf22008-05-20 07:13:37 +00001771 exec 'from Tkinter import *' in dir
Georg Brandl33cece02008-05-20 06:58:21 +00001772 if os.path.isfile(class_tcl):
1773 self.tk.call('source', class_tcl)
1774 if os.path.isfile(class_py):
1775 execfile(class_py, dir)
1776 if os.path.isfile(base_tcl):
1777 self.tk.call('source', base_tcl)
1778 if os.path.isfile(base_py):
1779 execfile(base_py, dir)
1780 def report_callback_exception(self, exc, val, tb):
1781 """Internal function. It reports exception on sys.stderr."""
1782 import traceback, sys
1783 sys.stderr.write("Exception in Tkinter callback\n")
1784 sys.last_type = exc
1785 sys.last_value = val
1786 sys.last_traceback = tb
1787 traceback.print_exception(exc, val, tb)
1788 def __getattr__(self, attr):
1789 "Delegate attribute access to the interpreter object"
1790 return getattr(self.tk, attr)
1791
1792# Ideally, the classes Pack, Place and Grid disappear, the
1793# pack/place/grid methods are defined on the Widget class, and
1794# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1795# ...), with pack(), place() and grid() being short for
1796# pack_configure(), place_configure() and grid_columnconfigure(), and
1797# forget() being short for pack_forget(). As a practical matter, I'm
1798# afraid that there is too much code out there that may be using the
1799# Pack, Place or Grid class, so I leave them intact -- but only as
1800# backwards compatibility features. Also note that those methods that
1801# take a master as argument (e.g. pack_propagate) have been moved to
1802# the Misc class (which now incorporates all methods common between
1803# toplevel and interior widgets). Again, for compatibility, these are
1804# copied into the Pack, Place or Grid class.
1805
1806
1807def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1808 return Tk(screenName, baseName, className, useTk)
1809
1810class Pack:
1811 """Geometry manager Pack.
1812
1813 Base class to use the methods pack_* in every widget."""
1814 def pack_configure(self, cnf={}, **kw):
1815 """Pack a widget in the parent widget. Use as options:
1816 after=widget - pack it after you have packed widget
1817 anchor=NSEW (or subset) - position widget according to
1818 given direction
Georg Brandl7943a322008-05-29 07:18:49 +00001819 before=widget - pack it before you will pack widget
Georg Brandl33cece02008-05-20 06:58:21 +00001820 expand=bool - expand widget if parent size grows
1821 fill=NONE or X or Y or BOTH - fill widget if widget grows
1822 in=master - use master to contain this widget
Georg Brandl7943a322008-05-29 07:18:49 +00001823 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001824 ipadx=amount - add internal padding in x direction
1825 ipady=amount - add internal padding in y direction
1826 padx=amount - add padding in x direction
1827 pady=amount - add padding in y direction
1828 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1829 """
1830 self.tk.call(
1831 ('pack', 'configure', self._w)
1832 + self._options(cnf, kw))
1833 pack = configure = config = pack_configure
1834 def pack_forget(self):
1835 """Unmap this widget and do not use it for the packing order."""
1836 self.tk.call('pack', 'forget', self._w)
1837 forget = pack_forget
1838 def pack_info(self):
1839 """Return information about the packing options
1840 for this widget."""
1841 words = self.tk.splitlist(
1842 self.tk.call('pack', 'info', self._w))
1843 dict = {}
1844 for i in range(0, len(words), 2):
1845 key = words[i][1:]
1846 value = words[i+1]
1847 if value[:1] == '.':
1848 value = self._nametowidget(value)
1849 dict[key] = value
1850 return dict
1851 info = pack_info
1852 propagate = pack_propagate = Misc.pack_propagate
1853 slaves = pack_slaves = Misc.pack_slaves
1854
1855class Place:
1856 """Geometry manager Place.
1857
1858 Base class to use the methods place_* in every widget."""
1859 def place_configure(self, cnf={}, **kw):
1860 """Place a widget in the parent widget. Use as options:
Georg Brandl7943a322008-05-29 07:18:49 +00001861 in=master - master relative to which the widget is placed
1862 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001863 x=amount - locate anchor of this widget at position x of master
1864 y=amount - locate anchor of this widget at position y of master
1865 relx=amount - locate anchor of this widget between 0.0 and 1.0
1866 relative to width of master (1.0 is right edge)
Georg Brandl7943a322008-05-29 07:18:49 +00001867 rely=amount - locate anchor of this widget between 0.0 and 1.0
Georg Brandl33cece02008-05-20 06:58:21 +00001868 relative to height of master (1.0 is bottom edge)
Georg Brandl7943a322008-05-29 07:18:49 +00001869 anchor=NSEW (or subset) - position anchor according to given direction
Georg Brandl33cece02008-05-20 06:58:21 +00001870 width=amount - width of this widget in pixel
1871 height=amount - height of this widget in pixel
1872 relwidth=amount - width of this widget between 0.0 and 1.0
1873 relative to width of master (1.0 is the same width
Georg Brandl7943a322008-05-29 07:18:49 +00001874 as the master)
1875 relheight=amount - height of this widget between 0.0 and 1.0
Georg Brandl33cece02008-05-20 06:58:21 +00001876 relative to height of master (1.0 is the same
Georg Brandl7943a322008-05-29 07:18:49 +00001877 height as the master)
1878 bordermode="inside" or "outside" - whether to take border width of
1879 master widget into account
1880 """
Georg Brandl33cece02008-05-20 06:58:21 +00001881 self.tk.call(
1882 ('place', 'configure', self._w)
1883 + self._options(cnf, kw))
1884 place = configure = config = place_configure
1885 def place_forget(self):
1886 """Unmap this widget."""
1887 self.tk.call('place', 'forget', self._w)
1888 forget = place_forget
1889 def place_info(self):
1890 """Return information about the placing options
1891 for this widget."""
1892 words = self.tk.splitlist(
1893 self.tk.call('place', 'info', self._w))
1894 dict = {}
1895 for i in range(0, len(words), 2):
1896 key = words[i][1:]
1897 value = words[i+1]
1898 if value[:1] == '.':
1899 value = self._nametowidget(value)
1900 dict[key] = value
1901 return dict
1902 info = place_info
1903 slaves = place_slaves = Misc.place_slaves
1904
1905class Grid:
1906 """Geometry manager Grid.
1907
1908 Base class to use the methods grid_* in every widget."""
1909 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1910 def grid_configure(self, cnf={}, **kw):
1911 """Position a widget in the parent widget in a grid. Use as options:
1912 column=number - use cell identified with given column (starting with 0)
1913 columnspan=number - this widget will span several columns
1914 in=master - use master to contain this widget
Georg Brandl7943a322008-05-29 07:18:49 +00001915 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001916 ipadx=amount - add internal padding in x direction
1917 ipady=amount - add internal padding in y direction
1918 padx=amount - add padding in x direction
1919 pady=amount - add padding in y direction
1920 row=number - use cell identified with given row (starting with 0)
1921 rowspan=number - this widget will span several rows
1922 sticky=NSEW - if cell is larger on which sides will this
1923 widget stick to the cell boundary
1924 """
1925 self.tk.call(
1926 ('grid', 'configure', self._w)
1927 + self._options(cnf, kw))
1928 grid = configure = config = grid_configure
1929 bbox = grid_bbox = Misc.grid_bbox
1930 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1931 def grid_forget(self):
1932 """Unmap this widget."""
1933 self.tk.call('grid', 'forget', self._w)
1934 forget = grid_forget
1935 def grid_remove(self):
1936 """Unmap this widget but remember the grid options."""
1937 self.tk.call('grid', 'remove', self._w)
1938 def grid_info(self):
1939 """Return information about the options
1940 for positioning this widget in a grid."""
1941 words = self.tk.splitlist(
1942 self.tk.call('grid', 'info', self._w))
1943 dict = {}
1944 for i in range(0, len(words), 2):
1945 key = words[i][1:]
1946 value = words[i+1]
1947 if value[:1] == '.':
1948 value = self._nametowidget(value)
1949 dict[key] = value
1950 return dict
1951 info = grid_info
1952 location = grid_location = Misc.grid_location
1953 propagate = grid_propagate = Misc.grid_propagate
1954 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1955 size = grid_size = Misc.grid_size
1956 slaves = grid_slaves = Misc.grid_slaves
1957
1958class BaseWidget(Misc):
1959 """Internal class."""
1960 def _setup(self, master, cnf):
1961 """Internal function. Sets up information about children."""
1962 if _support_default_root:
1963 global _default_root
1964 if not master:
1965 if not _default_root:
1966 _default_root = Tk()
1967 master = _default_root
1968 self.master = master
1969 self.tk = master.tk
1970 name = None
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00001971 if 'name' in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00001972 name = cnf['name']
1973 del cnf['name']
1974 if not name:
1975 name = repr(id(self))
1976 self._name = name
1977 if master._w=='.':
1978 self._w = '.' + name
1979 else:
1980 self._w = master._w + '.' + name
1981 self.children = {}
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00001982 if self._name in self.master.children:
Georg Brandl33cece02008-05-20 06:58:21 +00001983 self.master.children[self._name].destroy()
1984 self.master.children[self._name] = self
1985 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1986 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1987 and appropriate options."""
1988 if kw:
1989 cnf = _cnfmerge((cnf, kw))
1990 self.widgetName = widgetName
1991 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotob9828f62008-11-03 18:03:06 +00001992 if self._tclCommands is None:
1993 self._tclCommands = []
Georg Brandl33cece02008-05-20 06:58:21 +00001994 classes = []
1995 for k in cnf.keys():
1996 if type(k) is ClassType:
1997 classes.append((k, cnf[k]))
1998 del cnf[k]
1999 self.tk.call(
2000 (widgetName, self._w) + extra + self._options(cnf))
2001 for k, v in classes:
2002 k.configure(self, v)
2003 def destroy(self):
2004 """Destroy this and all descendants widgets."""
2005 for c in self.children.values(): c.destroy()
2006 self.tk.call('destroy', self._w)
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002007 if self._name in self.master.children:
Georg Brandl33cece02008-05-20 06:58:21 +00002008 del self.master.children[self._name]
2009 Misc.destroy(self)
2010 def _do(self, name, args=()):
2011 # XXX Obsolete -- better use self.tk.call directly!
2012 return self.tk.call((self._w, name) + args)
2013
2014class Widget(BaseWidget, Pack, Place, Grid):
2015 """Internal class.
2016
2017 Base class for a widget which can be positioned with the geometry managers
2018 Pack, Place or Grid."""
2019 pass
2020
2021class Toplevel(BaseWidget, Wm):
2022 """Toplevel widget, e.g. for dialogs."""
2023 def __init__(self, master=None, cnf={}, **kw):
2024 """Construct a toplevel widget with the parent MASTER.
2025
2026 Valid resource names: background, bd, bg, borderwidth, class,
2027 colormap, container, cursor, height, highlightbackground,
2028 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2029 use, visual, width."""
2030 if kw:
2031 cnf = _cnfmerge((cnf, kw))
2032 extra = ()
2033 for wmkey in ['screen', 'class_', 'class', 'visual',
2034 'colormap']:
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002035 if wmkey in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002036 val = cnf[wmkey]
2037 # TBD: a hack needed because some keys
2038 # are not valid as keyword arguments
2039 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2040 else: opt = '-'+wmkey
2041 extra = extra + (opt, val)
2042 del cnf[wmkey]
2043 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2044 root = self._root()
2045 self.iconname(root.iconname())
2046 self.title(root.title())
2047 self.protocol("WM_DELETE_WINDOW", self.destroy)
2048
2049class Button(Widget):
2050 """Button widget."""
2051 def __init__(self, master=None, cnf={}, **kw):
2052 """Construct a button widget with the parent MASTER.
2053
2054 STANDARD OPTIONS
2055
2056 activebackground, activeforeground, anchor,
2057 background, bitmap, borderwidth, cursor,
2058 disabledforeground, font, foreground
2059 highlightbackground, highlightcolor,
2060 highlightthickness, image, justify,
2061 padx, pady, relief, repeatdelay,
2062 repeatinterval, takefocus, text,
2063 textvariable, underline, wraplength
2064
2065 WIDGET-SPECIFIC OPTIONS
2066
2067 command, compound, default, height,
2068 overrelief, state, width
2069 """
2070 Widget.__init__(self, master, 'button', cnf, kw)
2071
2072 def tkButtonEnter(self, *dummy):
2073 self.tk.call('tkButtonEnter', self._w)
2074
2075 def tkButtonLeave(self, *dummy):
2076 self.tk.call('tkButtonLeave', self._w)
2077
2078 def tkButtonDown(self, *dummy):
2079 self.tk.call('tkButtonDown', self._w)
2080
2081 def tkButtonUp(self, *dummy):
2082 self.tk.call('tkButtonUp', self._w)
2083
2084 def tkButtonInvoke(self, *dummy):
2085 self.tk.call('tkButtonInvoke', self._w)
2086
2087 def flash(self):
2088 """Flash the button.
2089
2090 This is accomplished by redisplaying
2091 the button several times, alternating between active and
2092 normal colors. At the end of the flash the button is left
2093 in the same normal/active state as when the command was
2094 invoked. This command is ignored if the button's state is
2095 disabled.
2096 """
2097 self.tk.call(self._w, 'flash')
2098
2099 def invoke(self):
2100 """Invoke the command associated with the button.
2101
2102 The return value is the return value from the command,
2103 or an empty string if there is no command associated with
2104 the button. This command is ignored if the button's state
2105 is disabled.
2106 """
2107 return self.tk.call(self._w, 'invoke')
2108
2109# Indices:
2110# XXX I don't like these -- take them away
2111def AtEnd():
2112 return 'end'
2113def AtInsert(*args):
2114 s = 'insert'
2115 for a in args:
2116 if a: s = s + (' ' + a)
2117 return s
2118def AtSelFirst():
2119 return 'sel.first'
2120def AtSelLast():
2121 return 'sel.last'
2122def At(x, y=None):
2123 if y is None:
2124 return '@%r' % (x,)
2125 else:
2126 return '@%r,%r' % (x, y)
2127
Guilherme Poloe45f0172009-08-14 14:36:45 +00002128class Canvas(Widget, XView, YView):
Georg Brandl33cece02008-05-20 06:58:21 +00002129 """Canvas widget to display graphical elements like lines or text."""
2130 def __init__(self, master=None, cnf={}, **kw):
2131 """Construct a canvas widget with the parent MASTER.
2132
2133 Valid resource names: background, bd, bg, borderwidth, closeenough,
2134 confine, cursor, height, highlightbackground, highlightcolor,
2135 highlightthickness, insertbackground, insertborderwidth,
2136 insertofftime, insertontime, insertwidth, offset, relief,
2137 scrollregion, selectbackground, selectborderwidth, selectforeground,
2138 state, takefocus, width, xscrollcommand, xscrollincrement,
2139 yscrollcommand, yscrollincrement."""
2140 Widget.__init__(self, master, 'canvas', cnf, kw)
2141 def addtag(self, *args):
2142 """Internal function."""
2143 self.tk.call((self._w, 'addtag') + args)
2144 def addtag_above(self, newtag, tagOrId):
2145 """Add tag NEWTAG to all items above TAGORID."""
2146 self.addtag(newtag, 'above', tagOrId)
2147 def addtag_all(self, newtag):
2148 """Add tag NEWTAG to all items."""
2149 self.addtag(newtag, 'all')
2150 def addtag_below(self, newtag, tagOrId):
2151 """Add tag NEWTAG to all items below TAGORID."""
2152 self.addtag(newtag, 'below', tagOrId)
2153 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2154 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2155 If several match take the top-most.
2156 All items closer than HALO are considered overlapping (all are
2157 closests). If START is specified the next below this tag is taken."""
2158 self.addtag(newtag, 'closest', x, y, halo, start)
2159 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2160 """Add tag NEWTAG to all items in the rectangle defined
2161 by X1,Y1,X2,Y2."""
2162 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2163 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2164 """Add tag NEWTAG to all items which overlap the rectangle
2165 defined by X1,Y1,X2,Y2."""
2166 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2167 def addtag_withtag(self, newtag, tagOrId):
2168 """Add tag NEWTAG to all items with TAGORID."""
2169 self.addtag(newtag, 'withtag', tagOrId)
2170 def bbox(self, *args):
2171 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2172 which encloses all items with tags specified as arguments."""
2173 return self._getints(
2174 self.tk.call((self._w, 'bbox') + args)) or None
2175 def tag_unbind(self, tagOrId, sequence, funcid=None):
2176 """Unbind for all items with TAGORID for event SEQUENCE the
2177 function identified with FUNCID."""
2178 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2179 if funcid:
2180 self.deletecommand(funcid)
2181 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2182 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
2183
2184 An additional boolean parameter ADD specifies whether FUNC will be
2185 called additionally to the other bound function or whether it will
2186 replace the previous function. See bind for the return value."""
2187 return self._bind((self._w, 'bind', tagOrId),
2188 sequence, func, add)
2189 def canvasx(self, screenx, gridspacing=None):
2190 """Return the canvas x coordinate of pixel position SCREENX rounded
2191 to nearest multiple of GRIDSPACING units."""
2192 return getdouble(self.tk.call(
2193 self._w, 'canvasx', screenx, gridspacing))
2194 def canvasy(self, screeny, gridspacing=None):
2195 """Return the canvas y coordinate of pixel position SCREENY rounded
2196 to nearest multiple of GRIDSPACING units."""
2197 return getdouble(self.tk.call(
2198 self._w, 'canvasy', screeny, gridspacing))
2199 def coords(self, *args):
2200 """Return a list of coordinates for the item given in ARGS."""
2201 # XXX Should use _flatten on args
2202 return map(getdouble,
2203 self.tk.splitlist(
2204 self.tk.call((self._w, 'coords') + args)))
2205 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2206 """Internal function."""
2207 args = _flatten(args)
2208 cnf = args[-1]
2209 if type(cnf) in (DictionaryType, TupleType):
2210 args = args[:-1]
2211 else:
2212 cnf = {}
2213 return getint(self.tk.call(
2214 self._w, 'create', itemType,
2215 *(args + self._options(cnf, kw))))
2216 def create_arc(self, *args, **kw):
2217 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2218 return self._create('arc', args, kw)
2219 def create_bitmap(self, *args, **kw):
2220 """Create bitmap with coordinates x1,y1."""
2221 return self._create('bitmap', args, kw)
2222 def create_image(self, *args, **kw):
2223 """Create image item with coordinates x1,y1."""
2224 return self._create('image', args, kw)
2225 def create_line(self, *args, **kw):
2226 """Create line with coordinates x1,y1,...,xn,yn."""
2227 return self._create('line', args, kw)
2228 def create_oval(self, *args, **kw):
2229 """Create oval with coordinates x1,y1,x2,y2."""
2230 return self._create('oval', args, kw)
2231 def create_polygon(self, *args, **kw):
2232 """Create polygon with coordinates x1,y1,...,xn,yn."""
2233 return self._create('polygon', args, kw)
2234 def create_rectangle(self, *args, **kw):
2235 """Create rectangle with coordinates x1,y1,x2,y2."""
2236 return self._create('rectangle', args, kw)
2237 def create_text(self, *args, **kw):
2238 """Create text with coordinates x1,y1."""
2239 return self._create('text', args, kw)
2240 def create_window(self, *args, **kw):
2241 """Create window with coordinates x1,y1,x2,y2."""
2242 return self._create('window', args, kw)
2243 def dchars(self, *args):
2244 """Delete characters of text items identified by tag or id in ARGS (possibly
2245 several times) from FIRST to LAST character (including)."""
2246 self.tk.call((self._w, 'dchars') + args)
2247 def delete(self, *args):
2248 """Delete items identified by all tag or ids contained in ARGS."""
2249 self.tk.call((self._w, 'delete') + args)
2250 def dtag(self, *args):
2251 """Delete tag or id given as last arguments in ARGS from items
2252 identified by first argument in ARGS."""
2253 self.tk.call((self._w, 'dtag') + args)
2254 def find(self, *args):
2255 """Internal function."""
2256 return self._getints(
2257 self.tk.call((self._w, 'find') + args)) or ()
2258 def find_above(self, tagOrId):
2259 """Return items above TAGORID."""
2260 return self.find('above', tagOrId)
2261 def find_all(self):
2262 """Return all items."""
2263 return self.find('all')
2264 def find_below(self, tagOrId):
2265 """Return all items below TAGORID."""
2266 return self.find('below', tagOrId)
2267 def find_closest(self, x, y, halo=None, start=None):
2268 """Return item which is closest to pixel at X, Y.
2269 If several match take the top-most.
2270 All items closer than HALO are considered overlapping (all are
2271 closests). If START is specified the next below this tag is taken."""
2272 return self.find('closest', x, y, halo, start)
2273 def find_enclosed(self, x1, y1, x2, y2):
2274 """Return all items in rectangle defined
2275 by X1,Y1,X2,Y2."""
2276 return self.find('enclosed', x1, y1, x2, y2)
2277 def find_overlapping(self, x1, y1, x2, y2):
2278 """Return all items which overlap the rectangle
2279 defined by X1,Y1,X2,Y2."""
2280 return self.find('overlapping', x1, y1, x2, y2)
2281 def find_withtag(self, tagOrId):
2282 """Return all items with TAGORID."""
2283 return self.find('withtag', tagOrId)
2284 def focus(self, *args):
2285 """Set focus to the first item specified in ARGS."""
2286 return self.tk.call((self._w, 'focus') + args)
2287 def gettags(self, *args):
2288 """Return tags associated with the first item specified in ARGS."""
2289 return self.tk.splitlist(
2290 self.tk.call((self._w, 'gettags') + args))
2291 def icursor(self, *args):
2292 """Set cursor at position POS in the item identified by TAGORID.
2293 In ARGS TAGORID must be first."""
2294 self.tk.call((self._w, 'icursor') + args)
2295 def index(self, *args):
2296 """Return position of cursor as integer in item specified in ARGS."""
2297 return getint(self.tk.call((self._w, 'index') + args))
2298 def insert(self, *args):
2299 """Insert TEXT in item TAGORID at position POS. ARGS must
2300 be TAGORID POS TEXT."""
2301 self.tk.call((self._w, 'insert') + args)
2302 def itemcget(self, tagOrId, option):
2303 """Return the resource value for an OPTION for item TAGORID."""
2304 return self.tk.call(
2305 (self._w, 'itemcget') + (tagOrId, '-'+option))
2306 def itemconfigure(self, tagOrId, cnf=None, **kw):
2307 """Configure resources of an item TAGORID.
2308
2309 The values for resources are specified as keyword
2310 arguments. To get an overview about
2311 the allowed keyword arguments call the method without arguments.
2312 """
2313 return self._configure(('itemconfigure', tagOrId), cnf, kw)
2314 itemconfig = itemconfigure
2315 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2316 # so the preferred name for them is tag_lower, tag_raise
2317 # (similar to tag_bind, and similar to the Text widget);
2318 # unfortunately can't delete the old ones yet (maybe in 1.6)
2319 def tag_lower(self, *args):
2320 """Lower an item TAGORID given in ARGS
2321 (optional below another item)."""
2322 self.tk.call((self._w, 'lower') + args)
2323 lower = tag_lower
2324 def move(self, *args):
2325 """Move an item TAGORID given in ARGS."""
2326 self.tk.call((self._w, 'move') + args)
2327 def postscript(self, cnf={}, **kw):
2328 """Print the contents of the canvas to a postscript
2329 file. Valid options: colormap, colormode, file, fontmap,
2330 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2331 rotate, witdh, x, y."""
2332 return self.tk.call((self._w, 'postscript') +
2333 self._options(cnf, kw))
2334 def tag_raise(self, *args):
2335 """Raise an item TAGORID given in ARGS
2336 (optional above another item)."""
2337 self.tk.call((self._w, 'raise') + args)
2338 lift = tkraise = tag_raise
2339 def scale(self, *args):
2340 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2341 self.tk.call((self._w, 'scale') + args)
2342 def scan_mark(self, x, y):
2343 """Remember the current X, Y coordinates."""
2344 self.tk.call(self._w, 'scan', 'mark', x, y)
2345 def scan_dragto(self, x, y, gain=10):
2346 """Adjust the view of the canvas to GAIN times the
2347 difference between X and Y and the coordinates given in
2348 scan_mark."""
2349 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
2350 def select_adjust(self, tagOrId, index):
2351 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2352 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2353 def select_clear(self):
2354 """Clear the selection if it is in this widget."""
2355 self.tk.call(self._w, 'select', 'clear')
2356 def select_from(self, tagOrId, index):
2357 """Set the fixed end of a selection in item TAGORID to INDEX."""
2358 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2359 def select_item(self):
2360 """Return the item which has the selection."""
2361 return self.tk.call(self._w, 'select', 'item') or None
2362 def select_to(self, tagOrId, index):
2363 """Set the variable end of a selection in item TAGORID to INDEX."""
2364 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2365 def type(self, tagOrId):
2366 """Return the type of the item TAGORID."""
2367 return self.tk.call(self._w, 'type', tagOrId) or None
Georg Brandl33cece02008-05-20 06:58:21 +00002368
2369class Checkbutton(Widget):
2370 """Checkbutton widget which is either in on- or off-state."""
2371 def __init__(self, master=None, cnf={}, **kw):
2372 """Construct a checkbutton widget with the parent MASTER.
2373
2374 Valid resource names: activebackground, activeforeground, anchor,
2375 background, bd, bg, bitmap, borderwidth, command, cursor,
2376 disabledforeground, fg, font, foreground, height,
2377 highlightbackground, highlightcolor, highlightthickness, image,
2378 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2379 selectcolor, selectimage, state, takefocus, text, textvariable,
2380 underline, variable, width, wraplength."""
2381 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2382 def deselect(self):
2383 """Put the button in off-state."""
2384 self.tk.call(self._w, 'deselect')
2385 def flash(self):
2386 """Flash the button."""
2387 self.tk.call(self._w, 'flash')
2388 def invoke(self):
2389 """Toggle the button and invoke a command if given as resource."""
2390 return self.tk.call(self._w, 'invoke')
2391 def select(self):
2392 """Put the button in on-state."""
2393 self.tk.call(self._w, 'select')
2394 def toggle(self):
2395 """Toggle the button."""
2396 self.tk.call(self._w, 'toggle')
2397
Guilherme Poloe45f0172009-08-14 14:36:45 +00002398class Entry(Widget, XView):
Georg Brandl33cece02008-05-20 06:58:21 +00002399 """Entry widget which allows to display simple text."""
2400 def __init__(self, master=None, cnf={}, **kw):
2401 """Construct an entry widget with the parent MASTER.
2402
2403 Valid resource names: background, bd, bg, borderwidth, cursor,
2404 exportselection, fg, font, foreground, highlightbackground,
2405 highlightcolor, highlightthickness, insertbackground,
2406 insertborderwidth, insertofftime, insertontime, insertwidth,
2407 invalidcommand, invcmd, justify, relief, selectbackground,
2408 selectborderwidth, selectforeground, show, state, takefocus,
2409 textvariable, validate, validatecommand, vcmd, width,
2410 xscrollcommand."""
2411 Widget.__init__(self, master, 'entry', cnf, kw)
2412 def delete(self, first, last=None):
2413 """Delete text from FIRST to LAST (not included)."""
2414 self.tk.call(self._w, 'delete', first, last)
2415 def get(self):
2416 """Return the text."""
2417 return self.tk.call(self._w, 'get')
2418 def icursor(self, index):
2419 """Insert cursor at INDEX."""
2420 self.tk.call(self._w, 'icursor', index)
2421 def index(self, index):
2422 """Return position of cursor."""
2423 return getint(self.tk.call(
2424 self._w, 'index', index))
2425 def insert(self, index, string):
2426 """Insert STRING at INDEX."""
2427 self.tk.call(self._w, 'insert', index, string)
2428 def scan_mark(self, x):
2429 """Remember the current X, Y coordinates."""
2430 self.tk.call(self._w, 'scan', 'mark', x)
2431 def scan_dragto(self, x):
2432 """Adjust the view of the canvas to 10 times the
2433 difference between X and Y and the coordinates given in
2434 scan_mark."""
2435 self.tk.call(self._w, 'scan', 'dragto', x)
2436 def selection_adjust(self, index):
2437 """Adjust the end of the selection near the cursor to INDEX."""
2438 self.tk.call(self._w, 'selection', 'adjust', index)
2439 select_adjust = selection_adjust
2440 def selection_clear(self):
2441 """Clear the selection if it is in this widget."""
2442 self.tk.call(self._w, 'selection', 'clear')
2443 select_clear = selection_clear
2444 def selection_from(self, index):
2445 """Set the fixed end of a selection to INDEX."""
2446 self.tk.call(self._w, 'selection', 'from', index)
2447 select_from = selection_from
2448 def selection_present(self):
Guilherme Polo75e1f992009-08-14 14:43:43 +00002449 """Return True if there are characters selected in the entry, False
2450 otherwise."""
Georg Brandl33cece02008-05-20 06:58:21 +00002451 return self.tk.getboolean(
2452 self.tk.call(self._w, 'selection', 'present'))
2453 select_present = selection_present
2454 def selection_range(self, start, end):
2455 """Set the selection from START to END (not included)."""
2456 self.tk.call(self._w, 'selection', 'range', start, end)
2457 select_range = selection_range
2458 def selection_to(self, index):
2459 """Set the variable end of a selection to INDEX."""
2460 self.tk.call(self._w, 'selection', 'to', index)
2461 select_to = selection_to
Georg Brandl33cece02008-05-20 06:58:21 +00002462
2463class Frame(Widget):
2464 """Frame widget which may contain other widgets and can have a 3D border."""
2465 def __init__(self, master=None, cnf={}, **kw):
2466 """Construct a frame widget with the parent MASTER.
2467
2468 Valid resource names: background, bd, bg, borderwidth, class,
2469 colormap, container, cursor, height, highlightbackground,
2470 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2471 cnf = _cnfmerge((cnf, kw))
2472 extra = ()
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002473 if 'class_' in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002474 extra = ('-class', cnf['class_'])
2475 del cnf['class_']
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002476 elif 'class' in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002477 extra = ('-class', cnf['class'])
2478 del cnf['class']
2479 Widget.__init__(self, master, 'frame', cnf, {}, extra)
2480
2481class Label(Widget):
2482 """Label widget which can display text and bitmaps."""
2483 def __init__(self, master=None, cnf={}, **kw):
2484 """Construct a label widget with the parent MASTER.
2485
2486 STANDARD OPTIONS
2487
2488 activebackground, activeforeground, anchor,
2489 background, bitmap, borderwidth, cursor,
2490 disabledforeground, font, foreground,
2491 highlightbackground, highlightcolor,
2492 highlightthickness, image, justify,
2493 padx, pady, relief, takefocus, text,
2494 textvariable, underline, wraplength
2495
2496 WIDGET-SPECIFIC OPTIONS
2497
2498 height, state, width
2499
2500 """
2501 Widget.__init__(self, master, 'label', cnf, kw)
2502
Guilherme Poloe45f0172009-08-14 14:36:45 +00002503class Listbox(Widget, XView, YView):
Georg Brandl33cece02008-05-20 06:58:21 +00002504 """Listbox widget which can display a list of strings."""
2505 def __init__(self, master=None, cnf={}, **kw):
2506 """Construct a listbox widget with the parent MASTER.
2507
2508 Valid resource names: background, bd, bg, borderwidth, cursor,
2509 exportselection, fg, font, foreground, height, highlightbackground,
2510 highlightcolor, highlightthickness, relief, selectbackground,
2511 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2512 width, xscrollcommand, yscrollcommand, listvariable."""
2513 Widget.__init__(self, master, 'listbox', cnf, kw)
2514 def activate(self, index):
2515 """Activate item identified by INDEX."""
2516 self.tk.call(self._w, 'activate', index)
2517 def bbox(self, *args):
2518 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2519 which encloses the item identified by index in ARGS."""
2520 return self._getints(
2521 self.tk.call((self._w, 'bbox') + args)) or None
2522 def curselection(self):
2523 """Return list of indices of currently selected item."""
2524 # XXX Ought to apply self._getints()...
2525 return self.tk.splitlist(self.tk.call(
2526 self._w, 'curselection'))
2527 def delete(self, first, last=None):
2528 """Delete items from FIRST to LAST (not included)."""
2529 self.tk.call(self._w, 'delete', first, last)
2530 def get(self, first, last=None):
2531 """Get list of items from FIRST to LAST (not included)."""
2532 if last:
2533 return self.tk.splitlist(self.tk.call(
2534 self._w, 'get', first, last))
2535 else:
2536 return self.tk.call(self._w, 'get', first)
2537 def index(self, index):
2538 """Return index of item identified with INDEX."""
2539 i = self.tk.call(self._w, 'index', index)
2540 if i == 'none': return None
2541 return getint(i)
2542 def insert(self, index, *elements):
2543 """Insert ELEMENTS at INDEX."""
2544 self.tk.call((self._w, 'insert', index) + elements)
2545 def nearest(self, y):
2546 """Get index of item which is nearest to y coordinate Y."""
2547 return getint(self.tk.call(
2548 self._w, 'nearest', y))
2549 def scan_mark(self, x, y):
2550 """Remember the current X, Y coordinates."""
2551 self.tk.call(self._w, 'scan', 'mark', x, y)
2552 def scan_dragto(self, x, y):
2553 """Adjust the view of the listbox to 10 times the
2554 difference between X and Y and the coordinates given in
2555 scan_mark."""
2556 self.tk.call(self._w, 'scan', 'dragto', x, y)
2557 def see(self, index):
2558 """Scroll such that INDEX is visible."""
2559 self.tk.call(self._w, 'see', index)
2560 def selection_anchor(self, index):
2561 """Set the fixed end oft the selection to INDEX."""
2562 self.tk.call(self._w, 'selection', 'anchor', index)
2563 select_anchor = selection_anchor
2564 def selection_clear(self, first, last=None):
2565 """Clear the selection from FIRST to LAST (not included)."""
2566 self.tk.call(self._w,
2567 'selection', 'clear', first, last)
2568 select_clear = selection_clear
2569 def selection_includes(self, index):
2570 """Return 1 if INDEX is part of the selection."""
2571 return self.tk.getboolean(self.tk.call(
2572 self._w, 'selection', 'includes', index))
2573 select_includes = selection_includes
2574 def selection_set(self, first, last=None):
2575 """Set the selection from FIRST to LAST (not included) without
2576 changing the currently selected elements."""
2577 self.tk.call(self._w, 'selection', 'set', first, last)
2578 select_set = selection_set
2579 def size(self):
2580 """Return the number of elements in the listbox."""
2581 return getint(self.tk.call(self._w, 'size'))
Georg Brandl33cece02008-05-20 06:58:21 +00002582 def itemcget(self, index, option):
2583 """Return the resource value for an ITEM and an OPTION."""
2584 return self.tk.call(
2585 (self._w, 'itemcget') + (index, '-'+option))
2586 def itemconfigure(self, index, cnf=None, **kw):
2587 """Configure resources of an ITEM.
2588
2589 The values for resources are specified as keyword arguments.
2590 To get an overview about the allowed keyword arguments
2591 call the method without arguments.
2592 Valid resource names: background, bg, foreground, fg,
2593 selectbackground, selectforeground."""
2594 return self._configure(('itemconfigure', index), cnf, kw)
2595 itemconfig = itemconfigure
2596
2597class Menu(Widget):
2598 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2599 def __init__(self, master=None, cnf={}, **kw):
2600 """Construct menu widget with the parent MASTER.
2601
2602 Valid resource names: activebackground, activeborderwidth,
2603 activeforeground, background, bd, bg, borderwidth, cursor,
2604 disabledforeground, fg, font, foreground, postcommand, relief,
2605 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2606 Widget.__init__(self, master, 'menu', cnf, kw)
2607 def tk_bindForTraversal(self):
2608 pass # obsolete since Tk 4.0
2609 def tk_mbPost(self):
2610 self.tk.call('tk_mbPost', self._w)
2611 def tk_mbUnpost(self):
2612 self.tk.call('tk_mbUnpost')
2613 def tk_traverseToMenu(self, char):
2614 self.tk.call('tk_traverseToMenu', self._w, char)
2615 def tk_traverseWithinMenu(self, char):
2616 self.tk.call('tk_traverseWithinMenu', self._w, char)
2617 def tk_getMenuButtons(self):
2618 return self.tk.call('tk_getMenuButtons', self._w)
2619 def tk_nextMenu(self, count):
2620 self.tk.call('tk_nextMenu', count)
2621 def tk_nextMenuEntry(self, count):
2622 self.tk.call('tk_nextMenuEntry', count)
2623 def tk_invokeMenu(self):
2624 self.tk.call('tk_invokeMenu', self._w)
2625 def tk_firstMenu(self):
2626 self.tk.call('tk_firstMenu', self._w)
2627 def tk_mbButtonDown(self):
2628 self.tk.call('tk_mbButtonDown', self._w)
2629 def tk_popup(self, x, y, entry=""):
2630 """Post the menu at position X,Y with entry ENTRY."""
2631 self.tk.call('tk_popup', self._w, x, y, entry)
2632 def activate(self, index):
2633 """Activate entry at INDEX."""
2634 self.tk.call(self._w, 'activate', index)
2635 def add(self, itemType, cnf={}, **kw):
2636 """Internal function."""
2637 self.tk.call((self._w, 'add', itemType) +
2638 self._options(cnf, kw))
2639 def add_cascade(self, cnf={}, **kw):
2640 """Add hierarchical menu item."""
2641 self.add('cascade', cnf or kw)
2642 def add_checkbutton(self, cnf={}, **kw):
2643 """Add checkbutton menu item."""
2644 self.add('checkbutton', cnf or kw)
2645 def add_command(self, cnf={}, **kw):
2646 """Add command menu item."""
2647 self.add('command', cnf or kw)
2648 def add_radiobutton(self, cnf={}, **kw):
2649 """Addd radio menu item."""
2650 self.add('radiobutton', cnf or kw)
2651 def add_separator(self, cnf={}, **kw):
2652 """Add separator."""
2653 self.add('separator', cnf or kw)
2654 def insert(self, index, itemType, cnf={}, **kw):
2655 """Internal function."""
2656 self.tk.call((self._w, 'insert', index, itemType) +
2657 self._options(cnf, kw))
2658 def insert_cascade(self, index, cnf={}, **kw):
2659 """Add hierarchical menu item at INDEX."""
2660 self.insert(index, 'cascade', cnf or kw)
2661 def insert_checkbutton(self, index, cnf={}, **kw):
2662 """Add checkbutton menu item at INDEX."""
2663 self.insert(index, 'checkbutton', cnf or kw)
2664 def insert_command(self, index, cnf={}, **kw):
2665 """Add command menu item at INDEX."""
2666 self.insert(index, 'command', cnf or kw)
2667 def insert_radiobutton(self, index, cnf={}, **kw):
2668 """Addd radio menu item at INDEX."""
2669 self.insert(index, 'radiobutton', cnf or kw)
2670 def insert_separator(self, index, cnf={}, **kw):
2671 """Add separator at INDEX."""
2672 self.insert(index, 'separator', cnf or kw)
2673 def delete(self, index1, index2=None):
Hirokazu Yamamotob9828f62008-11-03 18:03:06 +00002674 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies14646332008-08-10 11:01:53 +00002675 if index2 is None:
2676 index2 = index1
Hirokazu Yamamotob9828f62008-11-03 18:03:06 +00002677
2678 num_index1, num_index2 = self.index(index1), self.index(index2)
2679 if (num_index1 is None) or (num_index2 is None):
2680 num_index1, num_index2 = 0, -1
2681
2682 for i in range(num_index1, num_index2 + 1):
2683 if 'command' in self.entryconfig(i):
2684 c = str(self.entrycget(i, 'command'))
2685 if c:
2686 self.deletecommand(c)
Georg Brandl33cece02008-05-20 06:58:21 +00002687 self.tk.call(self._w, 'delete', index1, index2)
Georg Brandl33cece02008-05-20 06:58:21 +00002688 def entrycget(self, index, option):
2689 """Return the resource value of an menu item for OPTION at INDEX."""
2690 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2691 def entryconfigure(self, index, cnf=None, **kw):
2692 """Configure a menu item at INDEX."""
2693 return self._configure(('entryconfigure', index), cnf, kw)
2694 entryconfig = entryconfigure
2695 def index(self, index):
2696 """Return the index of a menu item identified by INDEX."""
2697 i = self.tk.call(self._w, 'index', index)
2698 if i == 'none': return None
2699 return getint(i)
2700 def invoke(self, index):
2701 """Invoke a menu item identified by INDEX and execute
2702 the associated command."""
2703 return self.tk.call(self._w, 'invoke', index)
2704 def post(self, x, y):
2705 """Display a menu at position X,Y."""
2706 self.tk.call(self._w, 'post', x, y)
2707 def type(self, index):
2708 """Return the type of the menu item at INDEX."""
2709 return self.tk.call(self._w, 'type', index)
2710 def unpost(self):
2711 """Unmap a menu."""
2712 self.tk.call(self._w, 'unpost')
2713 def yposition(self, index):
2714 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2715 return getint(self.tk.call(
2716 self._w, 'yposition', index))
2717
2718class Menubutton(Widget):
2719 """Menubutton widget, obsolete since Tk8.0."""
2720 def __init__(self, master=None, cnf={}, **kw):
2721 Widget.__init__(self, master, 'menubutton', cnf, kw)
2722
2723class Message(Widget):
2724 """Message widget to display multiline text. Obsolete since Label does it too."""
2725 def __init__(self, master=None, cnf={}, **kw):
2726 Widget.__init__(self, master, 'message', cnf, kw)
2727
2728class Radiobutton(Widget):
2729 """Radiobutton widget which shows only one of several buttons in on-state."""
2730 def __init__(self, master=None, cnf={}, **kw):
2731 """Construct a radiobutton widget with the parent MASTER.
2732
2733 Valid resource names: activebackground, activeforeground, anchor,
2734 background, bd, bg, bitmap, borderwidth, command, cursor,
2735 disabledforeground, fg, font, foreground, height,
2736 highlightbackground, highlightcolor, highlightthickness, image,
2737 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2738 state, takefocus, text, textvariable, underline, value, variable,
2739 width, wraplength."""
2740 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2741 def deselect(self):
2742 """Put the button in off-state."""
2743
2744 self.tk.call(self._w, 'deselect')
2745 def flash(self):
2746 """Flash the button."""
2747 self.tk.call(self._w, 'flash')
2748 def invoke(self):
2749 """Toggle the button and invoke a command if given as resource."""
2750 return self.tk.call(self._w, 'invoke')
2751 def select(self):
2752 """Put the button in on-state."""
2753 self.tk.call(self._w, 'select')
2754
2755class Scale(Widget):
2756 """Scale widget which can display a numerical scale."""
2757 def __init__(self, master=None, cnf={}, **kw):
2758 """Construct a scale widget with the parent MASTER.
2759
2760 Valid resource names: activebackground, background, bigincrement, bd,
2761 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2762 highlightbackground, highlightcolor, highlightthickness, label,
2763 length, orient, relief, repeatdelay, repeatinterval, resolution,
2764 showvalue, sliderlength, sliderrelief, state, takefocus,
2765 tickinterval, to, troughcolor, variable, width."""
2766 Widget.__init__(self, master, 'scale', cnf, kw)
2767 def get(self):
2768 """Get the current value as integer or float."""
2769 value = self.tk.call(self._w, 'get')
2770 try:
2771 return getint(value)
2772 except ValueError:
2773 return getdouble(value)
2774 def set(self, value):
2775 """Set the value to VALUE."""
2776 self.tk.call(self._w, 'set', value)
2777 def coords(self, value=None):
2778 """Return a tuple (X,Y) of the point along the centerline of the
2779 trough that corresponds to VALUE or the current value if None is
2780 given."""
2781
2782 return self._getints(self.tk.call(self._w, 'coords', value))
2783 def identify(self, x, y):
2784 """Return where the point X,Y lies. Valid return values are "slider",
2785 "though1" and "though2"."""
2786 return self.tk.call(self._w, 'identify', x, y)
2787
2788class Scrollbar(Widget):
2789 """Scrollbar widget which displays a slider at a certain position."""
2790 def __init__(self, master=None, cnf={}, **kw):
2791 """Construct a scrollbar widget with the parent MASTER.
2792
2793 Valid resource names: activebackground, activerelief,
2794 background, bd, bg, borderwidth, command, cursor,
2795 elementborderwidth, highlightbackground,
2796 highlightcolor, highlightthickness, jump, orient,
2797 relief, repeatdelay, repeatinterval, takefocus,
2798 troughcolor, width."""
2799 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2800 def activate(self, index):
2801 """Display the element at INDEX with activebackground and activerelief.
2802 INDEX can be "arrow1","slider" or "arrow2"."""
2803 self.tk.call(self._w, 'activate', index)
2804 def delta(self, deltax, deltay):
2805 """Return the fractional change of the scrollbar setting if it
2806 would be moved by DELTAX or DELTAY pixels."""
2807 return getdouble(
2808 self.tk.call(self._w, 'delta', deltax, deltay))
2809 def fraction(self, x, y):
2810 """Return the fractional value which corresponds to a slider
2811 position of X,Y."""
2812 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2813 def identify(self, x, y):
2814 """Return the element under position X,Y as one of
2815 "arrow1","slider","arrow2" or ""."""
2816 return self.tk.call(self._w, 'identify', x, y)
2817 def get(self):
2818 """Return the current fractional values (upper and lower end)
2819 of the slider position."""
2820 return self._getdoubles(self.tk.call(self._w, 'get'))
2821 def set(self, *args):
2822 """Set the fractional values of the slider position (upper and
2823 lower ends as value between 0 and 1)."""
2824 self.tk.call((self._w, 'set') + args)
2825
2826
2827
Guilherme Poloe45f0172009-08-14 14:36:45 +00002828class Text(Widget, XView, YView):
Georg Brandl33cece02008-05-20 06:58:21 +00002829 """Text widget which can display text in various forms."""
2830 def __init__(self, master=None, cnf={}, **kw):
2831 """Construct a text widget with the parent MASTER.
2832
2833 STANDARD OPTIONS
2834
2835 background, borderwidth, cursor,
2836 exportselection, font, foreground,
2837 highlightbackground, highlightcolor,
2838 highlightthickness, insertbackground,
2839 insertborderwidth, insertofftime,
2840 insertontime, insertwidth, padx, pady,
2841 relief, selectbackground,
2842 selectborderwidth, selectforeground,
2843 setgrid, takefocus,
2844 xscrollcommand, yscrollcommand,
2845
2846 WIDGET-SPECIFIC OPTIONS
2847
2848 autoseparators, height, maxundo,
2849 spacing1, spacing2, spacing3,
2850 state, tabs, undo, width, wrap,
2851
2852 """
2853 Widget.__init__(self, master, 'text', cnf, kw)
2854 def bbox(self, *args):
2855 """Return a tuple of (x,y,width,height) which gives the bounding
2856 box of the visible part of the character at the index in ARGS."""
2857 return self._getints(
2858 self.tk.call((self._w, 'bbox') + args)) or None
2859 def tk_textSelectTo(self, index):
2860 self.tk.call('tk_textSelectTo', self._w, index)
2861 def tk_textBackspace(self):
2862 self.tk.call('tk_textBackspace', self._w)
2863 def tk_textIndexCloser(self, a, b, c):
2864 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2865 def tk_textResetAnchor(self, index):
2866 self.tk.call('tk_textResetAnchor', self._w, index)
2867 def compare(self, index1, op, index2):
2868 """Return whether between index INDEX1 and index INDEX2 the
2869 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2870 return self.tk.getboolean(self.tk.call(
2871 self._w, 'compare', index1, op, index2))
2872 def debug(self, boolean=None):
2873 """Turn on the internal consistency checks of the B-Tree inside the text
2874 widget according to BOOLEAN."""
2875 return self.tk.getboolean(self.tk.call(
2876 self._w, 'debug', boolean))
2877 def delete(self, index1, index2=None):
2878 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2879 self.tk.call(self._w, 'delete', index1, index2)
2880 def dlineinfo(self, index):
2881 """Return tuple (x,y,width,height,baseline) giving the bounding box
2882 and baseline position of the visible part of the line containing
2883 the character at INDEX."""
2884 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
2885 def dump(self, index1, index2=None, command=None, **kw):
2886 """Return the contents of the widget between index1 and index2.
2887
2888 The type of contents returned in filtered based on the keyword
2889 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2890 given and true, then the corresponding items are returned. The result
2891 is a list of triples of the form (key, value, index). If none of the
2892 keywords are true then 'all' is used by default.
2893
2894 If the 'command' argument is given, it is called once for each element
2895 of the list of triples, with the values of each triple serving as the
2896 arguments to the function. In this case the list is not returned."""
2897 args = []
2898 func_name = None
2899 result = None
2900 if not command:
2901 # Never call the dump command without the -command flag, since the
2902 # output could involve Tcl quoting and would be a pain to parse
2903 # right. Instead just set the command to build a list of triples
2904 # as if we had done the parsing.
2905 result = []
2906 def append_triple(key, value, index, result=result):
2907 result.append((key, value, index))
2908 command = append_triple
2909 try:
2910 if not isinstance(command, str):
2911 func_name = command = self._register(command)
2912 args += ["-command", command]
2913 for key in kw:
2914 if kw[key]: args.append("-" + key)
2915 args.append(index1)
2916 if index2:
2917 args.append(index2)
2918 self.tk.call(self._w, "dump", *args)
2919 return result
2920 finally:
2921 if func_name:
2922 self.deletecommand(func_name)
2923
2924 ## new in tk8.4
2925 def edit(self, *args):
2926 """Internal method
2927
2928 This method controls the undo mechanism and
2929 the modified flag. The exact behavior of the
2930 command depends on the option argument that
2931 follows the edit argument. The following forms
2932 of the command are currently supported:
2933
2934 edit_modified, edit_redo, edit_reset, edit_separator
2935 and edit_undo
2936
2937 """
2938 return self.tk.call(self._w, 'edit', *args)
2939
2940 def edit_modified(self, arg=None):
2941 """Get or Set the modified flag
2942
2943 If arg is not specified, returns the modified
2944 flag of the widget. The insert, delete, edit undo and
2945 edit redo commands or the user can set or clear the
2946 modified flag. If boolean is specified, sets the
2947 modified flag of the widget to arg.
2948 """
2949 return self.edit("modified", arg)
2950
2951 def edit_redo(self):
2952 """Redo the last undone edit
2953
2954 When the undo option is true, reapplies the last
2955 undone edits provided no other edits were done since
2956 then. Generates an error when the redo stack is empty.
2957 Does nothing when the undo option is false.
2958 """
2959 return self.edit("redo")
2960
2961 def edit_reset(self):
2962 """Clears the undo and redo stacks
2963 """
2964 return self.edit("reset")
2965
2966 def edit_separator(self):
2967 """Inserts a separator (boundary) on the undo stack.
2968
2969 Does nothing when the undo option is false
2970 """
2971 return self.edit("separator")
2972
2973 def edit_undo(self):
2974 """Undoes the last edit action
2975
2976 If the undo option is true. An edit action is defined
2977 as all the insert and delete commands that are recorded
2978 on the undo stack in between two separators. Generates
2979 an error when the undo stack is empty. Does nothing
2980 when the undo option is false
2981 """
2982 return self.edit("undo")
2983
2984 def get(self, index1, index2=None):
2985 """Return the text from INDEX1 to INDEX2 (not included)."""
2986 return self.tk.call(self._w, 'get', index1, index2)
2987 # (Image commands are new in 8.0)
2988 def image_cget(self, index, option):
2989 """Return the value of OPTION of an embedded image at INDEX."""
2990 if option[:1] != "-":
2991 option = "-" + option
2992 if option[-1:] == "_":
2993 option = option[:-1]
2994 return self.tk.call(self._w, "image", "cget", index, option)
2995 def image_configure(self, index, cnf=None, **kw):
2996 """Configure an embedded image at INDEX."""
2997 return self._configure(('image', 'configure', index), cnf, kw)
2998 def image_create(self, index, cnf={}, **kw):
2999 """Create an embedded image at INDEX."""
3000 return self.tk.call(
3001 self._w, "image", "create", index,
3002 *self._options(cnf, kw))
3003 def image_names(self):
3004 """Return all names of embedded images in this widget."""
3005 return self.tk.call(self._w, "image", "names")
3006 def index(self, index):
3007 """Return the index in the form line.char for INDEX."""
3008 return str(self.tk.call(self._w, 'index', index))
3009 def insert(self, index, chars, *args):
3010 """Insert CHARS before the characters at INDEX. An additional
3011 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3012 self.tk.call((self._w, 'insert', index, chars) + args)
3013 def mark_gravity(self, markName, direction=None):
3014 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3015 Return the current value if None is given for DIRECTION."""
3016 return self.tk.call(
3017 (self._w, 'mark', 'gravity', markName, direction))
3018 def mark_names(self):
3019 """Return all mark names."""
3020 return self.tk.splitlist(self.tk.call(
3021 self._w, 'mark', 'names'))
3022 def mark_set(self, markName, index):
3023 """Set mark MARKNAME before the character at INDEX."""
3024 self.tk.call(self._w, 'mark', 'set', markName, index)
3025 def mark_unset(self, *markNames):
3026 """Delete all marks in MARKNAMES."""
3027 self.tk.call((self._w, 'mark', 'unset') + markNames)
3028 def mark_next(self, index):
3029 """Return the name of the next mark after INDEX."""
3030 return self.tk.call(self._w, 'mark', 'next', index) or None
3031 def mark_previous(self, index):
3032 """Return the name of the previous mark before INDEX."""
3033 return self.tk.call(self._w, 'mark', 'previous', index) or None
3034 def scan_mark(self, x, y):
3035 """Remember the current X, Y coordinates."""
3036 self.tk.call(self._w, 'scan', 'mark', x, y)
3037 def scan_dragto(self, x, y):
3038 """Adjust the view of the text to 10 times the
3039 difference between X and Y and the coordinates given in
3040 scan_mark."""
3041 self.tk.call(self._w, 'scan', 'dragto', x, y)
3042 def search(self, pattern, index, stopindex=None,
3043 forwards=None, backwards=None, exact=None,
3044 regexp=None, nocase=None, count=None, elide=None):
3045 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Polod2ea0332009-02-09 16:41:09 +00003046 Return the index of the first character of a match or an
3047 empty string."""
Georg Brandl33cece02008-05-20 06:58:21 +00003048 args = [self._w, 'search']
3049 if forwards: args.append('-forwards')
3050 if backwards: args.append('-backwards')
3051 if exact: args.append('-exact')
3052 if regexp: args.append('-regexp')
3053 if nocase: args.append('-nocase')
3054 if elide: args.append('-elide')
3055 if count: args.append('-count'); args.append(count)
Guilherme Polod2ea0332009-02-09 16:41:09 +00003056 if pattern and pattern[0] == '-': args.append('--')
Georg Brandl33cece02008-05-20 06:58:21 +00003057 args.append(pattern)
3058 args.append(index)
3059 if stopindex: args.append(stopindex)
Guilherme Polo6d6c1fd2009-03-07 01:19:12 +00003060 return str(self.tk.call(tuple(args)))
Georg Brandl33cece02008-05-20 06:58:21 +00003061 def see(self, index):
3062 """Scroll such that the character at INDEX is visible."""
3063 self.tk.call(self._w, 'see', index)
3064 def tag_add(self, tagName, index1, *args):
3065 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3066 Additional pairs of indices may follow in ARGS."""
3067 self.tk.call(
3068 (self._w, 'tag', 'add', tagName, index1) + args)
3069 def tag_unbind(self, tagName, sequence, funcid=None):
3070 """Unbind for all characters with TAGNAME for event SEQUENCE the
3071 function identified with FUNCID."""
3072 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3073 if funcid:
3074 self.deletecommand(funcid)
3075 def tag_bind(self, tagName, sequence, func, add=None):
3076 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
3077
3078 An additional boolean parameter ADD specifies whether FUNC will be
3079 called additionally to the other bound function or whether it will
3080 replace the previous function. See bind for the return value."""
3081 return self._bind((self._w, 'tag', 'bind', tagName),
3082 sequence, func, add)
3083 def tag_cget(self, tagName, option):
3084 """Return the value of OPTION for tag TAGNAME."""
3085 if option[:1] != '-':
3086 option = '-' + option
3087 if option[-1:] == '_':
3088 option = option[:-1]
3089 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
3090 def tag_configure(self, tagName, cnf=None, **kw):
3091 """Configure a tag TAGNAME."""
3092 return self._configure(('tag', 'configure', tagName), cnf, kw)
3093 tag_config = tag_configure
3094 def tag_delete(self, *tagNames):
3095 """Delete all tags in TAGNAMES."""
3096 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3097 def tag_lower(self, tagName, belowThis=None):
3098 """Change the priority of tag TAGNAME such that it is lower
3099 than the priority of BELOWTHIS."""
3100 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3101 def tag_names(self, index=None):
3102 """Return a list of all tag names."""
3103 return self.tk.splitlist(
3104 self.tk.call(self._w, 'tag', 'names', index))
3105 def tag_nextrange(self, tagName, index1, index2=None):
3106 """Return a list of start and end index for the first sequence of
3107 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3108 The text is searched forward from INDEX1."""
3109 return self.tk.splitlist(self.tk.call(
3110 self._w, 'tag', 'nextrange', tagName, index1, index2))
3111 def tag_prevrange(self, tagName, index1, index2=None):
3112 """Return a list of start and end index for the first sequence of
3113 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3114 The text is searched backwards from INDEX1."""
3115 return self.tk.splitlist(self.tk.call(
3116 self._w, 'tag', 'prevrange', tagName, index1, index2))
3117 def tag_raise(self, tagName, aboveThis=None):
3118 """Change the priority of tag TAGNAME such that it is higher
3119 than the priority of ABOVETHIS."""
3120 self.tk.call(
3121 self._w, 'tag', 'raise', tagName, aboveThis)
3122 def tag_ranges(self, tagName):
3123 """Return a list of ranges of text which have tag TAGNAME."""
3124 return self.tk.splitlist(self.tk.call(
3125 self._w, 'tag', 'ranges', tagName))
3126 def tag_remove(self, tagName, index1, index2=None):
3127 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3128 self.tk.call(
3129 self._w, 'tag', 'remove', tagName, index1, index2)
3130 def window_cget(self, index, option):
3131 """Return the value of OPTION of an embedded window at INDEX."""
3132 if option[:1] != '-':
3133 option = '-' + option
3134 if option[-1:] == '_':
3135 option = option[:-1]
3136 return self.tk.call(self._w, 'window', 'cget', index, option)
3137 def window_configure(self, index, cnf=None, **kw):
3138 """Configure an embedded window at INDEX."""
3139 return self._configure(('window', 'configure', index), cnf, kw)
3140 window_config = window_configure
3141 def window_create(self, index, cnf={}, **kw):
3142 """Create a window at INDEX."""
3143 self.tk.call(
3144 (self._w, 'window', 'create', index)
3145 + self._options(cnf, kw))
3146 def window_names(self):
3147 """Return all names of embedded windows in this widget."""
3148 return self.tk.splitlist(
3149 self.tk.call(self._w, 'window', 'names'))
Georg Brandl33cece02008-05-20 06:58:21 +00003150 def yview_pickplace(self, *what):
3151 """Obsolete function, use see."""
3152 self.tk.call((self._w, 'yview', '-pickplace') + what)
3153
3154
3155class _setit:
3156 """Internal class. It wraps the command in the widget OptionMenu."""
3157 def __init__(self, var, value, callback=None):
3158 self.__value = value
3159 self.__var = var
3160 self.__callback = callback
3161 def __call__(self, *args):
3162 self.__var.set(self.__value)
3163 if self.__callback:
3164 self.__callback(self.__value, *args)
3165
3166class OptionMenu(Menubutton):
3167 """OptionMenu which allows the user to select a value from a menu."""
3168 def __init__(self, master, variable, value, *values, **kwargs):
3169 """Construct an optionmenu widget with the parent MASTER, with
3170 the resource textvariable set to VARIABLE, the initially selected
3171 value VALUE, the other menu values VALUES and an additional
3172 keyword argument command."""
3173 kw = {"borderwidth": 2, "textvariable": variable,
3174 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3175 "highlightthickness": 2}
3176 Widget.__init__(self, master, "menubutton", kw)
3177 self.widgetName = 'tk_optionMenu'
3178 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3179 self.menuname = menu._w
3180 # 'command' is the only supported keyword
3181 callback = kwargs.get('command')
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00003182 if 'command' in kwargs:
Georg Brandl33cece02008-05-20 06:58:21 +00003183 del kwargs['command']
3184 if kwargs:
3185 raise TclError, 'unknown option -'+kwargs.keys()[0]
3186 menu.add_command(label=value,
3187 command=_setit(variable, value, callback))
3188 for v in values:
3189 menu.add_command(label=v,
3190 command=_setit(variable, v, callback))
3191 self["menu"] = menu
3192
3193 def __getitem__(self, name):
3194 if name == 'menu':
3195 return self.__menu
3196 return Widget.__getitem__(self, name)
3197
3198 def destroy(self):
3199 """Destroy this widget and the associated menu."""
3200 Menubutton.destroy(self)
3201 self.__menu = None
3202
3203class Image:
3204 """Base class for images."""
3205 _last_id = 0
3206 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3207 self.name = None
3208 if not master:
3209 master = _default_root
3210 if not master:
3211 raise RuntimeError, 'Too early to create image'
3212 self.tk = master.tk
3213 if not name:
3214 Image._last_id += 1
3215 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
3216 # The following is needed for systems where id(x)
3217 # can return a negative number, such as Linux/m68k:
3218 if name[0] == '-': name = '_' + name[1:]
3219 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3220 elif kw: cnf = kw
3221 options = ()
3222 for k, v in cnf.items():
Benjamin Petersonde055992009-10-09 22:05:45 +00003223 if hasattr(v, '__call__'):
Georg Brandl33cece02008-05-20 06:58:21 +00003224 v = self._register(v)
3225 options = options + ('-'+k, v)
3226 self.tk.call(('image', 'create', imgtype, name,) + options)
3227 self.name = name
3228 def __str__(self): return self.name
3229 def __del__(self):
3230 if self.name:
3231 try:
3232 self.tk.call('image', 'delete', self.name)
3233 except TclError:
3234 # May happen if the root was destroyed
3235 pass
3236 def __setitem__(self, key, value):
3237 self.tk.call(self.name, 'configure', '-'+key, value)
3238 def __getitem__(self, key):
3239 return self.tk.call(self.name, 'configure', '-'+key)
3240 def configure(self, **kw):
3241 """Configure the image."""
3242 res = ()
3243 for k, v in _cnfmerge(kw).items():
3244 if v is not None:
3245 if k[-1] == '_': k = k[:-1]
Benjamin Petersonde055992009-10-09 22:05:45 +00003246 if hasattr(v, '__call__'):
Georg Brandl33cece02008-05-20 06:58:21 +00003247 v = self._register(v)
3248 res = res + ('-'+k, v)
3249 self.tk.call((self.name, 'config') + res)
3250 config = configure
3251 def height(self):
3252 """Return the height of the image."""
3253 return getint(
3254 self.tk.call('image', 'height', self.name))
3255 def type(self):
3256 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3257 return self.tk.call('image', 'type', self.name)
3258 def width(self):
3259 """Return the width of the image."""
3260 return getint(
3261 self.tk.call('image', 'width', self.name))
3262
3263class PhotoImage(Image):
3264 """Widget which can display colored images in GIF, PPM/PGM format."""
3265 def __init__(self, name=None, cnf={}, master=None, **kw):
3266 """Create an image with NAME.
3267
3268 Valid resource names: data, format, file, gamma, height, palette,
3269 width."""
3270 Image.__init__(self, 'photo', name, cnf, master, **kw)
3271 def blank(self):
3272 """Display a transparent image."""
3273 self.tk.call(self.name, 'blank')
3274 def cget(self, option):
3275 """Return the value of OPTION."""
3276 return self.tk.call(self.name, 'cget', '-' + option)
3277 # XXX config
3278 def __getitem__(self, key):
3279 return self.tk.call(self.name, 'cget', '-' + key)
3280 # XXX copy -from, -to, ...?
3281 def copy(self):
3282 """Return a new PhotoImage with the same image as this widget."""
3283 destImage = PhotoImage()
3284 self.tk.call(destImage, 'copy', self.name)
3285 return destImage
3286 def zoom(self,x,y=''):
3287 """Return a new PhotoImage with the same image as this widget
3288 but zoom it with X and Y."""
3289 destImage = PhotoImage()
3290 if y=='': y=x
3291 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3292 return destImage
3293 def subsample(self,x,y=''):
3294 """Return a new PhotoImage based on the same image as this widget
3295 but use only every Xth or Yth pixel."""
3296 destImage = PhotoImage()
3297 if y=='': y=x
3298 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3299 return destImage
3300 def get(self, x, y):
3301 """Return the color (red, green, blue) of the pixel at X,Y."""
3302 return self.tk.call(self.name, 'get', x, y)
3303 def put(self, data, to=None):
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00003304 """Put row formatted colors to image starting from
Georg Brandl33cece02008-05-20 06:58:21 +00003305 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3306 args = (self.name, 'put', data)
3307 if to:
3308 if to[0] == '-to':
3309 to = to[1:]
3310 args = args + ('-to',) + tuple(to)
3311 self.tk.call(args)
3312 # XXX read
3313 def write(self, filename, format=None, from_coords=None):
3314 """Write image to file FILENAME in FORMAT starting from
3315 position FROM_COORDS."""
3316 args = (self.name, 'write', filename)
3317 if format:
3318 args = args + ('-format', format)
3319 if from_coords:
3320 args = args + ('-from',) + tuple(from_coords)
3321 self.tk.call(args)
3322
3323class BitmapImage(Image):
3324 """Widget which can display a bitmap."""
3325 def __init__(self, name=None, cnf={}, master=None, **kw):
3326 """Create a bitmap with NAME.
3327
3328 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3329 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
3330
3331def image_names(): return _default_root.tk.call('image', 'names')
3332def image_types(): return _default_root.tk.call('image', 'types')
3333
3334
Guilherme Poloe45f0172009-08-14 14:36:45 +00003335class Spinbox(Widget, XView):
Georg Brandl33cece02008-05-20 06:58:21 +00003336 """spinbox widget."""
3337 def __init__(self, master=None, cnf={}, **kw):
3338 """Construct a spinbox widget with the parent MASTER.
3339
3340 STANDARD OPTIONS
3341
3342 activebackground, background, borderwidth,
3343 cursor, exportselection, font, foreground,
3344 highlightbackground, highlightcolor,
3345 highlightthickness, insertbackground,
3346 insertborderwidth, insertofftime,
3347 insertontime, insertwidth, justify, relief,
3348 repeatdelay, repeatinterval,
3349 selectbackground, selectborderwidth
3350 selectforeground, takefocus, textvariable
3351 xscrollcommand.
3352
3353 WIDGET-SPECIFIC OPTIONS
3354
3355 buttonbackground, buttoncursor,
3356 buttondownrelief, buttonuprelief,
3357 command, disabledbackground,
3358 disabledforeground, format, from,
3359 invalidcommand, increment,
3360 readonlybackground, state, to,
3361 validate, validatecommand values,
3362 width, wrap,
3363 """
3364 Widget.__init__(self, master, 'spinbox', cnf, kw)
3365
3366 def bbox(self, index):
3367 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3368 rectangle which encloses the character given by index.
3369
3370 The first two elements of the list give the x and y
3371 coordinates of the upper-left corner of the screen
3372 area covered by the character (in pixels relative
3373 to the widget) and the last two elements give the
3374 width and height of the character, in pixels. The
3375 bounding box may refer to a region outside the
3376 visible area of the window.
3377 """
3378 return self.tk.call(self._w, 'bbox', index)
3379
3380 def delete(self, first, last=None):
3381 """Delete one or more elements of the spinbox.
3382
3383 First is the index of the first character to delete,
3384 and last is the index of the character just after
3385 the last one to delete. If last isn't specified it
3386 defaults to first+1, i.e. a single character is
3387 deleted. This command returns an empty string.
3388 """
3389 return self.tk.call(self._w, 'delete', first, last)
3390
3391 def get(self):
3392 """Returns the spinbox's string"""
3393 return self.tk.call(self._w, 'get')
3394
3395 def icursor(self, index):
3396 """Alter the position of the insertion cursor.
3397
3398 The insertion cursor will be displayed just before
3399 the character given by index. Returns an empty string
3400 """
3401 return self.tk.call(self._w, 'icursor', index)
3402
3403 def identify(self, x, y):
3404 """Returns the name of the widget at position x, y
3405
3406 Return value is one of: none, buttondown, buttonup, entry
3407 """
3408 return self.tk.call(self._w, 'identify', x, y)
3409
3410 def index(self, index):
3411 """Returns the numerical index corresponding to index
3412 """
3413 return self.tk.call(self._w, 'index', index)
3414
3415 def insert(self, index, s):
3416 """Insert string s at index
3417
3418 Returns an empty string.
3419 """
3420 return self.tk.call(self._w, 'insert', index, s)
3421
3422 def invoke(self, element):
3423 """Causes the specified element to be invoked
3424
3425 The element could be buttondown or buttonup
3426 triggering the action associated with it.
3427 """
3428 return self.tk.call(self._w, 'invoke', element)
3429
3430 def scan(self, *args):
3431 """Internal function."""
3432 return self._getints(
3433 self.tk.call((self._w, 'scan') + args)) or ()
3434
3435 def scan_mark(self, x):
3436 """Records x and the current view in the spinbox window;
3437
3438 used in conjunction with later scan dragto commands.
3439 Typically this command is associated with a mouse button
3440 press in the widget. It returns an empty string.
3441 """
3442 return self.scan("mark", x)
3443
3444 def scan_dragto(self, x):
3445 """Compute the difference between the given x argument
3446 and the x argument to the last scan mark command
3447
3448 It then adjusts the view left or right by 10 times the
3449 difference in x-coordinates. This command is typically
3450 associated with mouse motion events in the widget, to
3451 produce the effect of dragging the spinbox at high speed
3452 through the window. The return value is an empty string.
3453 """
3454 return self.scan("dragto", x)
3455
3456 def selection(self, *args):
3457 """Internal function."""
3458 return self._getints(
3459 self.tk.call((self._w, 'selection') + args)) or ()
3460
3461 def selection_adjust(self, index):
3462 """Locate the end of the selection nearest to the character
3463 given by index,
3464
3465 Then adjust that end of the selection to be at index
3466 (i.e including but not going beyond index). The other
3467 end of the selection is made the anchor point for future
3468 select to commands. If the selection isn't currently in
3469 the spinbox, then a new selection is created to include
3470 the characters between index and the most recent selection
3471 anchor point, inclusive. Returns an empty string.
3472 """
3473 return self.selection("adjust", index)
3474
3475 def selection_clear(self):
3476 """Clear the selection
3477
3478 If the selection isn't in this widget then the
3479 command has no effect. Returns an empty string.
3480 """
3481 return self.selection("clear")
3482
3483 def selection_element(self, element=None):
3484 """Sets or gets the currently selected element.
3485
3486 If a spinbutton element is specified, it will be
3487 displayed depressed
3488 """
3489 return self.selection("element", element)
3490
3491###########################################################################
3492
3493class LabelFrame(Widget):
3494 """labelframe widget."""
3495 def __init__(self, master=None, cnf={}, **kw):
3496 """Construct a labelframe widget with the parent MASTER.
3497
3498 STANDARD OPTIONS
3499
3500 borderwidth, cursor, font, foreground,
3501 highlightbackground, highlightcolor,
3502 highlightthickness, padx, pady, relief,
3503 takefocus, text
3504
3505 WIDGET-SPECIFIC OPTIONS
3506
3507 background, class, colormap, container,
3508 height, labelanchor, labelwidget,
3509 visual, width
3510 """
3511 Widget.__init__(self, master, 'labelframe', cnf, kw)
3512
3513########################################################################
3514
3515class PanedWindow(Widget):
3516 """panedwindow widget."""
3517 def __init__(self, master=None, cnf={}, **kw):
3518 """Construct a panedwindow widget with the parent MASTER.
3519
3520 STANDARD OPTIONS
3521
3522 background, borderwidth, cursor, height,
3523 orient, relief, width
3524
3525 WIDGET-SPECIFIC OPTIONS
3526
3527 handlepad, handlesize, opaqueresize,
3528 sashcursor, sashpad, sashrelief,
3529 sashwidth, showhandle,
3530 """
3531 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3532
3533 def add(self, child, **kw):
3534 """Add a child widget to the panedwindow in a new pane.
3535
3536 The child argument is the name of the child widget
3537 followed by pairs of arguments that specify how to
Guilherme Polo1c6787f2009-05-31 21:31:21 +00003538 manage the windows. The possible options and values
3539 are the ones accepted by the paneconfigure method.
Georg Brandl33cece02008-05-20 06:58:21 +00003540 """
3541 self.tk.call((self._w, 'add', child) + self._options(kw))
3542
3543 def remove(self, child):
3544 """Remove the pane containing child from the panedwindow
3545
3546 All geometry management options for child will be forgotten.
3547 """
3548 self.tk.call(self._w, 'forget', child)
3549 forget=remove
3550
3551 def identify(self, x, y):
3552 """Identify the panedwindow component at point x, y
3553
3554 If the point is over a sash or a sash handle, the result
3555 is a two element list containing the index of the sash or
3556 handle, and a word indicating whether it is over a sash
3557 or a handle, such as {0 sash} or {2 handle}. If the point
3558 is over any other part of the panedwindow, the result is
3559 an empty list.
3560 """
3561 return self.tk.call(self._w, 'identify', x, y)
3562
3563 def proxy(self, *args):
3564 """Internal function."""
3565 return self._getints(
3566 self.tk.call((self._w, 'proxy') + args)) or ()
3567
3568 def proxy_coord(self):
3569 """Return the x and y pair of the most recent proxy location
3570 """
3571 return self.proxy("coord")
3572
3573 def proxy_forget(self):
3574 """Remove the proxy from the display.
3575 """
3576 return self.proxy("forget")
3577
3578 def proxy_place(self, x, y):
3579 """Place the proxy at the given x and y coordinates.
3580 """
3581 return self.proxy("place", x, y)
3582
3583 def sash(self, *args):
3584 """Internal function."""
3585 return self._getints(
3586 self.tk.call((self._w, 'sash') + args)) or ()
3587
3588 def sash_coord(self, index):
3589 """Return the current x and y pair for the sash given by index.
3590
3591 Index must be an integer between 0 and 1 less than the
3592 number of panes in the panedwindow. The coordinates given are
3593 those of the top left corner of the region containing the sash.
3594 pathName sash dragto index x y This command computes the
3595 difference between the given coordinates and the coordinates
3596 given to the last sash coord command for the given sash. It then
3597 moves that sash the computed difference. The return value is the
3598 empty string.
3599 """
3600 return self.sash("coord", index)
3601
3602 def sash_mark(self, index):
3603 """Records x and y for the sash given by index;
3604
3605 Used in conjunction with later dragto commands to move the sash.
3606 """
3607 return self.sash("mark", index)
3608
3609 def sash_place(self, index, x, y):
3610 """Place the sash given by index at the given coordinates
3611 """
3612 return self.sash("place", index, x, y)
3613
3614 def panecget(self, child, option):
3615 """Query a management option for window.
3616
3617 Option may be any value allowed by the paneconfigure subcommand
3618 """
3619 return self.tk.call(
3620 (self._w, 'panecget') + (child, '-'+option))
3621
3622 def paneconfigure(self, tagOrId, cnf=None, **kw):
3623 """Query or modify the management options for window.
3624
3625 If no option is specified, returns a list describing all
3626 of the available options for pathName. If option is
3627 specified with no value, then the command returns a list
3628 describing the one named option (this list will be identical
3629 to the corresponding sublist of the value returned if no
3630 option is specified). If one or more option-value pairs are
3631 specified, then the command modifies the given widget
3632 option(s) to have the given value(s); in this case the
3633 command returns an empty string. The following options
3634 are supported:
3635
3636 after window
3637 Insert the window after the window specified. window
3638 should be the name of a window already managed by pathName.
3639 before window
3640 Insert the window before the window specified. window
3641 should be the name of a window already managed by pathName.
3642 height size
3643 Specify a height for the window. The height will be the
3644 outer dimension of the window including its border, if
3645 any. If size is an empty string, or if -height is not
3646 specified, then the height requested internally by the
3647 window will be used initially; the height may later be
3648 adjusted by the movement of sashes in the panedwindow.
3649 Size may be any value accepted by Tk_GetPixels.
3650 minsize n
3651 Specifies that the size of the window cannot be made
3652 less than n. This constraint only affects the size of
3653 the widget in the paned dimension -- the x dimension
3654 for horizontal panedwindows, the y dimension for
3655 vertical panedwindows. May be any value accepted by
3656 Tk_GetPixels.
3657 padx n
3658 Specifies a non-negative value indicating how much
3659 extra space to leave on each side of the window in
3660 the X-direction. The value may have any of the forms
3661 accepted by Tk_GetPixels.
3662 pady n
3663 Specifies a non-negative value indicating how much
3664 extra space to leave on each side of the window in
3665 the Y-direction. The value may have any of the forms
3666 accepted by Tk_GetPixels.
3667 sticky style
3668 If a window's pane is larger than the requested
3669 dimensions of the window, this option may be used
3670 to position (or stretch) the window within its pane.
3671 Style is a string that contains zero or more of the
3672 characters n, s, e or w. The string can optionally
3673 contains spaces or commas, but they are ignored. Each
3674 letter refers to a side (north, south, east, or west)
3675 that the window will "stick" to. If both n and s
3676 (or e and w) are specified, the window will be
3677 stretched to fill the entire height (or width) of
3678 its cavity.
3679 width size
3680 Specify a width for the window. The width will be
3681 the outer dimension of the window including its
3682 border, if any. If size is an empty string, or
3683 if -width is not specified, then the width requested
3684 internally by the window will be used initially; the
3685 width may later be adjusted by the movement of sashes
3686 in the panedwindow. Size may be any value accepted by
3687 Tk_GetPixels.
3688
3689 """
3690 if cnf is None and not kw:
3691 cnf = {}
3692 for x in self.tk.split(
3693 self.tk.call(self._w,
3694 'paneconfigure', tagOrId)):
3695 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3696 return cnf
3697 if type(cnf) == StringType and not kw:
3698 x = self.tk.split(self.tk.call(
3699 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3700 return (x[0][1:],) + x[1:]
3701 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3702 self._options(cnf, kw))
3703 paneconfig = paneconfigure
3704
3705 def panes(self):
3706 """Returns an ordered list of the child panes."""
3707 return self.tk.call(self._w, 'panes')
3708
3709######################################################################
3710# Extensions:
3711
3712class Studbutton(Button):
3713 def __init__(self, master=None, cnf={}, **kw):
3714 Widget.__init__(self, master, 'studbutton', cnf, kw)
3715 self.bind('<Any-Enter>', self.tkButtonEnter)
3716 self.bind('<Any-Leave>', self.tkButtonLeave)
3717 self.bind('<1>', self.tkButtonDown)
3718 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3719
3720class Tributton(Button):
3721 def __init__(self, master=None, cnf={}, **kw):
3722 Widget.__init__(self, master, 'tributton', cnf, kw)
3723 self.bind('<Any-Enter>', self.tkButtonEnter)
3724 self.bind('<Any-Leave>', self.tkButtonLeave)
3725 self.bind('<1>', self.tkButtonDown)
3726 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3727 self['fg'] = self['bg']
3728 self['activebackground'] = self['bg']
3729
3730######################################################################
3731# Test:
3732
3733def _test():
3734 root = Tk()
3735 text = "This is Tcl/Tk version %s" % TclVersion
3736 if TclVersion >= 8.1:
3737 try:
3738 text = text + unicode("\nThis should be a cedilla: \347",
3739 "iso-8859-1")
3740 except NameError:
3741 pass # no unicode support
3742 label = Label(root, text=text)
3743 label.pack()
3744 test = Button(root, text="Click me!",
3745 command=lambda root=root: root.test.configure(
3746 text="[%s]" % root.test['text']))
3747 test.pack()
3748 root.test = test
3749 quit = Button(root, text="QUIT", command=root.destroy)
3750 quit.pack()
3751 # The following three commands are needed so the window pops
3752 # up on top on Windows...
3753 root.iconify()
3754 root.update()
3755 root.deiconify()
3756 root.mainloop()
3757
3758if __name__ == '__main__':
3759 _test()