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