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