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