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