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