Debian Codegraph @

Lib/tkinter/__init__.py

raw ◀ ▶
1 Debian patch touch this file
1 """Wrapper functions for Tcl/Tk.
2
3 Tkinter provides classes which allow the display, positioning and
4 control of widgets. Toplevel widgets are Tk and Toplevel. Other
5 widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
6 Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
7 LabelFrame and PanedWindow.
8
9 Properties of the widgets are specified with keyword arguments.
10 Keyword arguments have the same name as the corresponding options
11 under Tk.
12
13 Widgets are positioned with one of the geometry managers Place, Pack
14 or Grid. These managers can be called with methods place, pack, grid
15 available in every Widget.
16
17 Actions are bound to events by options (e.g. the command
18 keyword argument) or with the bind() method.
19
20 Example (Hello, World):
21 import tkinter
22 from tkinter.constants import *
23 tk = tkinter.Tk()
24 frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25 frame.pack(fill=BOTH, expand=1)
26 label = tkinter.Label(frame, text="Hello, World")
27 label.pack(fill=X, expand=1)
28 button = tkinter.Button(frame, text="Exit", command=tk.destroy)
29 button.pack(side=BOTTOM)
30 tk.mainloop()
31 """
32
33 import collections
34 import enum
35 import sys
36 import types
37
•38 try:
39 import _tkinter
40 except ImportError as msg:
41 raise ImportError(str(msg) + ', please install the python3-tk package')
42 TclError = _tkinter.TclError
43 from tkinter.constants import *
44 import re
45
46 wantobjects = 1
47 _debug = False # set to True to print executed Tcl/Tk commands
48
49 TkVersion = float(_tkinter.TK_VERSION)
50 TclVersion = float(_tkinter.TCL_VERSION)
51
52 READABLE = _tkinter.READABLE
53 WRITABLE = _tkinter.WRITABLE
54 EXCEPTION = _tkinter.EXCEPTION
55
56
57 _magic_re = re.compile(r'([\\{}])')
58 _space_re = re.compile(r'([\s])', re.ASCII)
59
60
61 def _join(value):
62 """Internal function."""
63 return ' '.join(map(_stringify, value))
64
65
66 def _stringify(value):
67 """Internal function."""
68 if isinstance(value, (list, tuple)):
69 if len(value) == 1:
70 value = _stringify(value[0])
71 if _magic_re.search(value):
72 value = '{%s}' % value
73 else:
74 value = '{%s}' % _join(value)
75 else:
76 if isinstance(value, bytes):
77 value = str(value, 'latin1')
78 else:
79 value = str(value)
80 if not value:
81 value = '{}'
82 elif _magic_re.search(value):
83 # add '\' before special characters and spaces
84 value = _magic_re.sub(r'\\\1', value)
85 value = value.replace('\n', r'\n')
86 value = _space_re.sub(r'\\\1', value)
87 if value[0] == '"':
88 value = '\\' + value
89 elif value[0] == '"' or _space_re.search(value):
90 value = '{%s}' % value
91 return value
92
93
94 def _flatten(seq):
95 """Internal function."""
96 res = ()
97 for item in seq:
98 if isinstance(item, (tuple, list)):
99 res = res + _flatten(item)
100 elif item is not None:
101 res = res + (item,)
102 return res
103
104
105 try: _flatten = _tkinter._flatten
106 except AttributeError: pass
107
108
109 def _cnfmerge(cnfs):
110 """Internal function."""
111 if isinstance(cnfs, dict):
112 return cnfs
113 elif isinstance(cnfs, (type(None), str)):
114 return cnfs
115 else:
116 cnf = {}
117 for c in _flatten(cnfs):
118 try:
119 cnf.update(c)
120 except (AttributeError, TypeError) as msg:
121 print("_cnfmerge: fallback due to:", msg)
122 for k, v in c.items():
123 cnf[k] = v
124 return cnf
125
126
127 try: _cnfmerge = _tkinter._cnfmerge
128 except AttributeError: pass
129
130
131 def _splitdict(tk, v, cut_minus=True, conv=None):
132 """Return a properly formatted dict built from Tcl list pairs.
133
134 If cut_minus is True, the supposed '-' prefix will be removed from
135 keys. If conv is specified, it is used to convert values.
136
137 Tcl list is expected to contain an even number of elements.
138 """
139 t = tk.splitlist(v)
140 if len(t) % 2:
141 raise RuntimeError('Tcl list representing a dict is expected '
142 'to contain an even number of elements')
143 it = iter(t)
144 dict = {}
145 for key, value in zip(it, it):
146 key = str(key)
147 if cut_minus and key[0] == '-':
148 key = key[1:]
149 if conv:
150 value = conv(value)
151 dict[key] = value
152 return dict
153
154 class _VersionInfoType(collections.namedtuple('_VersionInfoType',
155 ('major', 'minor', 'micro', 'releaselevel', 'serial'))):
156 def __str__(self):
157 if self.releaselevel == 'final':
158 return f'{self.major}.{self.minor}.{self.micro}'
159 else:
160 return f'{self.major}.{self.minor}{self.releaselevel[0]}{self.serial}'
161
162 def _parse_version(version):
163 import re
164 m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', version)
165 major, minor, releaselevel, serial = m.groups()
166 major, minor, serial = int(major), int(minor), int(serial)
167 if releaselevel == '.':
168 micro = serial
169 serial = 0
170 releaselevel = 'final'
171 else:
172 micro = 0
173 releaselevel = {'a': 'alpha', 'b': 'beta'}[releaselevel]
174 return _VersionInfoType(major, minor, micro, releaselevel, serial)
175
176
177 @enum._simple_enum(enum.StrEnum)
178 class EventType:
179 KeyPress = '2'
180 Key = KeyPress
181 KeyRelease = '3'
182 ButtonPress = '4'
183 Button = ButtonPress
184 ButtonRelease = '5'
185 Motion = '6'
186 Enter = '7'
187 Leave = '8'
188 FocusIn = '9'
189 FocusOut = '10'
190 Keymap = '11' # undocumented
191 Expose = '12'
192 GraphicsExpose = '13' # undocumented
193 NoExpose = '14' # undocumented
194 Visibility = '15'
195 Create = '16'
196 Destroy = '17'
197 Unmap = '18'
198 Map = '19'
199 MapRequest = '20'
200 Reparent = '21'
201 Configure = '22'
202 ConfigureRequest = '23'
203 Gravity = '24'
204 ResizeRequest = '25'
205 Circulate = '26'
206 CirculateRequest = '27'
207 Property = '28'
208 SelectionClear = '29' # undocumented
209 SelectionRequest = '30' # undocumented
210 Selection = '31' # undocumented
211 Colormap = '32'
212 ClientMessage = '33' # undocumented
213 Mapping = '34' # undocumented
214 VirtualEvent = '35' # undocumented
215 Activate = '36'
216 Deactivate = '37'
217 MouseWheel = '38'
218
219
220 class Event:
221 """Container for the properties of an event.
222
223 Instances of this type are generated if one of the following events occurs:
224
225 KeyPress, KeyRelease - for keyboard events
226 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
227 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
228 Colormap, Gravity, Reparent, Property, Destroy, Activate,
229 Deactivate - for window events.
230
231 If a callback function for one of these events is registered
232 using bind, bind_all, bind_class, or tag_bind, the callback is
233 called with an Event as first argument. It will have the
234 following attributes (in braces are the event types for which
235 the attribute is valid):
236
237 serial - serial number of event
238 num - mouse button pressed (ButtonPress, ButtonRelease)
239 focus - whether the window has the focus (Enter, Leave)
240 height - height of the exposed window (Configure, Expose)
241 width - width of the exposed window (Configure, Expose)
242 keycode - keycode of the pressed key (KeyPress, KeyRelease)
243 state - state of the event as a number (ButtonPress, ButtonRelease,
244 Enter, KeyPress, KeyRelease,
245 Leave, Motion)
246 state - state as a string (Visibility)
247 time - when the event occurred
248 x - x-position of the mouse
249 y - y-position of the mouse
250 x_root - x-position of the mouse on the screen
251 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
252 y_root - y-position of the mouse on the screen
253 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
254 char - pressed character (KeyPress, KeyRelease)
255 send_event - see X/Windows documentation
256 keysym - keysym of the event as a string (KeyPress, KeyRelease)
257 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
258 type - type of the event as a number
259 widget - widget in which the event occurred
260 delta - delta of wheel movement (MouseWheel)
261 """
262
263 def __repr__(self):
264 attrs = {k: v for k, v in self.__dict__.items() if v != '??'}
265 if not self.char:
266 del attrs['char']
267 elif self.char != '??':
268 attrs['char'] = repr(self.char)
269 if not getattr(self, 'send_event', True):
270 del attrs['send_event']
271 if self.state == 0:
272 del attrs['state']
273 elif isinstance(self.state, int):
274 state = self.state
275 mods = ('Shift', 'Lock', 'Control',
276 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5',
277 'Button1', 'Button2', 'Button3', 'Button4', 'Button5')
278 s = []
279 for i, n in enumerate(mods):
280 if state & (1 << i):
281 s.append(n)
282 state = state & ~((1<< len(mods)) - 1)
283 if state or not s:
284 s.append(hex(state))
285 attrs['state'] = '|'.join(s)
286 if self.delta == 0:
287 del attrs['delta']
288 # widget usually is known
289 # serial and time are not very interesting
290 # keysym_num duplicates keysym
291 # x_root and y_root mostly duplicate x and y
292 keys = ('send_event',
293 'state', 'keysym', 'keycode', 'char',
294 'num', 'delta', 'focus',
295 'x', 'y', 'width', 'height')
296 return '<%s event%s>' % (
297 getattr(self.type, 'name', self.type),
298 ''.join(' %s=%s' % (k, attrs[k]) for k in keys if k in attrs)
299 )
300
301
302 _support_default_root = True
303 _default_root = None
304
305
306 def NoDefaultRoot():
307 """Inhibit setting of default root window.
308
309 Call this function to inhibit that the first instance of
310 Tk is used for windows without an explicit parent window.
311 """
312 global _support_default_root, _default_root
313 _support_default_root = False
314 # Delete, so any use of _default_root will immediately raise an exception.
315 # Rebind before deletion, so repeated calls will not fail.
316 _default_root = None
317 del _default_root
318
319
320 def _get_default_root(what=None):
321 if not _support_default_root:
322 raise RuntimeError("No master specified and tkinter is "
323 "configured to not support default root")
324 if _default_root is None:
325 if what:
326 raise RuntimeError(f"Too early to {what}: no default root window")
327 root = Tk()
328 assert _default_root is root
329 return _default_root
330
331
332 def _get_temp_root():
333 global _support_default_root
334 if not _support_default_root:
335 raise RuntimeError("No master specified and tkinter is "
336 "configured to not support default root")
337 root = _default_root
338 if root is None:
339 assert _support_default_root
340 _support_default_root = False
341 root = Tk()
342 _support_default_root = True
343 assert _default_root is None
344 root.withdraw()
345 root._temporary = True
346 return root
347
348
349 def _destroy_temp_root(master):
350 if getattr(master, '_temporary', False):
351 try:
352 master.destroy()
353 except TclError:
354 pass
355
356
357 def _tkerror(err):
358 """Internal function."""
359 pass
360
361
362 def _exit(code=0):
363 """Internal function. Calling it will raise the exception SystemExit."""
364 try:
365 code = int(code)
366 except ValueError:
367 pass
368 raise SystemExit(code)
369
370
371 _varnum = 0
372
373
374 class Variable:
375 """Class to define value holders for e.g. buttons.
376
377 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
378 that constrain the type of the value returned from get()."""
379 _default = ""
380 _tk = None
381 _tclCommands = None
382
383 def __init__(self, master=None, value=None, name=None):
384 """Construct a variable
385
386 MASTER can be given as master widget.
387 VALUE is an optional value (defaults to "")
388 NAME is an optional Tcl name (defaults to PY_VARnum).
389
390 If NAME matches an existing variable and VALUE is omitted
391 then the existing value is retained.
392 """
393 # check for type of NAME parameter to override weird error message
394 # raised from Modules/_tkinter.c:SetVar like:
395 # TypeError: setvar() takes exactly 3 arguments (2 given)
396 if name is not None and not isinstance(name, str):
397 raise TypeError("name must be a string")
398 global _varnum
399 if master is None:
400 master = _get_default_root('create variable')
401 self._root = master._root()
402 self._tk = master.tk
403 if name:
404 self._name = name
405 else:
406 self._name = 'PY_VAR' + repr(_varnum)
407 _varnum += 1
408 if value is not None:
409 self.initialize(value)
410 elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)):
411 self.initialize(self._default)
412
413 def __del__(self):
414 """Unset the variable in Tcl."""
415 if self._tk is None:
416 return
417 if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
418 self._tk.globalunsetvar(self._name)
419 if self._tclCommands is not None:
420 for name in self._tclCommands:
421 self._tk.deletecommand(name)
422 self._tclCommands = None
423
424 def __str__(self):
425 """Return the name of the variable in Tcl."""
426 return self._name
427
428 def set(self, value):
429 """Set the variable to VALUE."""
430 return self._tk.globalsetvar(self._name, value)
431
432 initialize = set
433
434 def get(self):
435 """Return value of variable."""
436 return self._tk.globalgetvar(self._name)
437
438 def _register(self, callback):
439 f = CallWrapper(callback, None, self._root).__call__
440 cbname = repr(id(f))
441 try:
442 callback = callback.__func__
443 except AttributeError:
444 pass
445 try:
446 cbname = cbname + callback.__name__
447 except AttributeError:
448 pass
449 self._tk.createcommand(cbname, f)
450 if self._tclCommands is None:
451 self._tclCommands = []
452 self._tclCommands.append(cbname)
453 return cbname
454
455 def trace_add(self, mode, callback):
456 """Define a trace callback for the variable.
457
458 Mode is one of "read", "write", "unset", or a list or tuple of
459 such strings.
460 Callback must be a function which is called when the variable is
461 read, written or unset.
462
463 Return the name of the callback.
464 """
465 cbname = self._register(callback)
466 self._tk.call('trace', 'add', 'variable',
467 self._name, mode, (cbname,))
468 return cbname
469
470 def trace_remove(self, mode, cbname):
471 """Delete the trace callback for a variable.
472
473 Mode is one of "read", "write", "unset" or a list or tuple of
474 such strings. Must be same as were specified in trace_add().
475 cbname is the name of the callback returned from trace_add().
476 """
477 self._tk.call('trace', 'remove', 'variable',
478 self._name, mode, cbname)
479 for m, ca in self.trace_info():
480 if self._tk.splitlist(ca)[0] == cbname:
481 break
482 else:
483 self._tk.deletecommand(cbname)
484 try:
485 self._tclCommands.remove(cbname)
486 except ValueError:
487 pass
488
489 def trace_info(self):
490 """Return all trace callback information."""
491 splitlist = self._tk.splitlist
492 return [(splitlist(k), v) for k, v in map(splitlist,
493 splitlist(self._tk.call('trace', 'info', 'variable', self._name)))]
494
495 def trace_variable(self, mode, callback):
496 """Define a trace callback for the variable.
497
498 MODE is one of "r", "w", "u" for read, write, undefine.
499 CALLBACK must be a function which is called when
500 the variable is read, written or undefined.
501
502 Return the name of the callback.
503
504 This deprecated method wraps a deprecated Tcl method that will
505 likely be removed in the future. Use trace_add() instead.
506 """
507 # TODO: Add deprecation warning
508 cbname = self._register(callback)
509 self._tk.call("trace", "variable", self._name, mode, cbname)
510 return cbname
511
512 trace = trace_variable
513
514 def trace_vdelete(self, mode, cbname):
515 """Delete the trace callback for a variable.
516
517 MODE is one of "r", "w", "u" for read, write, undefine.
518 CBNAME is the name of the callback returned from trace_variable or trace.
519
520 This deprecated method wraps a deprecated Tcl method that will
521 likely be removed in the future. Use trace_remove() instead.
522 """
523 # TODO: Add deprecation warning
524 self._tk.call("trace", "vdelete", self._name, mode, cbname)
525 cbname = self._tk.splitlist(cbname)[0]
526 for m, ca in self.trace_info():
527 if self._tk.splitlist(ca)[0] == cbname:
528 break
529 else:
530 self._tk.deletecommand(cbname)
531 try:
532 self._tclCommands.remove(cbname)
533 except ValueError:
534 pass
535
536 def trace_vinfo(self):
537 """Return all trace callback information.
538
539 This deprecated method wraps a deprecated Tcl method that will
540 likely be removed in the future. Use trace_info() instead.
541 """
542 # TODO: Add deprecation warning
543 return [self._tk.splitlist(x) for x in self._tk.splitlist(
544 self._tk.call("trace", "vinfo", self._name))]
545
546 def __eq__(self, other):
547 if not isinstance(other, Variable):
548 return NotImplemented
549 return (self._name == other._name
550 and self.__class__.__name__ == other.__class__.__name__
551 and self._tk == other._tk)
552
553
554 class StringVar(Variable):
555 """Value holder for strings variables."""
556 _default = ""
557
558 def __init__(self, master=None, value=None, name=None):
559 """Construct a string variable.
560
561 MASTER can be given as master widget.
562 VALUE is an optional value (defaults to "")
563 NAME is an optional Tcl name (defaults to PY_VARnum).
564
565 If NAME matches an existing variable and VALUE is omitted
566 then the existing value is retained.
567 """
568 Variable.__init__(self, master, value, name)
569
570 def get(self):
571 """Return value of variable as string."""
572 value = self._tk.globalgetvar(self._name)
573 if isinstance(value, str):
574 return value
575 return str(value)
576
577
578 class IntVar(Variable):
579 """Value holder for integer variables."""
580 _default = 0
581
582 def __init__(self, master=None, value=None, name=None):
583 """Construct an integer variable.
584
585 MASTER can be given as master widget.
586 VALUE is an optional value (defaults to 0)
587 NAME is an optional Tcl name (defaults to PY_VARnum).
588
589 If NAME matches an existing variable and VALUE is omitted
590 then the existing value is retained.
591 """
592 Variable.__init__(self, master, value, name)
593
594 def get(self):
595 """Return the value of the variable as an integer."""
596 value = self._tk.globalgetvar(self._name)
597 try:
598 return self._tk.getint(value)
599 except (TypeError, TclError):
600 return int(self._tk.getdouble(value))
601
602
603 class DoubleVar(Variable):
604 """Value holder for float variables."""
605 _default = 0.0
606
607 def __init__(self, master=None, value=None, name=None):
608 """Construct a float variable.
609
610 MASTER can be given as master widget.
611 VALUE is an optional value (defaults to 0.0)
612 NAME is an optional Tcl name (defaults to PY_VARnum).
613
614 If NAME matches an existing variable and VALUE is omitted
615 then the existing value is retained.
616 """
617 Variable.__init__(self, master, value, name)
618
619 def get(self):
620 """Return the value of the variable as a float."""
621 return self._tk.getdouble(self._tk.globalgetvar(self._name))
622
623
624 class BooleanVar(Variable):
625 """Value holder for boolean variables."""
626 _default = False
627
628 def __init__(self, master=None, value=None, name=None):
629 """Construct a boolean variable.
630
631 MASTER can be given as master widget.
632 VALUE is an optional value (defaults to False)
633 NAME is an optional Tcl name (defaults to PY_VARnum).
634
635 If NAME matches an existing variable and VALUE is omitted
636 then the existing value is retained.
637 """
638 Variable.__init__(self, master, value, name)
639
640 def set(self, value):
641 """Set the variable to VALUE."""
642 return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
643
644 initialize = set
645
646 def get(self):
647 """Return the value of the variable as a bool."""
648 try:
649 return self._tk.getboolean(self._tk.globalgetvar(self._name))
650 except TclError:
651 raise ValueError("invalid literal for getboolean()")
652
653
654 def mainloop(n=0):
655 """Run the main loop of Tcl."""
656 _get_default_root('run the main loop').tk.mainloop(n)
657
658
659 getint = int
660
661 getdouble = float
662
663
664 def getboolean(s):
665 """Convert Tcl object to True or False."""
666 try:
667 return _get_default_root('use getboolean()').tk.getboolean(s)
668 except TclError:
669 raise ValueError("invalid literal for getboolean()")
670
671
672 # Methods defined on both toplevel and interior widgets
673
674 class Misc:
675 """Internal class.
676
677 Base class which defines methods common for interior widgets."""
678
679 # used for generating child widget names
680 _last_child_ids = None
681
682 # XXX font command?
683 _tclCommands = None
684
685 def destroy(self):
686 """Internal function.
687
688 Delete all Tcl commands created for
689 this widget in the Tcl interpreter."""
690 if self._tclCommands is not None:
691 for name in self._tclCommands:
692 self.tk.deletecommand(name)
693 self._tclCommands = None
694
695 def deletecommand(self, name):
696 """Internal function.
697
698 Delete the Tcl command provided in NAME."""
699 self.tk.deletecommand(name)
700 try:
701 self._tclCommands.remove(name)
702 except ValueError:
703 pass
704
705 def tk_strictMotif(self, boolean=None):
706 """Set Tcl internal variable, whether the look and feel
707 should adhere to Motif.
708
709 A parameter of 1 means adhere to Motif (e.g. no color
710 change if mouse passes over slider).
711 Returns the set value."""
712 return self.tk.getboolean(self.tk.call(
713 'set', 'tk_strictMotif', boolean))
714
715 def tk_bisque(self):
716 """Change the color scheme to light brown as used in Tk 3.6 and before."""
717 self.tk.call('tk_bisque')
718
719 def tk_setPalette(self, *args, **kw):
720 """Set a new color scheme for all widget elements.
721
722 A single color as argument will cause that all colors of Tk
723 widget elements are derived from this.
724 Alternatively several keyword parameters and its associated
725 colors can be given. The following keywords are valid:
726 activeBackground, foreground, selectColor,
727 activeForeground, highlightBackground, selectBackground,
728 background, highlightColor, selectForeground,
729 disabledForeground, insertBackground, troughColor."""
730 self.tk.call(('tk_setPalette',)
731 + _flatten(args) + _flatten(list(kw.items())))
732
733 def wait_variable(self, name='PY_VAR'):
734 """Wait until the variable is modified.
735
736 A parameter of type IntVar, StringVar, DoubleVar or
737 BooleanVar must be given."""
738 self.tk.call('tkwait', 'variable', name)
739 waitvar = wait_variable # XXX b/w compat
740
741 def wait_window(self, window=None):
742 """Wait until a WIDGET is destroyed.
743
744 If no parameter is given self is used."""
745 if window is None:
746 window = self
747 self.tk.call('tkwait', 'window', window._w)
748
749 def wait_visibility(self, window=None):
750 """Wait until the visibility of a WIDGET changes
751 (e.g. it appears).
752
753 If no parameter is given self is used."""
754 if window is None:
755 window = self
756 self.tk.call('tkwait', 'visibility', window._w)
757
758 def setvar(self, name='PY_VAR', value='1'):
759 """Set Tcl variable NAME to VALUE."""
760 self.tk.setvar(name, value)
761
762 def getvar(self, name='PY_VAR'):
763 """Return value of Tcl variable NAME."""
764 return self.tk.getvar(name)
765
766 def getint(self, s):
767 try:
768 return self.tk.getint(s)
769 except TclError as exc:
770 raise ValueError(str(exc))
771
772 def getdouble(self, s):
773 try:
774 return self.tk.getdouble(s)
775 except TclError as exc:
776 raise ValueError(str(exc))
777
778 def getboolean(self, s):
779 """Return a boolean value for Tcl boolean values true and false given as parameter."""
780 try:
781 return self.tk.getboolean(s)
782 except TclError:
783 raise ValueError("invalid literal for getboolean()")
784
785 def focus_set(self):
786 """Direct input focus to this widget.
787
788 If the application currently does not have the focus
789 this widget will get the focus if the application gets
790 the focus through the window manager."""
791 self.tk.call('focus', self._w)
792 focus = focus_set # XXX b/w compat?
793
794 def focus_force(self):
795 """Direct input focus to this widget even if the
796 application does not have the focus. Use with
797 caution!"""
798 self.tk.call('focus', '-force', self._w)
799
800 def focus_get(self):
801 """Return the widget which has currently the focus in the
802 application.
803
804 Use focus_displayof to allow working with several
805 displays. Return None if application does not have
806 the focus."""
807 name = self.tk.call('focus')
808 if name == 'none' or not name: return None
809 return self._nametowidget(name)
810
811 def focus_displayof(self):
812 """Return the widget which has currently the focus on the
813 display where this widget is located.
814
815 Return None if the application does not have the focus."""
816 name = self.tk.call('focus', '-displayof', self._w)
817 if name == 'none' or not name: return None
818 return self._nametowidget(name)
819
820 def focus_lastfor(self):
821 """Return the widget which would have the focus if top level
822 for this widget gets the focus from the window manager."""
823 name = self.tk.call('focus', '-lastfor', self._w)
824 if name == 'none' or not name: return None
825 return self._nametowidget(name)
826
827 def tk_focusFollowsMouse(self):
828 """The widget under mouse will get automatically focus. Can not
829 be disabled easily."""
830 self.tk.call('tk_focusFollowsMouse')
831
832 def tk_focusNext(self):
833 """Return the next widget in the focus order which follows
834 widget which has currently the focus.
835
836 The focus order first goes to the next child, then to
837 the children of the child recursively and then to the
838 next sibling which is higher in the stacking order. A
839 widget is omitted if it has the takefocus option set
840 to 0."""
841 name = self.tk.call('tk_focusNext', self._w)
842 if not name: return None
843 return self._nametowidget(name)
844
845 def tk_focusPrev(self):
846 """Return previous widget in the focus order. See tk_focusNext for details."""
847 name = self.tk.call('tk_focusPrev', self._w)
848 if not name: return None
849 return self._nametowidget(name)
850
851 def after(self, ms, func=None, *args):
852 """Call function once after given time.
853
854 MS specifies the time in milliseconds. FUNC gives the
855 function which shall be called. Additional parameters
856 are given as parameters to the function call. Return
857 identifier to cancel scheduling with after_cancel."""
858 if func is None:
859 # I'd rather use time.sleep(ms*0.001)
860 self.tk.call('after', ms)
861 return None
862 else:
863 def callit():
864 try:
865 func(*args)
866 finally:
867 try:
868 self.deletecommand(name)
869 except TclError:
870 pass
871 try:
872 callit.__name__ = func.__name__
873 except AttributeError:
874 # Required for callable classes (bpo-44404)
875 callit.__name__ = type(func).__name__
876 name = self._register(callit)
877 return self.tk.call('after', ms, name)
878
879 def after_idle(self, func, *args):
880 """Call FUNC once if the Tcl main loop has no event to
881 process.
882
883 Return an identifier to cancel the scheduling with
884 after_cancel."""
885 return self.after('idle', func, *args)
886
887 def after_cancel(self, id):
888 """Cancel scheduling of function identified with ID.
889
890 Identifier returned by after or after_idle must be
891 given as first parameter.
892 """
893 if not id:
894 raise ValueError('id must be a valid identifier returned from '
895 'after or after_idle')
896 try:
897 data = self.tk.call('after', 'info', id)
898 script = self.tk.splitlist(data)[0]
899 self.deletecommand(script)
900 except TclError:
901 pass
902 self.tk.call('after', 'cancel', id)
903
904 def after_info(self, id=None):
905 """Return information about existing event handlers.
906
907 With no argument, return a tuple of the identifiers for all existing
908 event handlers created by the after and after_idle commands for this
909 interpreter. If id is supplied, it specifies an existing handler; id
910 must have been the return value from some previous call to after or
911 after_idle and it must not have triggered yet or been canceled. If the
912 id doesn't exist, a TclError is raised. Otherwise, the return value is
913 a tuple containing (script, type) where script is a reference to the
914 function to be called by the event handler and type is either 'idle'
915 or 'timer' to indicate what kind of event handler it is.
916 """
917 return self.tk.splitlist(self.tk.call('after', 'info', id))
918
919 def bell(self, displayof=0):
920 """Ring a display's bell."""
921 self.tk.call(('bell',) + self._displayof(displayof))
922
923 def tk_busy_cget(self, option):
924 """Return the value of busy configuration option.
925
926 The widget must have been previously made busy by
927 tk_busy_hold(). Option may have any of the values accepted by
928 tk_busy_hold().
929 """
930 return self.tk.call('tk', 'busy', 'cget', self._w, '-'+option)
931 busy_cget = tk_busy_cget
932
933 def tk_busy_configure(self, cnf=None, **kw):
934 """Query or modify the busy configuration options.
935
936 The widget must have been previously made busy by
937 tk_busy_hold(). Options may have any of the values accepted by
938 tk_busy_hold().
939
940 Please note that the option database is referenced by the widget
941 name or class. For example, if a Frame widget with name "frame"
942 is to be made busy, the busy cursor can be specified for it by
943 either call:
944
945 w.option_add('*frame.busyCursor', 'gumby')
946 w.option_add('*Frame.BusyCursor', 'gumby')
947 """
948 if kw:
949 cnf = _cnfmerge((cnf, kw))
950 elif cnf:
951 cnf = _cnfmerge(cnf)
952 if cnf is None:
953 return self._getconfigure(
954 'tk', 'busy', 'configure', self._w)
955 if isinstance(cnf, str):
956 return self._getconfigure1(
957 'tk', 'busy', 'configure', self._w, '-'+cnf)
958 self.tk.call('tk', 'busy', 'configure', self._w, *self._options(cnf))
959 busy_config = busy_configure = tk_busy_config = tk_busy_configure
960
961 def tk_busy_current(self, pattern=None):
962 """Return a list of widgets that are currently busy.
963
964 If a pattern is given, only busy widgets whose path names match
965 a pattern are returned.
966 """
967 return [self._nametowidget(x) for x in
968 self.tk.splitlist(self.tk.call(
969 'tk', 'busy', 'current', pattern))]
970 busy_current = tk_busy_current
971
972 def tk_busy_forget(self):
973 """Make this widget no longer busy.
974
975 User events will again be received by the widget.
976 """
977 self.tk.call('tk', 'busy', 'forget', self._w)
978 busy_forget = tk_busy_forget
979
980 def tk_busy_hold(self, **kw):
981 """Make this widget appear busy.
982
983 The specified widget and its descendants will be blocked from
984 user interactions. Normally update() should be called
985 immediately afterward to insure that the hold operation is in
986 effect before the application starts its processing.
987
988 The only supported configuration option is:
989
990 cursor: the cursor to be displayed when the widget is made
991 busy.
992 """
993 self.tk.call('tk', 'busy', 'hold', self._w, *self._options(kw))
994 busy = busy_hold = tk_busy = tk_busy_hold
995
996 def tk_busy_status(self):
997 """Return True if the widget is busy, False otherwise."""
998 return self.tk.getboolean(self.tk.call(
999 'tk', 'busy', 'status', self._w))
1000 busy_status = tk_busy_status
1001
1002 # Clipboard handling:
1003 def clipboard_get(self, **kw):
1004 """Retrieve data from the clipboard on window's display.
1005
1006 The window keyword defaults to the root window of the Tkinter
1007 application.
1008
1009 The type keyword specifies the form in which the data is
1010 to be returned and should be an atom name such as STRING
1011 or FILE_NAME. Type defaults to STRING, except on X11, where the default
1012 is to try UTF8_STRING and fall back to STRING.
1013
1014 This command is equivalent to:
1015
1016 selection_get(CLIPBOARD)
1017 """
1018 if 'type' not in kw and self._windowingsystem == 'x11':
1019 try:
1020 kw['type'] = 'UTF8_STRING'
1021 return self.tk.call(('clipboard', 'get') + self._options(kw))
1022 except TclError:
1023 del kw['type']
1024 return self.tk.call(('clipboard', 'get') + self._options(kw))
1025
1026 def clipboard_clear(self, **kw):
1027 """Clear the data in the Tk clipboard.
1028
1029 A widget specified for the optional displayof keyword
1030 argument specifies the target display."""
1031 if 'displayof' not in kw: kw['displayof'] = self._w
1032 self.tk.call(('clipboard', 'clear') + self._options(kw))
1033
1034 def clipboard_append(self, string, **kw):
1035 """Append STRING to the Tk clipboard.
1036
1037 A widget specified at the optional displayof keyword
1038 argument specifies the target display. The clipboard
1039 can be retrieved with selection_get."""
1040 if 'displayof' not in kw: kw['displayof'] = self._w
1041 self.tk.call(('clipboard', 'append') + self._options(kw)
1042 + ('--', string))
1043 # XXX grab current w/o window argument
1044
1045 def grab_current(self):
1046 """Return widget which has currently the grab in this application
1047 or None."""
1048 name = self.tk.call('grab', 'current', self._w)
1049 if not name: return None
1050 return self._nametowidget(name)
1051
1052 def grab_release(self):
1053 """Release grab for this widget if currently set."""
1054 self.tk.call('grab', 'release', self._w)
1055
1056 def grab_set(self):
1057 """Set grab for this widget.
1058
1059 A grab directs all events to this and descendant
1060 widgets in the application."""
1061 self.tk.call('grab', 'set', self._w)
1062
1063 def grab_set_global(self):
1064 """Set global grab for this widget.
1065
1066 A global grab directs all events to this and
1067 descendant widgets on the display. Use with caution -
1068 other applications do not get events anymore."""
1069 self.tk.call('grab', 'set', '-global', self._w)
1070
1071 def grab_status(self):
1072 """Return None, "local" or "global" if this widget has
1073 no, a local or a global grab."""
1074 status = self.tk.call('grab', 'status', self._w)
1075 if status == 'none': status = None
1076 return status
1077
1078 def option_add(self, pattern, value, priority = None):
1079 """Set a VALUE (second parameter) for an option
1080 PATTERN (first parameter).
1081
1082 An optional third parameter gives the numeric priority
1083 (defaults to 80)."""
1084 self.tk.call('option', 'add', pattern, value, priority)
1085
1086 def option_clear(self):
1087 """Clear the option database.
1088
1089 It will be reloaded if option_add is called."""
1090 self.tk.call('option', 'clear')
1091
1092 def option_get(self, name, className):
1093 """Return the value for an option NAME for this widget
1094 with CLASSNAME.
1095
1096 Values with higher priority override lower values."""
1097 return self.tk.call('option', 'get', self._w, name, className)
1098
1099 def option_readfile(self, fileName, priority = None):
1100 """Read file FILENAME into the option database.
1101
1102 An optional second parameter gives the numeric
1103 priority."""
1104 self.tk.call('option', 'readfile', fileName, priority)
1105
1106 def selection_clear(self, **kw):
1107 """Clear the current X selection."""
1108 if 'displayof' not in kw: kw['displayof'] = self._w
1109 self.tk.call(('selection', 'clear') + self._options(kw))
1110
1111 def selection_get(self, **kw):
1112 """Return the contents of the current X selection.
1113
1114 A keyword parameter selection specifies the name of
1115 the selection and defaults to PRIMARY. A keyword
1116 parameter displayof specifies a widget on the display
1117 to use. A keyword parameter type specifies the form of data to be
1118 fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
1119 before STRING."""
1120 if 'displayof' not in kw: kw['displayof'] = self._w
1121 if 'type' not in kw and self._windowingsystem == 'x11':
1122 try:
1123 kw['type'] = 'UTF8_STRING'
1124 return self.tk.call(('selection', 'get') + self._options(kw))
1125 except TclError:
1126 del kw['type']
1127 return self.tk.call(('selection', 'get') + self._options(kw))
1128
1129 def selection_handle(self, command, **kw):
1130 """Specify a function COMMAND to call if the X
1131 selection owned by this widget is queried by another
1132 application.
1133
1134 This function must return the contents of the
1135 selection. The function will be called with the
1136 arguments OFFSET and LENGTH which allows the chunking
1137 of very long selections. The following keyword
1138 parameters can be provided:
1139 selection - name of the selection (default PRIMARY),
1140 type - type of the selection (e.g. STRING, FILE_NAME)."""
1141 name = self._register(command)
1142 self.tk.call(('selection', 'handle') + self._options(kw)
1143 + (self._w, name))
1144
1145 def selection_own(self, **kw):
1146 """Become owner of X selection.
1147
1148 A keyword parameter selection specifies the name of
1149 the selection (default PRIMARY)."""
1150 self.tk.call(('selection', 'own') +
1151 self._options(kw) + (self._w,))
1152
1153 def selection_own_get(self, **kw):
1154 """Return owner of X selection.
1155
1156 The following keyword parameter can
1157 be provided:
1158 selection - name of the selection (default PRIMARY),
1159 type - type of the selection (e.g. STRING, FILE_NAME)."""
1160 if 'displayof' not in kw: kw['displayof'] = self._w
1161 name = self.tk.call(('selection', 'own') + self._options(kw))
1162 if not name: return None
1163 return self._nametowidget(name)
1164
1165 def send(self, interp, cmd, *args):
1166 """Send Tcl command CMD to different interpreter INTERP to be executed."""
1167 return self.tk.call(('send', interp, cmd) + args)
1168
1169 def lower(self, belowThis=None):
1170 """Lower this widget in the stacking order."""
1171 self.tk.call('lower', self._w, belowThis)
1172
1173 def tkraise(self, aboveThis=None):
1174 """Raise this widget in the stacking order."""
1175 self.tk.call('raise', self._w, aboveThis)
1176
1177 lift = tkraise
1178
1179 def info_patchlevel(self):
1180 """Returns the exact version of the Tcl library."""
1181 patchlevel = self.tk.call('info', 'patchlevel')
1182 return _parse_version(patchlevel)
1183
1184 def winfo_atom(self, name, displayof=0):
1185 """Return integer which represents atom NAME."""
1186 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
1187 return self.tk.getint(self.tk.call(args))
1188
1189 def winfo_atomname(self, id, displayof=0):
1190 """Return name of atom with identifier ID."""
1191 args = ('winfo', 'atomname') \
1192 + self._displayof(displayof) + (id,)
1193 return self.tk.call(args)
1194
1195 def winfo_cells(self):
1196 """Return number of cells in the colormap for this widget."""
1197 return self.tk.getint(
1198 self.tk.call('winfo', 'cells', self._w))
1199
1200 def winfo_children(self):
1201 """Return a list of all widgets which are children of this widget."""
1202 result = []
1203 for child in self.tk.splitlist(
1204 self.tk.call('winfo', 'children', self._w)):
1205 try:
1206 # Tcl sometimes returns extra windows, e.g. for
1207 # menus; those need to be skipped
1208 result.append(self._nametowidget(child))
1209 except KeyError:
1210 pass
1211 return result
1212
1213 def winfo_class(self):
1214 """Return window class name of this widget."""
1215 return self.tk.call('winfo', 'class', self._w)
1216
1217 def winfo_colormapfull(self):
1218 """Return True if at the last color request the colormap was full."""
1219 return self.tk.getboolean(
1220 self.tk.call('winfo', 'colormapfull', self._w))
1221
1222 def winfo_containing(self, rootX, rootY, displayof=0):
1223 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
1224 args = ('winfo', 'containing') \
1225 + self._displayof(displayof) + (rootX, rootY)
1226 name = self.tk.call(args)
1227 if not name: return None
1228 return self._nametowidget(name)
1229
1230 def winfo_depth(self):
1231 """Return the number of bits per pixel."""
1232 return self.tk.getint(self.tk.call('winfo', 'depth', self._w))
1233
1234 def winfo_exists(self):
1235 """Return true if this widget exists."""
1236 return self.tk.getint(
1237 self.tk.call('winfo', 'exists', self._w))
1238
1239 def winfo_fpixels(self, number):
1240 """Return the number of pixels for the given distance NUMBER
1241 (e.g. "3c") as float."""
1242 return self.tk.getdouble(self.tk.call(
1243 'winfo', 'fpixels', self._w, number))
1244
1245 def winfo_geometry(self):
1246 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
1247 return self.tk.call('winfo', 'geometry', self._w)
1248
1249 def winfo_height(self):
1250 """Return height of this widget."""
1251 return self.tk.getint(
1252 self.tk.call('winfo', 'height', self._w))
1253
1254 def winfo_id(self):
1255 """Return identifier ID for this widget."""
1256 return int(self.tk.call('winfo', 'id', self._w), 0)
1257
1258 def winfo_interps(self, displayof=0):
1259 """Return the name of all Tcl interpreters for this display."""
1260 args = ('winfo', 'interps') + self._displayof(displayof)
1261 return self.tk.splitlist(self.tk.call(args))
1262
1263 def winfo_ismapped(self):
1264 """Return true if this widget is mapped."""
1265 return self.tk.getint(
1266 self.tk.call('winfo', 'ismapped', self._w))
1267
1268 def winfo_manager(self):
1269 """Return the window manager name for this widget."""
1270 return self.tk.call('winfo', 'manager', self._w)
1271
1272 def winfo_name(self):
1273 """Return the name of this widget."""
1274 return self.tk.call('winfo', 'name', self._w)
1275
1276 def winfo_parent(self):
1277 """Return the name of the parent of this widget."""
1278 return self.tk.call('winfo', 'parent', self._w)
1279
1280 def winfo_pathname(self, id, displayof=0):
1281 """Return the pathname of the widget given by ID."""
1282 if isinstance(id, int):
1283 id = hex(id)
1284 args = ('winfo', 'pathname') \
1285 + self._displayof(displayof) + (id,)
1286 return self.tk.call(args)
1287
1288 def winfo_pixels(self, number):
1289 """Rounded integer value of winfo_fpixels."""
1290 return self.tk.getint(
1291 self.tk.call('winfo', 'pixels', self._w, number))
1292
1293 def winfo_pointerx(self):
1294 """Return the x coordinate of the pointer on the root window."""
1295 return self.tk.getint(
1296 self.tk.call('winfo', 'pointerx', self._w))
1297
1298 def winfo_pointerxy(self):
1299 """Return a tuple of x and y coordinates of the pointer on the root window."""
1300 return self._getints(
1301 self.tk.call('winfo', 'pointerxy', self._w))
1302
1303 def winfo_pointery(self):
1304 """Return the y coordinate of the pointer on the root window."""
1305 return self.tk.getint(
1306 self.tk.call('winfo', 'pointery', self._w))
1307
1308 def winfo_reqheight(self):
1309 """Return requested height of this widget."""
1310 return self.tk.getint(
1311 self.tk.call('winfo', 'reqheight', self._w))
1312
1313 def winfo_reqwidth(self):
1314 """Return requested width of this widget."""
1315 return self.tk.getint(
1316 self.tk.call('winfo', 'reqwidth', self._w))
1317
1318 def winfo_rgb(self, color):
1319 """Return a tuple of integer RGB values in range(65536) for color in this widget."""
1320 return self._getints(
1321 self.tk.call('winfo', 'rgb', self._w, color))
1322
1323 def winfo_rootx(self):
1324 """Return x coordinate of upper left corner of this widget on the
1325 root window."""
1326 return self.tk.getint(
1327 self.tk.call('winfo', 'rootx', self._w))
1328
1329 def winfo_rooty(self):
1330 """Return y coordinate of upper left corner of this widget on the
1331 root window."""
1332 return self.tk.getint(
1333 self.tk.call('winfo', 'rooty', self._w))
1334
1335 def winfo_screen(self):
1336 """Return the screen name of this widget."""
1337 return self.tk.call('winfo', 'screen', self._w)
1338
1339 def winfo_screencells(self):
1340 """Return the number of the cells in the colormap of the screen
1341 of this widget."""
1342 return self.tk.getint(
1343 self.tk.call('winfo', 'screencells', self._w))
1344
1345 def winfo_screendepth(self):
1346 """Return the number of bits per pixel of the root window of the
1347 screen of this widget."""
1348 return self.tk.getint(
1349 self.tk.call('winfo', 'screendepth', self._w))
1350
1351 def winfo_screenheight(self):
1352 """Return the number of pixels of the height of the screen of this widget
1353 in pixel."""
1354 return self.tk.getint(
1355 self.tk.call('winfo', 'screenheight', self._w))
1356
1357 def winfo_screenmmheight(self):
1358 """Return the number of pixels of the height of the screen of
1359 this widget in mm."""
1360 return self.tk.getint(
1361 self.tk.call('winfo', 'screenmmheight', self._w))
1362
1363 def winfo_screenmmwidth(self):
1364 """Return the number of pixels of the width of the screen of
1365 this widget in mm."""
1366 return self.tk.getint(
1367 self.tk.call('winfo', 'screenmmwidth', self._w))
1368
1369 def winfo_screenvisual(self):
1370 """Return one of the strings directcolor, grayscale, pseudocolor,
1371 staticcolor, staticgray, or truecolor for the default
1372 colormodel of this screen."""
1373 return self.tk.call('winfo', 'screenvisual', self._w)
1374
1375 def winfo_screenwidth(self):
1376 """Return the number of pixels of the width of the screen of
1377 this widget in pixel."""
1378 return self.tk.getint(
1379 self.tk.call('winfo', 'screenwidth', self._w))
1380
1381 def winfo_server(self):
1382 """Return information of the X-Server of the screen of this widget in
1383 the form "XmajorRminor vendor vendorVersion"."""
1384 return self.tk.call('winfo', 'server', self._w)
1385
1386 def winfo_toplevel(self):
1387 """Return the toplevel widget of this widget."""
1388 return self._nametowidget(self.tk.call(
1389 'winfo', 'toplevel', self._w))
1390
1391 def winfo_viewable(self):
1392 """Return true if the widget and all its higher ancestors are mapped."""
1393 return self.tk.getint(
1394 self.tk.call('winfo', 'viewable', self._w))
1395
1396 def winfo_visual(self):
1397 """Return one of the strings directcolor, grayscale, pseudocolor,
1398 staticcolor, staticgray, or truecolor for the
1399 colormodel of this widget."""
1400 return self.tk.call('winfo', 'visual', self._w)
1401
1402 def winfo_visualid(self):
1403 """Return the X identifier for the visual for this widget."""
1404 return self.tk.call('winfo', 'visualid', self._w)
1405
1406 def winfo_visualsavailable(self, includeids=False):
1407 """Return a list of all visuals available for the screen
1408 of this widget.
1409
1410 Each item in the list consists of a visual name (see winfo_visual), a
1411 depth and if includeids is true is given also the X identifier."""
1412 data = self.tk.call('winfo', 'visualsavailable', self._w,
1413 'includeids' if includeids else None)
1414 data = [self.tk.splitlist(x) for x in self.tk.splitlist(data)]
1415 return [self.__winfo_parseitem(x) for x in data]
1416
1417 def __winfo_parseitem(self, t):
1418 """Internal function."""
1419 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
1420
1421 def __winfo_getint(self, x):
1422 """Internal function."""
1423 return int(x, 0)
1424
1425 def winfo_vrootheight(self):
1426 """Return the height of the virtual root window associated with this
1427 widget in pixels. If there is no virtual root window return the
1428 height of the screen."""
1429 return self.tk.getint(
1430 self.tk.call('winfo', 'vrootheight', self._w))
1431
1432 def winfo_vrootwidth(self):
1433 """Return the width of the virtual root window associated with this
1434 widget in pixel. If there is no virtual root window return the
1435 width of the screen."""
1436 return self.tk.getint(
1437 self.tk.call('winfo', 'vrootwidth', self._w))
1438
1439 def winfo_vrootx(self):
1440 """Return the x offset of the virtual root relative to the root
1441 window of the screen of this widget."""
1442 return self.tk.getint(
1443 self.tk.call('winfo', 'vrootx', self._w))
1444
1445 def winfo_vrooty(self):
1446 """Return the y offset of the virtual root relative to the root
1447 window of the screen of this widget."""
1448 return self.tk.getint(
1449 self.tk.call('winfo', 'vrooty', self._w))
1450
1451 def winfo_width(self):
1452 """Return the width of this widget."""
1453 return self.tk.getint(
1454 self.tk.call('winfo', 'width', self._w))
1455
1456 def winfo_x(self):
1457 """Return the x coordinate of the upper left corner of this widget
1458 in the parent."""
1459 return self.tk.getint(
1460 self.tk.call('winfo', 'x', self._w))
1461
1462 def winfo_y(self):
1463 """Return the y coordinate of the upper left corner of this widget
1464 in the parent."""
1465 return self.tk.getint(
1466 self.tk.call('winfo', 'y', self._w))
1467
1468 def update(self):
1469 """Enter event loop until all pending events have been processed by Tcl."""
1470 self.tk.call('update')
1471
1472 def update_idletasks(self):
1473 """Enter event loop until all idle callbacks have been called. This
1474 will update the display of windows but not process events caused by
1475 the user."""
1476 self.tk.call('update', 'idletasks')
1477
1478 def bindtags(self, tagList=None):
1479 """Set or get the list of bindtags for this widget.
1480
1481 With no argument return the list of all bindtags associated with
1482 this widget. With a list of strings as argument the bindtags are
1483 set to this list. The bindtags determine in which order events are
1484 processed (see bind)."""
1485 if tagList is None:
1486 return self.tk.splitlist(
1487 self.tk.call('bindtags', self._w))
1488 else:
1489 self.tk.call('bindtags', self._w, tagList)
1490
1491 def _bind(self, what, sequence, func, add, needcleanup=1):
1492 """Internal function."""
1493 if isinstance(func, str):
1494 self.tk.call(what + (sequence, func))
1495 elif func:
1496 funcid = self._register(func, self._substitute,
1497 needcleanup)
1498 cmd = ('%sif {"[%s %s]" == "break"} break\n'
1499 %
1500 (add and '+' or '',
1501 funcid, self._subst_format_str))
1502 self.tk.call(what + (sequence, cmd))
1503 return funcid
1504 elif sequence:
1505 return self.tk.call(what + (sequence,))
1506 else:
1507 return self.tk.splitlist(self.tk.call(what))
1508
1509 def bind(self, sequence=None, func=None, add=None):
1510 """Bind to this widget at event SEQUENCE a call to function FUNC.
1511
1512 SEQUENCE is a string of concatenated event
1513 patterns. An event pattern is of the form
1514 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
1515 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
1516 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
1517 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
1518 Mod1, M1. TYPE is one of Activate, Enter, Map,
1519 ButtonPress, Button, Expose, Motion, ButtonRelease
1520 FocusIn, MouseWheel, Circulate, FocusOut, Property,
1521 Colormap, Gravity Reparent, Configure, KeyPress, Key,
1522 Unmap, Deactivate, KeyRelease Visibility, Destroy,
1523 Leave and DETAIL is the button number for ButtonPress,
1524 ButtonRelease and DETAIL is the Keysym for KeyPress and
1525 KeyRelease. Examples are
1526 <Control-Button-1> for pressing Control and mouse button 1 or
1527 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
1528 An event pattern can also be a virtual event of the form
1529 <<AString>> where AString can be arbitrary. This
1530 event can be generated by event_generate.
1531 If events are concatenated they must appear shortly
1532 after each other.
1533
1534 FUNC will be called if the event sequence occurs with an
1535 instance of Event as argument. If the return value of FUNC is
1536 "break" no further bound function is invoked.
1537
1538 An additional boolean parameter ADD specifies whether FUNC will
1539 be called additionally to the other bound function or whether
1540 it will replace the previous function.
1541
1542 Bind will return an identifier to allow deletion of the bound function with
1543 unbind without memory leak.
1544
1545 If FUNC or SEQUENCE is omitted the bound function or list
1546 of bound events are returned."""
1547
1548 return self._bind(('bind', self._w), sequence, func, add)
1549
1550 def unbind(self, sequence, funcid=None):
1551 """Unbind for this widget the event SEQUENCE.
1552
1553 If FUNCID is given, only unbind the function identified with FUNCID
1554 and also delete the corresponding Tcl command.
1555
1556 Otherwise destroy the current binding for SEQUENCE, leaving SEQUENCE
1557 unbound.
1558 """
1559 self._unbind(('bind', self._w, sequence), funcid)
1560
1561 def _unbind(self, what, funcid=None):
1562 if funcid is None:
1563 self.tk.call(*what, '')
1564 else:
1565 lines = self.tk.call(what).split('\n')
1566 prefix = f'if {{"[{funcid} '
1567 keep = '\n'.join(line for line in lines
1568 if not line.startswith(prefix))
1569 if not keep.strip():
1570 keep = ''
1571 self.tk.call(*what, keep)
1572 self.deletecommand(funcid)
1573
1574 def bind_all(self, sequence=None, func=None, add=None):
1575 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1576 An additional boolean parameter ADD specifies whether FUNC will
1577 be called additionally to the other bound function or whether
1578 it will replace the previous function. See bind for the return value."""
1579 return self._root()._bind(('bind', 'all'), sequence, func, add, True)
1580
1581 def unbind_all(self, sequence):
1582 """Unbind for all widgets for event SEQUENCE all functions."""
1583 self._root()._unbind(('bind', 'all', sequence))
1584
1585 def bind_class(self, className, sequence=None, func=None, add=None):
1586 """Bind to widgets with bindtag CLASSNAME at event
1587 SEQUENCE a call of function FUNC. An additional
1588 boolean parameter ADD specifies whether FUNC will be
1589 called additionally to the other bound function or
1590 whether it will replace the previous function. See bind for
1591 the return value."""
1592
1593 return self._root()._bind(('bind', className), sequence, func, add, True)
1594
1595 def unbind_class(self, className, sequence):
1596 """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
1597 all functions."""
1598 self._root()._unbind(('bind', className, sequence))
1599
1600 def mainloop(self, n=0):
1601 """Call the mainloop of Tk."""
1602 self.tk.mainloop(n)
1603
1604 def quit(self):
1605 """Quit the Tcl interpreter. All widgets will be destroyed."""
1606 self.tk.quit()
1607
1608 def _getints(self, string):
1609 """Internal function."""
1610 if string:
1611 return tuple(map(self.tk.getint, self.tk.splitlist(string)))
1612
1613 def _getdoubles(self, string):
1614 """Internal function."""
1615 if string:
1616 return tuple(map(self.tk.getdouble, self.tk.splitlist(string)))
1617
1618 def _getboolean(self, string):
1619 """Internal function."""
1620 if string:
1621 return self.tk.getboolean(string)
1622
1623 def _displayof(self, displayof):
1624 """Internal function."""
1625 if displayof:
1626 return ('-displayof', displayof)
1627 if displayof is None:
1628 return ('-displayof', self._w)
1629 return ()
1630
1631 @property
1632 def _windowingsystem(self):
1633 """Internal function."""
1634 try:
1635 return self._root()._windowingsystem_cached
1636 except AttributeError:
1637 ws = self._root()._windowingsystem_cached = \
1638 self.tk.call('tk', 'windowingsystem')
1639 return ws
1640
1641 def _options(self, cnf, kw = None):
1642 """Internal function."""
1643 if kw:
1644 cnf = _cnfmerge((cnf, kw))
1645 else:
1646 cnf = _cnfmerge(cnf)
1647 res = ()
1648 for k, v in cnf.items():
1649 if v is not None:
1650 if k[-1] == '_': k = k[:-1]
1651 if callable(v):
1652 v = self._register(v)
1653 elif isinstance(v, (tuple, list)):
1654 nv = []
1655 for item in v:
1656 if isinstance(item, int):
1657 nv.append(str(item))
1658 elif isinstance(item, str):
1659 nv.append(_stringify(item))
1660 else:
1661 break
1662 else:
1663 v = ' '.join(nv)
1664 res = res + ('-'+k, v)
1665 return res
1666
1667 def nametowidget(self, name):
1668 """Return the Tkinter instance of a widget identified by
1669 its Tcl name NAME."""
1670 name = str(name).split('.')
1671 w = self
1672
1673 if not name[0]:
1674 w = w._root()
1675 name = name[1:]
1676
1677 for n in name:
1678 if not n:
1679 break
1680 w = w.children[n]
1681
1682 return w
1683
1684 _nametowidget = nametowidget
1685
1686 def _register(self, func, subst=None, needcleanup=1):
1687 """Return a newly created Tcl function. If this
1688 function is called, the Python function FUNC will
1689 be executed. An optional function SUBST can
1690 be given which will be executed before FUNC."""
1691 f = CallWrapper(func, subst, self).__call__
1692 name = repr(id(f))
1693 try:
1694 func = func.__func__
1695 except AttributeError:
1696 pass
1697 try:
1698 name = name + func.__name__
1699 except AttributeError:
1700 pass
1701 self.tk.createcommand(name, f)
1702 if needcleanup:
1703 if self._tclCommands is None:
1704 self._tclCommands = []
1705 self._tclCommands.append(name)
1706 return name
1707
1708 register = _register
1709
1710 def _root(self):
1711 """Internal function."""
1712 w = self
1713 while w.master is not None: w = w.master
1714 return w
1715 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1716 '%s', '%t', '%w', '%x', '%y',
1717 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1718 _subst_format_str = " ".join(_subst_format)
1719
1720 def _substitute(self, *args):
1721 """Internal function."""
1722 if len(args) != len(self._subst_format): return args
1723 getboolean = self.tk.getboolean
1724
1725 getint = self.tk.getint
1726 def getint_event(s):
1727 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1728 try:
1729 return getint(s)
1730 except (ValueError, TclError):
1731 return s
1732
1733 if any(isinstance(s, tuple) for s in args):
1734 args = [s[0] if isinstance(s, tuple) and len(s) == 1 else s
1735 for s in args]
1736 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1737 # Missing: (a, c, d, m, o, v, B, R)
1738 e = Event()
1739 # serial field: valid for all events
1740 # number of button: ButtonPress and ButtonRelease events only
1741 # height field: Configure, ConfigureRequest, Create,
1742 # ResizeRequest, and Expose events only
1743 # keycode field: KeyPress and KeyRelease events only
1744 # time field: "valid for events that contain a time field"
1745 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1746 # and Expose events only
1747 # x field: "valid for events that contain an x field"
1748 # y field: "valid for events that contain a y field"
1749 # keysym as decimal: KeyPress and KeyRelease events only
1750 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1751 # KeyRelease, and Motion events
1752 e.serial = getint(nsign)
1753 e.num = getint_event(b)
1754 try: e.focus = getboolean(f)
1755 except TclError: pass
1756 e.height = getint_event(h)
1757 e.keycode = getint_event(k)
1758 e.state = getint_event(s)
1759 e.time = getint_event(t)
1760 e.width = getint_event(w)
1761 e.x = getint_event(x)
1762 e.y = getint_event(y)
1763 e.char = A
1764 try: e.send_event = getboolean(E)
1765 except TclError: pass
1766 e.keysym = K
1767 e.keysym_num = getint_event(N)
1768 try:
1769 e.type = EventType(T)
1770 except ValueError:
1771 try:
1772 e.type = EventType(str(T)) # can be int
1773 except ValueError:
1774 e.type = T
1775 try:
1776 e.widget = self._nametowidget(W)
1777 except KeyError:
1778 e.widget = W
1779 e.x_root = getint_event(X)
1780 e.y_root = getint_event(Y)
1781 try:
1782 e.delta = getint(D)
1783 except (ValueError, TclError):
1784 e.delta = 0
1785 return (e,)
1786
1787 def _report_exception(self):
1788 """Internal function."""
1789 exc, val, tb = sys.exc_info()
1790 root = self._root()
1791 root.report_callback_exception(exc, val, tb)
1792
1793 def _getconfigure(self, *args):
1794 """Call Tcl configure command and return the result as a dict."""
1795 cnf = {}
1796 for x in self.tk.splitlist(self.tk.call(*args)):
1797 x = self.tk.splitlist(x)
1798 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1799 return cnf
1800
1801 def _getconfigure1(self, *args):
1802 x = self.tk.splitlist(self.tk.call(*args))
1803 return (x[0][1:],) + x[1:]
1804
1805 def _configure(self, cmd, cnf, kw):
1806 """Internal function."""
1807 if kw:
1808 cnf = _cnfmerge((cnf, kw))
1809 elif cnf:
1810 cnf = _cnfmerge(cnf)
1811 if cnf is None:
1812 return self._getconfigure(_flatten((self._w, cmd)))
1813 if isinstance(cnf, str):
1814 return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
1815 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1816 # These used to be defined in Widget:
1817
1818 def configure(self, cnf=None, **kw):
1819 """Query or modify the configuration options of the widget.
1820
1821 If no arguments are specified, return a dictionary describing
1822 all of the available options for the widget.
1823
1824 If an option name is specified, then return a tuple describing
1825 the one named option.
1826
1827 If one or more keyword arguments are specified or a dictionary
1828 is specified, then modify the widget option(s) to have the given
1829 value(s).
1830 """
1831 return self._configure('configure', cnf, kw)
1832
1833 config = configure
1834
1835 def cget(self, key):
1836 """Return the current value of the configuration option."""
1837 return self.tk.call(self._w, 'cget', '-' + key)
1838
1839 __getitem__ = cget
1840
1841 def __setitem__(self, key, value):
1842 self.configure({key: value})
1843
1844 def keys(self):
1845 """Return a list of all option names of this widget."""
1846 splitlist = self.tk.splitlist
1847 return [splitlist(x)[0][1:] for x in
1848 splitlist(self.tk.call(self._w, 'configure'))]
1849
1850 def __str__(self):
1851 """Return the window path name of this widget."""
1852 return self._w
1853
1854 def __repr__(self):
1855 return '<%s.%s object %s>' % (
1856 self.__class__.__module__, self.__class__.__qualname__, self._w)
1857
1858 # Pack methods that apply to the container widget
1859 _noarg_ = ['_noarg_']
1860
1861 def pack_propagate(self, flag=_noarg_):
1862 """Set or get the status for propagation of geometry information.
1863
1864 A boolean argument specifies whether the size of this container will
1865 be determined by the geometry information of its content.
1866 If no argument is given the current setting will be returned.
1867 """
1868 if flag is Misc._noarg_:
1869 return self._getboolean(self.tk.call(
1870 'pack', 'propagate', self._w))
1871 else:
1872 self.tk.call('pack', 'propagate', self._w, flag)
1873
1874 propagate = pack_propagate
1875
1876 def pack_slaves(self):
1877 """Returns a list of all of the content widgets in the packing order
1878 for this container."""
1879 return [self._nametowidget(x) for x in
1880 self.tk.splitlist(
1881 self.tk.call('pack', 'slaves', self._w))]
1882
1883 slaves = pack_slaves
1884
1885 # Place method that applies to the container widget
1886 def place_slaves(self):
1887 """Returns a list of all the content widgets for which this widget is
1888 the container."""
1889 return [self._nametowidget(x) for x in
1890 self.tk.splitlist(
1891 self.tk.call(
1892 'place', 'slaves', self._w))]
1893
1894 # Grid methods that apply to the container widget
1895
1896 def grid_anchor(self, anchor=None): # new in Tk 8.5
1897 """The anchor value controls how to place the grid within the
1898 container widget when no row/column has any weight.
1899
1900 The default anchor is nw."""
1901 self.tk.call('grid', 'anchor', self._w, anchor)
1902
1903 anchor = grid_anchor
1904
1905 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1906 """Return a tuple of integer coordinates for the bounding
1907 box of this widget controlled by the geometry manager grid.
1908
1909 If COLUMN, ROW is given the bounding box applies from
1910 the cell with row and column 0 to the specified
1911 cell. If COL2 and ROW2 are given the bounding box
1912 starts at that cell.
1913
1914 The returned integers specify the offset of the upper left
1915 corner in the container widget and the width and height.
1916 """
1917 args = ('grid', 'bbox', self._w)
1918 if column is not None and row is not None:
1919 args = args + (column, row)
1920 if col2 is not None and row2 is not None:
1921 args = args + (col2, row2)
1922 return self._getints(self.tk.call(*args)) or None
1923
1924 bbox = grid_bbox
1925
1926 def _gridconvvalue(self, value):
1927 if isinstance(value, (str, _tkinter.Tcl_Obj)):
1928 try:
1929 svalue = str(value)
1930 if not svalue:
1931 return None
1932 elif '.' in svalue:
1933 return self.tk.getdouble(svalue)
1934 else:
1935 return self.tk.getint(svalue)
1936 except (ValueError, TclError):
1937 pass
1938 return value
1939
1940 def _grid_configure(self, command, index, cnf, kw):
1941 """Internal function."""
1942 if isinstance(cnf, str) and not kw:
1943 if cnf[-1:] == '_':
1944 cnf = cnf[:-1]
1945 if cnf[:1] != '-':
1946 cnf = '-'+cnf
1947 options = (cnf,)
1948 else:
1949 options = self._options(cnf, kw)
1950 if not options:
1951 return _splitdict(
1952 self.tk,
1953 self.tk.call('grid', command, self._w, index),
1954 conv=self._gridconvvalue)
1955 res = self.tk.call(
1956 ('grid', command, self._w, index)
1957 + options)
1958 if len(options) == 1:
1959 return self._gridconvvalue(res)
1960
1961 def grid_columnconfigure(self, index, cnf={}, **kw):
1962 """Configure column INDEX of a grid.
1963
1964 Valid options are minsize (minimum size of the column),
1965 weight (how much does additional space propagate to this column)
1966 and pad (how much space to let additionally)."""
1967 return self._grid_configure('columnconfigure', index, cnf, kw)
1968
1969 columnconfigure = grid_columnconfigure
1970
1971 def grid_location(self, x, y):
1972 """Return a tuple of column and row which identify the cell
1973 at which the pixel at position X and Y inside the container
1974 widget is located."""
1975 return self._getints(
1976 self.tk.call(
1977 'grid', 'location', self._w, x, y)) or None
1978
1979 def grid_propagate(self, flag=_noarg_):
1980 """Set or get the status for propagation of geometry information.
1981
1982 A boolean argument specifies whether the size of this container will
1983 be determined by the geometry information of its content.
1984 If no argument is given the current setting will be returned.
1985 """
1986 if flag is Misc._noarg_:
1987 return self._getboolean(self.tk.call(
1988 'grid', 'propagate', self._w))
1989 else:
1990 self.tk.call('grid', 'propagate', self._w, flag)
1991
1992 def grid_rowconfigure(self, index, cnf={}, **kw):
1993 """Configure row INDEX of a grid.
1994
1995 Valid options are minsize (minimum size of the row),
1996 weight (how much does additional space propagate to this row)
1997 and pad (how much space to let additionally)."""
1998 return self._grid_configure('rowconfigure', index, cnf, kw)
1999
2000 rowconfigure = grid_rowconfigure
2001
2002 def grid_size(self):
2003 """Return a tuple of the number of column and rows in the grid."""
2004 return self._getints(
2005 self.tk.call('grid', 'size', self._w)) or None
2006
2007 size = grid_size
2008
2009 def grid_slaves(self, row=None, column=None):
2010 """Returns a list of the content widgets.
2011
2012 If no arguments are supplied, a list of all of the content in this
2013 container widget is returned, most recently managed first.
2014 If ROW or COLUMN is specified, only the content in the row or
2015 column is returned.
2016 """
2017 args = ()
2018 if row is not None:
2019 args = args + ('-row', row)
2020 if column is not None:
2021 args = args + ('-column', column)
2022 return [self._nametowidget(x) for x in
2023 self.tk.splitlist(self.tk.call(
2024 ('grid', 'slaves', self._w) + args))]
2025
2026 # Support for the "event" command, new in Tk 4.2.
2027 # By Case Roole.
2028
2029 def event_add(self, virtual, *sequences):
2030 """Bind a virtual event VIRTUAL (of the form <<Name>>)
2031 to an event SEQUENCE such that the virtual event is triggered
2032 whenever SEQUENCE occurs."""
2033 args = ('event', 'add', virtual) + sequences
2034 self.tk.call(args)
2035
2036 def event_delete(self, virtual, *sequences):
2037 """Unbind a virtual event VIRTUAL from SEQUENCE."""
2038 args = ('event', 'delete', virtual) + sequences
2039 self.tk.call(args)
2040
2041 def event_generate(self, sequence, **kw):
2042 """Generate an event SEQUENCE. Additional
2043 keyword arguments specify parameter of the event
2044 (e.g. x, y, rootx, rooty)."""
2045 args = ('event', 'generate', self._w, sequence)
2046 for k, v in kw.items():
2047 args = args + ('-%s' % k, str(v))
2048 self.tk.call(args)
2049
2050 def event_info(self, virtual=None):
2051 """Return a list of all virtual events or the information
2052 about the SEQUENCE bound to the virtual event VIRTUAL."""
2053 return self.tk.splitlist(
2054 self.tk.call('event', 'info', virtual))
2055
2056 # Image related commands
2057
2058 def image_names(self):
2059 """Return a list of all existing image names."""
2060 return self.tk.splitlist(self.tk.call('image', 'names'))
2061
2062 def image_types(self):
2063 """Return a list of all available image types (e.g. photo bitmap)."""
2064 return self.tk.splitlist(self.tk.call('image', 'types'))
2065
2066
2067 class CallWrapper:
2068 """Internal class. Stores function to call when some user
2069 defined Tcl function is called e.g. after an event occurred."""
2070
2071 def __init__(self, func, subst, widget):
2072 """Store FUNC, SUBST and WIDGET as members."""
2073 self.func = func
2074 self.subst = subst
2075 self.widget = widget
2076
2077 def __call__(self, *args):
2078 """Apply first function SUBST to arguments, than FUNC."""
2079 try:
2080 if self.subst:
2081 args = self.subst(*args)
2082 return self.func(*args)
2083 except SystemExit:
2084 raise
2085 except:
2086 self.widget._report_exception()
2087
2088
2089 class XView:
2090 """Mix-in class for querying and changing the horizontal position
2091 of a widget's window."""
2092
2093 def xview(self, *args):
2094 """Query and change the horizontal position of the view."""
2095 res = self.tk.call(self._w, 'xview', *args)
2096 if not args:
2097 return self._getdoubles(res)
2098
2099 def xview_moveto(self, fraction):
2100 """Adjusts the view in the window so that FRACTION of the
2101 total width of the canvas is off-screen to the left."""
2102 self.tk.call(self._w, 'xview', 'moveto', fraction)
2103
2104 def xview_scroll(self, number, what):
2105 """Shift the x-view according to NUMBER which is measured in "units"
2106 or "pages" (WHAT)."""
2107 self.tk.call(self._w, 'xview', 'scroll', number, what)
2108
2109
2110 class YView:
2111 """Mix-in class for querying and changing the vertical position
2112 of a widget's window."""
2113
2114 def yview(self, *args):
2115 """Query and change the vertical position of the view."""
2116 res = self.tk.call(self._w, 'yview', *args)
2117 if not args:
2118 return self._getdoubles(res)
2119
2120 def yview_moveto(self, fraction):
2121 """Adjusts the view in the window so that FRACTION of the
2122 total height of the canvas is off-screen to the top."""
2123 self.tk.call(self._w, 'yview', 'moveto', fraction)
2124
2125 def yview_scroll(self, number, what):
2126 """Shift the y-view according to NUMBER which is measured in
2127 "units" or "pages" (WHAT)."""
2128 self.tk.call(self._w, 'yview', 'scroll', number, what)
2129
2130
2131 class Wm:
2132 """Provides functions for the communication with the window manager."""
2133
2134 def wm_aspect(self,
2135 minNumer=None, minDenom=None,
2136 maxNumer=None, maxDenom=None):
2137 """Instruct the window manager to set the aspect ratio (width/height)
2138 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
2139 of the actual values if no argument is given."""
2140 return self._getints(
2141 self.tk.call('wm', 'aspect', self._w,
2142 minNumer, minDenom,
2143 maxNumer, maxDenom))
2144
2145 aspect = wm_aspect
2146
2147 def wm_attributes(self, *args, return_python_dict=False, **kwargs):
2148 """Return or sets platform specific attributes.
2149
2150 When called with a single argument return_python_dict=True,
2151 return a dict of the platform specific attributes and their values.
2152 When called without arguments or with a single argument
2153 return_python_dict=False, return a tuple containing intermixed
2154 attribute names with the minus prefix and their values.
2155
2156 When called with a single string value, return the value for the
2157 specific option. When called with keyword arguments, set the
2158 corresponding attributes.
2159 """
2160 if not kwargs:
2161 if not args:
2162 res = self.tk.call('wm', 'attributes', self._w)
2163 if return_python_dict:
2164 return _splitdict(self.tk, res)
2165 else:
2166 return self.tk.splitlist(res)
2167 if len(args) == 1 and args[0] is not None:
2168 option = args[0]
2169 if option[0] == '-':
2170 # TODO: deprecate
2171 option = option[1:]
2172 return self.tk.call('wm', 'attributes', self._w, '-' + option)
2173 # TODO: deprecate
2174 return self.tk.call('wm', 'attributes', self._w, *args)
2175 elif args:
2176 raise TypeError('wm_attribute() options have been specified as '
2177 'positional and keyword arguments')
2178 else:
2179 self.tk.call('wm', 'attributes', self._w, *self._options(kwargs))
2180
2181 attributes = wm_attributes
2182
2183 def wm_client(self, name=None):
2184 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
2185 current value."""
2186 return self.tk.call('wm', 'client', self._w, name)
2187
2188 client = wm_client
2189
2190 def wm_colormapwindows(self, *wlist):
2191 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
2192 of this widget. This list contains windows whose colormaps differ from their
2193 parents. Return current list of widgets if WLIST is empty."""
2194 if len(wlist) > 1:
2195 wlist = (wlist,) # Tk needs a list of windows here
2196 args = ('wm', 'colormapwindows', self._w) + wlist
2197 if wlist:
2198 self.tk.call(args)
2199 else:
2200 return [self._nametowidget(x)
2201 for x in self.tk.splitlist(self.tk.call(args))]
2202
2203 colormapwindows = wm_colormapwindows
2204
2205 def wm_command(self, value=None):
2206 """Store VALUE in WM_COMMAND property. It is the command
2207 which shall be used to invoke the application. Return current
2208 command if VALUE is None."""
2209 return self.tk.call('wm', 'command', self._w, value)
2210
2211 command = wm_command
2212
2213 def wm_deiconify(self):
2214 """Deiconify this widget. If it was never mapped it will not be mapped.
2215 On Windows it will raise this widget and give it the focus."""
2216 return self.tk.call('wm', 'deiconify', self._w)
2217
2218 deiconify = wm_deiconify
2219
2220 def wm_focusmodel(self, model=None):
2221 """Set focus model to MODEL. "active" means that this widget will claim
2222 the focus itself, "passive" means that the window manager shall give
2223 the focus. Return current focus model if MODEL is None."""
2224 return self.tk.call('wm', 'focusmodel', self._w, model)
2225
2226 focusmodel = wm_focusmodel
2227
2228 def wm_forget(self, window): # new in Tk 8.5
2229 """The window will be unmapped from the screen and will no longer
2230 be managed by wm. toplevel windows will be treated like frame
2231 windows once they are no longer managed by wm, however, the menu
2232 option configuration will be remembered and the menus will return
2233 once the widget is managed again."""
2234 self.tk.call('wm', 'forget', window)
2235
2236 forget = wm_forget
2237
2238 def wm_frame(self):
2239 """Return identifier for decorative frame of this widget if present."""
2240 return self.tk.call('wm', 'frame', self._w)
2241
2242 frame = wm_frame
2243
2244 def wm_geometry(self, newGeometry=None):
2245 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
2246 current value if None is given."""
2247 return self.tk.call('wm', 'geometry', self._w, newGeometry)
2248
2249 geometry = wm_geometry
2250
2251 def wm_grid(self,
2252 baseWidth=None, baseHeight=None,
2253 widthInc=None, heightInc=None):
2254 """Instruct the window manager that this widget shall only be
2255 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
2256 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
2257 number of grid units requested in Tk_GeometryRequest."""
2258 return self._getints(self.tk.call(
2259 'wm', 'grid', self._w,
2260 baseWidth, baseHeight, widthInc, heightInc))
2261
2262 grid = wm_grid
2263
2264 def wm_group(self, pathName=None):
2265 """Set the group leader widgets for related widgets to PATHNAME. Return
2266 the group leader of this widget if None is given."""
2267 return self.tk.call('wm', 'group', self._w, pathName)
2268
2269 group = wm_group
2270
2271 def wm_iconbitmap(self, bitmap=None, default=None):
2272 """Set bitmap for the iconified widget to BITMAP. Return
2273 the bitmap if None is given.
2274
2275 Under Windows, the DEFAULT parameter can be used to set the icon
2276 for the widget and any descendants that don't have an icon set
2277 explicitly. DEFAULT can be the relative path to a .ico file
2278 (example: root.iconbitmap(default='myicon.ico') ). See Tk
2279 documentation for more information."""
2280 if default is not None:
2281 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
2282 else:
2283 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
2284
2285 iconbitmap = wm_iconbitmap
2286
2287 def wm_iconify(self):
2288 """Display widget as icon."""
2289 return self.tk.call('wm', 'iconify', self._w)
2290
2291 iconify = wm_iconify
2292
2293 def wm_iconmask(self, bitmap=None):
2294 """Set mask for the icon bitmap of this widget. Return the
2295 mask if None is given."""
2296 return self.tk.call('wm', 'iconmask', self._w, bitmap)
2297
2298 iconmask = wm_iconmask
2299
2300 def wm_iconname(self, newName=None):
2301 """Set the name of the icon for this widget. Return the name if
2302 None is given."""
2303 return self.tk.call('wm', 'iconname', self._w, newName)
2304
2305 iconname = wm_iconname
2306
2307 def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
2308 """Sets the titlebar icon for this window based on the named photo
2309 images passed through args. If default is True, this is applied to
2310 all future created toplevels as well.
2311
2312 The data in the images is taken as a snapshot at the time of
2313 invocation. If the images are later changed, this is not reflected
2314 to the titlebar icons. Multiple images are accepted to allow
2315 different images sizes to be provided. The window manager may scale
2316 provided icons to an appropriate size.
2317
2318 On Windows, the images are packed into a Windows icon structure.
2319 This will override an icon specified to wm_iconbitmap, and vice
2320 versa.
2321
2322 On X, the images are arranged into the _NET_WM_ICON X property,
2323 which most modern window managers support. An icon specified by
2324 wm_iconbitmap may exist simultaneously.
2325
2326 On Macintosh, this currently does nothing."""
2327 if default:
2328 self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
2329 else:
2330 self.tk.call('wm', 'iconphoto', self._w, *args)
2331
2332 iconphoto = wm_iconphoto
2333
2334 def wm_iconposition(self, x=None, y=None):
2335 """Set the position of the icon of this widget to X and Y. Return
2336 a tuple of the current values of X and X if None is given."""
2337 return self._getints(self.tk.call(
2338 'wm', 'iconposition', self._w, x, y))
2339
2340 iconposition = wm_iconposition
2341
2342 def wm_iconwindow(self, pathName=None):
2343 """Set widget PATHNAME to be displayed instead of icon. Return the current
2344 value if None is given."""
2345 return self.tk.call('wm', 'iconwindow', self._w, pathName)
2346
2347 iconwindow = wm_iconwindow
2348
2349 def wm_manage(self, widget): # new in Tk 8.5
2350 """The widget specified will become a stand alone top-level window.
2351 The window will be decorated with the window managers title bar,
2352 etc."""
2353 self.tk.call('wm', 'manage', widget)
2354
2355 manage = wm_manage
2356
2357 def wm_maxsize(self, width=None, height=None):
2358 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
2359 the values are given in grid units. Return the current values if None
2360 is given."""
2361 return self._getints(self.tk.call(
2362 'wm', 'maxsize', self._w, width, height))
2363
2364 maxsize = wm_maxsize
2365
2366 def wm_minsize(self, width=None, height=None):
2367 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
2368 the values are given in grid units. Return the current values if None
2369 is given."""
2370 return self._getints(self.tk.call(
2371 'wm', 'minsize', self._w, width, height))
2372
2373 minsize = wm_minsize
2374
2375 def wm_overrideredirect(self, boolean=None):
2376 """Instruct the window manager to ignore this widget
2377 if BOOLEAN is given with 1. Return the current value if None
2378 is given."""
2379 return self._getboolean(self.tk.call(
2380 'wm', 'overrideredirect', self._w, boolean))
2381
2382 overrideredirect = wm_overrideredirect
2383
2384 def wm_positionfrom(self, who=None):
2385 """Instruct the window manager that the position of this widget shall
2386 be defined by the user if WHO is "user", and by its own policy if WHO is
2387 "program"."""
2388 return self.tk.call('wm', 'positionfrom', self._w, who)
2389
2390 positionfrom = wm_positionfrom
2391
2392 def wm_protocol(self, name=None, func=None):
2393 """Bind function FUNC to command NAME for this widget.
2394 Return the function bound to NAME if None is given. NAME could be
2395 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
2396 if callable(func):
2397 command = self._register(func)
2398 else:
2399 command = func
2400 return self.tk.call(
2401 'wm', 'protocol', self._w, name, command)
2402
2403 protocol = wm_protocol
2404
2405 def wm_resizable(self, width=None, height=None):
2406 """Instruct the window manager whether this width can be resized
2407 in WIDTH or HEIGHT. Both values are boolean values."""
2408 return self.tk.call('wm', 'resizable', self._w, width, height)
2409
2410 resizable = wm_resizable
2411
2412 def wm_sizefrom(self, who=None):
2413 """Instruct the window manager that the size of this widget shall
2414 be defined by the user if WHO is "user", and by its own policy if WHO is
2415 "program"."""
2416 return self.tk.call('wm', 'sizefrom', self._w, who)
2417
2418 sizefrom = wm_sizefrom
2419
2420 def wm_state(self, newstate=None):
2421 """Query or set the state of this widget as one of normal, icon,
2422 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
2423 return self.tk.call('wm', 'state', self._w, newstate)
2424
2425 state = wm_state
2426
2427 def wm_title(self, string=None):
2428 """Set the title of this widget."""
2429 return self.tk.call('wm', 'title', self._w, string)
2430
2431 title = wm_title
2432
2433 def wm_transient(self, master=None):
2434 """Instruct the window manager that this widget is transient
2435 with regard to widget MASTER."""
2436 return self.tk.call('wm', 'transient', self._w, master)
2437
2438 transient = wm_transient
2439
2440 def wm_withdraw(self):
2441 """Withdraw this widget from the screen such that it is unmapped
2442 and forgotten by the window manager. Re-draw it with wm_deiconify."""
2443 return self.tk.call('wm', 'withdraw', self._w)
2444
2445 withdraw = wm_withdraw
2446
2447
2448 class Tk(Misc, Wm):
2449 """Toplevel widget of Tk which represents mostly the main window
2450 of an application. It has an associated Tcl interpreter."""
2451 _w = '.'
2452
2453 def __init__(self, screenName=None, baseName=None, className='Tk',
2454 useTk=True, sync=False, use=None):
2455 """Return a new top level widget on screen SCREENNAME. A new Tcl interpreter will
2456 be created. BASENAME will be used for the identification of the profile file (see
2457 readprofile).
2458 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
2459 is the name of the widget class."""
2460 self.master = None
2461 self.children = {}
2462 self._tkloaded = False
2463 # to avoid recursions in the getattr code in case of failure, we
2464 # ensure that self.tk is always _something_.
2465 self.tk = None
2466 if baseName is None:
2467 import os
2468 baseName = os.path.basename(sys.argv[0])
2469 baseName, ext = os.path.splitext(baseName)
2470 if ext not in ('.py', '.pyc'):
2471 baseName = baseName + ext
2472 interactive = False
2473 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
2474 if _debug:
2475 self.tk.settrace(_print_command)
2476 if useTk:
2477 self._loadtk()
2478 if not sys.flags.ignore_environment:
2479 # Issue #16248: Honor the -E flag to avoid code injection.
2480 self.readprofile(baseName, className)
2481
2482 def loadtk(self):
2483 if not self._tkloaded:
2484 self.tk.loadtk()
2485 self._loadtk()
2486
2487 def _loadtk(self):
2488 self._tkloaded = True
2489 global _default_root
2490 # Version sanity checks
2491 tk_version = self.tk.getvar('tk_version')
2492 if tk_version != _tkinter.TK_VERSION:
2493 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
2494 % (_tkinter.TK_VERSION, tk_version))
2495 # Under unknown circumstances, tcl_version gets coerced to float
2496 tcl_version = str(self.tk.getvar('tcl_version'))
2497 if tcl_version != _tkinter.TCL_VERSION:
2498 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
2499 % (_tkinter.TCL_VERSION, tcl_version))
2500 # Create and register the tkerror and exit commands
2501 # We need to inline parts of _register here, _ register
2502 # would register differently-named commands.
2503 if self._tclCommands is None:
2504 self._tclCommands = []
2505 self.tk.createcommand('tkerror', _tkerror)
2506 self.tk.createcommand('exit', _exit)
2507 self._tclCommands.append('tkerror')
2508 self._tclCommands.append('exit')
2509 if _support_default_root and _default_root is None:
2510 _default_root = self
2511 self.protocol("WM_DELETE_WINDOW", self.destroy)
2512
2513 def destroy(self):
2514 """Destroy this and all descendants widgets. This will
2515 end the application of this Tcl interpreter."""
2516 for c in list(self.children.values()): c.destroy()
2517 self.tk.call('destroy', self._w)
2518 Misc.destroy(self)
2519 global _default_root
2520 if _support_default_root and _default_root is self:
2521 _default_root = None
2522
2523 def readprofile(self, baseName, className):
2524 """Internal function. It reads .BASENAME.tcl and .CLASSNAME.tcl into
2525 the Tcl Interpreter and calls exec on the contents of .BASENAME.py and
2526 .CLASSNAME.py if such a file exists in the home directory."""
2527 import os
2528 if 'HOME' in os.environ: home = os.environ['HOME']
2529 else: home = os.curdir
2530 class_tcl = os.path.join(home, '.%s.tcl' % className)
2531 class_py = os.path.join(home, '.%s.py' % className)
2532 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
2533 base_py = os.path.join(home, '.%s.py' % baseName)
2534 dir = {'self': self}
2535 exec('from tkinter import *', dir)
2536 if os.path.isfile(class_tcl):
2537 self.tk.call('source', class_tcl)
2538 if os.path.isfile(class_py):
2539 exec(open(class_py).read(), dir)
2540 if os.path.isfile(base_tcl):
2541 self.tk.call('source', base_tcl)
2542 if os.path.isfile(base_py):
2543 exec(open(base_py).read(), dir)
2544
2545 def report_callback_exception(self, exc, val, tb):
2546 """Report callback exception on sys.stderr.
2547
2548 Applications may want to override this internal function, and
2549 should when sys.stderr is None."""
2550 import traceback
2551 print("Exception in Tkinter callback", file=sys.stderr)
2552 sys.last_exc = val
2553 sys.last_type = exc
2554 sys.last_value = val
2555 sys.last_traceback = tb
2556 traceback.print_exception(exc, val, tb)
2557
2558 def __getattr__(self, attr):
2559 "Delegate attribute access to the interpreter object"
2560 return getattr(self.tk, attr)
2561
2562
2563 def _print_command(cmd, *, file=sys.stderr):
2564 # Print executed Tcl/Tk commands.
2565 assert isinstance(cmd, tuple)
2566 cmd = _join(cmd)
2567 print(cmd, file=file)
2568
2569
2570 # Ideally, the classes Pack, Place and Grid disappear, the
2571 # pack/place/grid methods are defined on the Widget class, and
2572 # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
2573 # ...), with pack(), place() and grid() being short for
2574 # pack_configure(), place_configure() and grid_columnconfigure(), and
2575 # forget() being short for pack_forget(). As a practical matter, I'm
2576 # afraid that there is too much code out there that may be using the
2577 # Pack, Place or Grid class, so I leave them intact -- but only as
2578 # backwards compatibility features. Also note that those methods that
2579 # take a master as argument (e.g. pack_propagate) have been moved to
2580 # the Misc class (which now incorporates all methods common between
2581 # toplevel and interior widgets). Again, for compatibility, these are
2582 # copied into the Pack, Place or Grid class.
2583
2584
2585 def Tcl(screenName=None, baseName=None, className='Tk', useTk=False):
2586 return Tk(screenName, baseName, className, useTk)
2587
2588
2589 class Pack:
2590 """Geometry manager Pack.
2591
2592 Base class to use the methods pack_* in every widget."""
2593
2594 def pack_configure(self, cnf={}, **kw):
2595 """Pack a widget in the parent widget. Use as options:
2596 after=widget - pack it after you have packed widget
2597 anchor=NSEW (or subset) - position widget according to
2598 given direction
2599 before=widget - pack it before you will pack widget
2600 expand=bool - expand widget if parent size grows
2601 fill=NONE or X or Y or BOTH - fill widget if widget grows
2602 in=container - use the container widget to contain this widget
2603 in_=container - see 'in' option description
2604 ipadx=amount - add internal padding in x direction
2605 ipady=amount - add internal padding in y direction
2606 padx=amount - add padding in x direction
2607 pady=amount - add padding in y direction
2608 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
2609 """
2610 self.tk.call(
2611 ('pack', 'configure', self._w)
2612 + self._options(cnf, kw))
2613
2614 pack = configure = config = pack_configure
2615
2616 def pack_forget(self):
2617 """Unmap this widget and do not use it for the packing order."""
2618 self.tk.call('pack', 'forget', self._w)
2619
2620 forget = pack_forget
2621
2622 def pack_info(self):
2623 """Return information about the packing options
2624 for this widget."""
2625 d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
2626 if 'in' in d:
2627 d['in'] = self.nametowidget(d['in'])
2628 return d
2629
2630 info = pack_info
2631 propagate = pack_propagate = Misc.pack_propagate
2632 slaves = pack_slaves = Misc.pack_slaves
2633
2634
2635 class Place:
2636 """Geometry manager Place.
2637
2638 Base class to use the methods place_* in every widget."""
2639
2640 def place_configure(self, cnf={}, **kw):
2641 """Place a widget in the parent widget. Use as options:
2642 in=container - the container widget relative to which this widget is
2643 placed
2644 in_=container - see 'in' option description
2645 x=amount - locate anchor of this widget at position x of the
2646 container widget
2647 y=amount - locate anchor of this widget at position y of the
2648 container widget
2649 relx=amount - locate anchor of this widget between 0.0 and 1.0
2650 relative to width of the container widget (1.0 is
2651 right edge)
2652 rely=amount - locate anchor of this widget between 0.0 and 1.0
2653 relative to height of the container widget (1.0 is
2654 bottom edge)
2655 anchor=NSEW (or subset) - position anchor according to given
2656 direction
2657 width=amount - width of this widget in pixel
2658 height=amount - height of this widget in pixel
2659 relwidth=amount - width of this widget between 0.0 and 1.0
2660 relative to width of the container widget (1.0 is
2661 the same width as the container widget)
2662 relheight=amount - height of this widget between 0.0 and 1.0
2663 relative to height of the container widget (1.0
2664 is the same height as the container widget)
2665 bordermode="inside" or "outside" - whether to take border width of
2666 the container widget into account
2667 """
2668 self.tk.call(
2669 ('place', 'configure', self._w)
2670 + self._options(cnf, kw))
2671
2672 place = configure = config = place_configure
2673
2674 def place_forget(self):
2675 """Unmap this widget."""
2676 self.tk.call('place', 'forget', self._w)
2677
2678 forget = place_forget
2679
2680 def place_info(self):
2681 """Return information about the placing options
2682 for this widget."""
2683 d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
2684 if 'in' in d:
2685 d['in'] = self.nametowidget(d['in'])
2686 return d
2687
2688 info = place_info
2689 slaves = place_slaves = Misc.place_slaves
2690
2691
2692 class Grid:
2693 """Geometry manager Grid.
2694
2695 Base class to use the methods grid_* in every widget."""
2696 # Thanks to Masazumi Yoshikawa ([email protected])
2697
2698 def grid_configure(self, cnf={}, **kw):
2699 """Position a widget in the parent widget in a grid. Use as options:
2700 column=number - use cell identified with given column (starting with 0)
2701 columnspan=number - this widget will span several columns
2702 in=container - use the container widget to contain this widget
2703 in_=container - see 'in' option description
2704 ipadx=amount - add internal padding in x direction
2705 ipady=amount - add internal padding in y direction
2706 padx=amount - add padding in x direction
2707 pady=amount - add padding in y direction
2708 row=number - use cell identified with given row (starting with 0)
2709 rowspan=number - this widget will span several rows
2710 sticky=NSEW - if cell is larger on which sides will this
2711 widget stick to the cell boundary
2712 """
2713 self.tk.call(
2714 ('grid', 'configure', self._w)
2715 + self._options(cnf, kw))
2716
2717 grid = configure = config = grid_configure
2718 bbox = grid_bbox = Misc.grid_bbox
2719 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
2720
2721 def grid_forget(self):
2722 """Unmap this widget."""
2723 self.tk.call('grid', 'forget', self._w)
2724
2725 forget = grid_forget
2726
2727 def grid_remove(self):
2728 """Unmap this widget but remember the grid options."""
2729 self.tk.call('grid', 'remove', self._w)
2730
2731 def grid_info(self):
2732 """Return information about the options
2733 for positioning this widget in a grid."""
2734 d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
2735 if 'in' in d:
2736 d['in'] = self.nametowidget(d['in'])
2737 return d
2738
2739 info = grid_info
2740 location = grid_location = Misc.grid_location
2741 propagate = grid_propagate = Misc.grid_propagate
2742 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
2743 size = grid_size = Misc.grid_size
2744 slaves = grid_slaves = Misc.grid_slaves
2745
2746
2747 class BaseWidget(Misc):
2748 """Internal class."""
2749
2750 def _setup(self, master, cnf):
2751 """Internal function. Sets up information about children."""
2752 if master is None:
2753 master = _get_default_root()
2754 self.master = master
2755 self.tk = master.tk
2756 name = None
2757 if 'name' in cnf:
2758 name = cnf['name']
2759 del cnf['name']
2760 if not name:
2761 name = self.__class__.__name__.lower()
2762 if name[-1].isdigit():
2763 name += "!" # Avoid duplication when calculating names below
2764 if master._last_child_ids is None:
2765 master._last_child_ids = {}
2766 count = master._last_child_ids.get(name, 0) + 1
2767 master._last_child_ids[name] = count
2768 if count == 1:
2769 name = '!%s' % (name,)
2770 else:
2771 name = '!%s%d' % (name, count)
2772 self._name = name
2773 if master._w=='.':
2774 self._w = '.' + name
2775 else:
2776 self._w = master._w + '.' + name
2777 self.children = {}
2778 if self._name in self.master.children:
2779 self.master.children[self._name].destroy()
2780 self.master.children[self._name] = self
2781
2782 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2783 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2784 and appropriate options."""
2785 if kw:
2786 cnf = _cnfmerge((cnf, kw))
2787 self.widgetName = widgetName
2788 self._setup(master, cnf)
2789 if self._tclCommands is None:
2790 self._tclCommands = []
2791 classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
2792 for k, v in classes:
2793 del cnf[k]
2794 self.tk.call(
2795 (widgetName, self._w) + extra + self._options(cnf))
2796 for k, v in classes:
2797 k.configure(self, v)
2798
2799 def destroy(self):
2800 """Destroy this and all descendants widgets."""
2801 for c in list(self.children.values()): c.destroy()
2802 self.tk.call('destroy', self._w)
2803 if self._name in self.master.children:
2804 del self.master.children[self._name]
2805 Misc.destroy(self)
2806
2807 def _do(self, name, args=()):
2808 # XXX Obsolete -- better use self.tk.call directly!
2809 return self.tk.call((self._w, name) + args)
2810
2811
2812 class Widget(BaseWidget, Pack, Place, Grid):
2813 """Internal class.
2814
2815 Base class for a widget which can be positioned with the geometry managers
2816 Pack, Place or Grid."""
2817 pass
2818
2819
2820 class Toplevel(BaseWidget, Wm):
2821 """Toplevel widget, e.g. for dialogs."""
2822
2823 def __init__(self, master=None, cnf={}, **kw):
2824 """Construct a toplevel widget with the parent MASTER.
2825
2826 Valid option names: background, bd, bg, borderwidth, class,
2827 colormap, container, cursor, height, highlightbackground,
2828 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2829 use, visual, width."""
2830 if kw:
2831 cnf = _cnfmerge((cnf, kw))
2832 extra = ()
2833 for wmkey in ['screen', 'class_', 'class', 'visual',
2834 'colormap']:
2835 if wmkey in cnf:
2836 val = cnf[wmkey]
2837 # TBD: a hack needed because some keys
2838 # are not valid as keyword arguments
2839 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2840 else: opt = '-'+wmkey
2841 extra = extra + (opt, val)
2842 del cnf[wmkey]
2843 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2844 root = self._root()
2845 self.iconname(root.iconname())
2846 self.title(root.title())
2847 self.protocol("WM_DELETE_WINDOW", self.destroy)
2848
2849
2850 class Button(Widget):
2851 """Button widget."""
2852
2853 def __init__(self, master=None, cnf={}, **kw):
2854 """Construct a button widget with the parent MASTER.
2855
2856 STANDARD OPTIONS
2857
2858 activebackground, activeforeground, anchor,
2859 background, bitmap, borderwidth, cursor,
2860 disabledforeground, font, foreground
2861 highlightbackground, highlightcolor,
2862 highlightthickness, image, justify,
2863 padx, pady, relief, repeatdelay,
2864 repeatinterval, takefocus, text,
2865 textvariable, underline, wraplength
2866
2867 WIDGET-SPECIFIC OPTIONS
2868
2869 command, compound, default, height,
2870 overrelief, state, width
2871 """
2872 Widget.__init__(self, master, 'button', cnf, kw)
2873
2874 def flash(self):
2875 """Flash the button.
2876
2877 This is accomplished by redisplaying
2878 the button several times, alternating between active and
2879 normal colors. At the end of the flash the button is left
2880 in the same normal/active state as when the command was
2881 invoked. This command is ignored if the button's state is
2882 disabled.
2883 """
2884 self.tk.call(self._w, 'flash')
2885
2886 def invoke(self):
2887 """Invoke the command associated with the button.
2888
2889 The return value is the return value from the command,
2890 or an empty string if there is no command associated with
2891 the button. This command is ignored if the button's state
2892 is disabled.
2893 """
2894 return self.tk.call(self._w, 'invoke')
2895
2896
2897 class Canvas(Widget, XView, YView):
2898 """Canvas widget to display graphical elements like lines or text."""
2899
2900 def __init__(self, master=None, cnf={}, **kw):
2901 """Construct a canvas widget with the parent MASTER.
2902
2903 Valid option names: background, bd, bg, borderwidth, closeenough,
2904 confine, cursor, height, highlightbackground, highlightcolor,
2905 highlightthickness, insertbackground, insertborderwidth,
2906 insertofftime, insertontime, insertwidth, offset, relief,
2907 scrollregion, selectbackground, selectborderwidth, selectforeground,
2908 state, takefocus, width, xscrollcommand, xscrollincrement,
2909 yscrollcommand, yscrollincrement."""
2910 Widget.__init__(self, master, 'canvas', cnf, kw)
2911
2912 def addtag(self, *args):
2913 """Internal function."""
2914 self.tk.call((self._w, 'addtag') + args)
2915
2916 def addtag_above(self, newtag, tagOrId):
2917 """Add tag NEWTAG to all items above TAGORID."""
2918 self.addtag(newtag, 'above', tagOrId)
2919
2920 def addtag_all(self, newtag):
2921 """Add tag NEWTAG to all items."""
2922 self.addtag(newtag, 'all')
2923
2924 def addtag_below(self, newtag, tagOrId):
2925 """Add tag NEWTAG to all items below TAGORID."""
2926 self.addtag(newtag, 'below', tagOrId)
2927
2928 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2929 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2930 If several match take the top-most.
2931 All items closer than HALO are considered overlapping (all are
2932 closest). If START is specified the next below this tag is taken."""
2933 self.addtag(newtag, 'closest', x, y, halo, start)
2934
2935 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2936 """Add tag NEWTAG to all items in the rectangle defined
2937 by X1,Y1,X2,Y2."""
2938 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2939
2940 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2941 """Add tag NEWTAG to all items which overlap the rectangle
2942 defined by X1,Y1,X2,Y2."""
2943 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2944
2945 def addtag_withtag(self, newtag, tagOrId):
2946 """Add tag NEWTAG to all items with TAGORID."""
2947 self.addtag(newtag, 'withtag', tagOrId)
2948
2949 def bbox(self, *args):
2950 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2951 which encloses all items with tags specified as arguments."""
2952 return self._getints(
2953 self.tk.call((self._w, 'bbox') + args)) or None
2954
2955 def tag_unbind(self, tagOrId, sequence, funcid=None):
2956 """Unbind for all items with TAGORID for event SEQUENCE the
2957 function identified with FUNCID."""
2958 self._unbind((self._w, 'bind', tagOrId, sequence), funcid)
2959
2960 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2961 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
2962
2963 An additional boolean parameter ADD specifies whether FUNC will be
2964 called additionally to the other bound function or whether it will
2965 replace the previous function. See bind for the return value."""
2966 return self._bind((self._w, 'bind', tagOrId),
2967 sequence, func, add)
2968
2969 def canvasx(self, screenx, gridspacing=None):
2970 """Return the canvas x coordinate of pixel position SCREENX rounded
2971 to nearest multiple of GRIDSPACING units."""
2972 return self.tk.getdouble(self.tk.call(
2973 self._w, 'canvasx', screenx, gridspacing))
2974
2975 def canvasy(self, screeny, gridspacing=None):
2976 """Return the canvas y coordinate of pixel position SCREENY rounded
2977 to nearest multiple of GRIDSPACING units."""
2978 return self.tk.getdouble(self.tk.call(
2979 self._w, 'canvasy', screeny, gridspacing))
2980
2981 def coords(self, *args):
2982 """Return a list of coordinates for the item given in ARGS."""
2983 args = _flatten(args)
2984 return [self.tk.getdouble(x) for x in
2985 self.tk.splitlist(
2986 self.tk.call((self._w, 'coords') + args))]
2987
2988 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2989 """Internal function."""
2990 args = _flatten(args)
2991 cnf = args[-1]
2992 if isinstance(cnf, (dict, tuple)):
2993 args = args[:-1]
2994 else:
2995 cnf = {}
2996 return self.tk.getint(self.tk.call(
2997 self._w, 'create', itemType,
2998 *(args + self._options(cnf, kw))))
2999
3000 def create_arc(self, *args, **kw):
3001 """Create arc shaped region with coordinates x1,y1,x2,y2."""
3002 return self._create('arc', args, kw)
3003
3004 def create_bitmap(self, *args, **kw):
3005 """Create bitmap with coordinates x1,y1."""
3006 return self._create('bitmap', args, kw)
3007
3008 def create_image(self, *args, **kw):
3009 """Create image item with coordinates x1,y1."""
3010 return self._create('image', args, kw)
3011
3012 def create_line(self, *args, **kw):
3013 """Create line with coordinates x1,y1,...,xn,yn."""
3014 return self._create('line', args, kw)
3015
3016 def create_oval(self, *args, **kw):
3017 """Create oval with coordinates x1,y1,x2,y2."""
3018 return self._create('oval', args, kw)
3019
3020 def create_polygon(self, *args, **kw):
3021 """Create polygon with coordinates x1,y1,...,xn,yn."""
3022 return self._create('polygon', args, kw)
3023
3024 def create_rectangle(self, *args, **kw):
3025 """Create rectangle with coordinates x1,y1,x2,y2."""
3026 return self._create('rectangle', args, kw)
3027
3028 def create_text(self, *args, **kw):
3029 """Create text with coordinates x1,y1."""
3030 return self._create('text', args, kw)
3031
3032 def create_window(self, *args, **kw):
3033 """Create window with coordinates x1,y1,x2,y2."""
3034 return self._create('window', args, kw)
3035
3036 def dchars(self, *args):
3037 """Delete characters of text items identified by tag or id in ARGS (possibly
3038 several times) from FIRST to LAST character (including)."""
3039 self.tk.call((self._w, 'dchars') + args)
3040
3041 def delete(self, *args):
3042 """Delete items identified by all tag or ids contained in ARGS."""
3043 self.tk.call((self._w, 'delete') + args)
3044
3045 def dtag(self, *args):
3046 """Delete tag or id given as last arguments in ARGS from items
3047 identified by first argument in ARGS."""
3048 self.tk.call((self._w, 'dtag') + args)
3049
3050 def find(self, *args):
3051 """Internal function."""
3052 return self._getints(
3053 self.tk.call((self._w, 'find') + args)) or ()
3054
3055 def find_above(self, tagOrId):
3056 """Return items above TAGORID."""
3057 return self.find('above', tagOrId)
3058
3059 def find_all(self):
3060 """Return all items."""
3061 return self.find('all')
3062
3063 def find_below(self, tagOrId):
3064 """Return all items below TAGORID."""
3065 return self.find('below', tagOrId)
3066
3067 def find_closest(self, x, y, halo=None, start=None):
3068 """Return item which is closest to pixel at X, Y.
3069 If several match take the top-most.
3070 All items closer than HALO are considered overlapping (all are
3071 closest). If START is specified the next below this tag is taken."""
3072 return self.find('closest', x, y, halo, start)
3073
3074 def find_enclosed(self, x1, y1, x2, y2):
3075 """Return all items in rectangle defined
3076 by X1,Y1,X2,Y2."""
3077 return self.find('enclosed', x1, y1, x2, y2)
3078
3079 def find_overlapping(self, x1, y1, x2, y2):
3080 """Return all items which overlap the rectangle
3081 defined by X1,Y1,X2,Y2."""
3082 return self.find('overlapping', x1, y1, x2, y2)
3083
3084 def find_withtag(self, tagOrId):
3085 """Return all items with TAGORID."""
3086 return self.find('withtag', tagOrId)
3087
3088 def focus(self, *args):
3089 """Set focus to the first item specified in ARGS."""
3090 return self.tk.call((self._w, 'focus') + args)
3091
3092 def gettags(self, *args):
3093 """Return tags associated with the first item specified in ARGS."""
3094 return self.tk.splitlist(
3095 self.tk.call((self._w, 'gettags') + args))
3096
3097 def icursor(self, *args):
3098 """Set cursor at position POS in the item identified by TAGORID.
3099 In ARGS TAGORID must be first."""
3100 self.tk.call((self._w, 'icursor') + args)
3101
3102 def index(self, *args):
3103 """Return position of cursor as integer in item specified in ARGS."""
3104 return self.tk.getint(self.tk.call((self._w, 'index') + args))
3105
3106 def insert(self, *args):
3107 """Insert TEXT in item TAGORID at position POS. ARGS must
3108 be TAGORID POS TEXT."""
3109 self.tk.call((self._w, 'insert') + args)
3110
3111 def itemcget(self, tagOrId, option):
3112 """Return the value of OPTION for item TAGORID."""
3113 return self.tk.call(
3114 (self._w, 'itemcget') + (tagOrId, '-'+option))
3115
3116 def itemconfigure(self, tagOrId, cnf=None, **kw):
3117 """Query or modify the configuration options of an item TAGORID.
3118
3119 Similar to configure() except that it applies to the specified item.
3120 """
3121 return self._configure(('itemconfigure', tagOrId), cnf, kw)
3122
3123 itemconfig = itemconfigure
3124
3125 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
3126 # so the preferred name for them is tag_lower, tag_raise
3127 # (similar to tag_bind, and similar to the Text widget);
3128 # unfortunately can't delete the old ones yet (maybe in 1.6)
3129 def tag_lower(self, *args):
3130 """Lower an item TAGORID given in ARGS
3131 (optional below another item)."""
3132 self.tk.call((self._w, 'lower') + args)
3133
3134 lower = tag_lower
3135
3136 def move(self, *args):
3137 """Move an item TAGORID given in ARGS."""
3138 self.tk.call((self._w, 'move') + args)
3139
3140 def moveto(self, tagOrId, x='', y=''):
3141 """Move the items given by TAGORID in the canvas coordinate
3142 space so that the first coordinate pair of the bottommost
3143 item with tag TAGORID is located at position (X,Y).
3144 X and Y may be the empty string, in which case the
3145 corresponding coordinate will be unchanged. All items matching
3146 TAGORID remain in the same positions relative to each other."""
3147 self.tk.call(self._w, 'moveto', tagOrId, x, y)
3148
3149 def postscript(self, cnf={}, **kw):
3150 """Print the contents of the canvas to a postscript
3151 file. Valid options: colormap, colormode, file, fontmap,
3152 height, pageanchor, pageheight, pagewidth, pagex, pagey,
3153 rotate, width, x, y."""
3154 return self.tk.call((self._w, 'postscript') +
3155 self._options(cnf, kw))
3156
3157 def tag_raise(self, *args):
3158 """Raise an item TAGORID given in ARGS
3159 (optional above another item)."""
3160 self.tk.call((self._w, 'raise') + args)
3161
3162 lift = tkraise = tag_raise
3163
3164 def scale(self, *args):
3165 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
3166 self.tk.call((self._w, 'scale') + args)
3167
3168 def scan_mark(self, x, y):
3169 """Remember the current X, Y coordinates."""
3170 self.tk.call(self._w, 'scan', 'mark', x, y)
3171
3172 def scan_dragto(self, x, y, gain=10):
3173 """Adjust the view of the canvas to GAIN times the
3174 difference between X and Y and the coordinates given in
3175 scan_mark."""
3176 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
3177
3178 def select_adjust(self, tagOrId, index):
3179 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
3180 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
3181
3182 def select_clear(self):
3183 """Clear the selection if it is in this widget."""
3184 self.tk.call(self._w, 'select', 'clear')
3185
3186 def select_from(self, tagOrId, index):
3187 """Set the fixed end of a selection in item TAGORID to INDEX."""
3188 self.tk.call(self._w, 'select', 'from', tagOrId, index)
3189
3190 def select_item(self):
3191 """Return the item which has the selection."""
3192 return self.tk.call(self._w, 'select', 'item') or None
3193
3194 def select_to(self, tagOrId, index):
3195 """Set the variable end of a selection in item TAGORID to INDEX."""
3196 self.tk.call(self._w, 'select', 'to', tagOrId, index)
3197
3198 def type(self, tagOrId):
3199 """Return the type of the item TAGORID."""
3200 return self.tk.call(self._w, 'type', tagOrId) or None
3201
3202
3203 _checkbutton_count = 0
3204
3205 class Checkbutton(Widget):
3206 """Checkbutton widget which is either in on- or off-state."""
3207
3208 def __init__(self, master=None, cnf={}, **kw):
3209 """Construct a checkbutton widget with the parent MASTER.
3210
3211 Valid option names: activebackground, activeforeground, anchor,
3212 background, bd, bg, bitmap, borderwidth, command, cursor,
3213 disabledforeground, fg, font, foreground, height,
3214 highlightbackground, highlightcolor, highlightthickness, image,
3215 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
3216 selectcolor, selectimage, state, takefocus, text, textvariable,
3217 underline, variable, width, wraplength."""
3218 Widget.__init__(self, master, 'checkbutton', cnf, kw)
3219
3220 def _setup(self, master, cnf):
3221 # Because Checkbutton defaults to a variable with the same name as
3222 # the widget, Checkbutton default names must be globally unique,
3223 # not just unique within the parent widget.
3224 if not cnf.get('name'):
3225 global _checkbutton_count
3226 name = self.__class__.__name__.lower()
3227 _checkbutton_count += 1
3228 # To avoid collisions with ttk.Checkbutton, use the different
3229 # name template.
3230 cnf['name'] = f'!{name}-{_checkbutton_count}'
3231 super()._setup(master, cnf)
3232
3233 def deselect(self):
3234 """Put the button in off-state."""
3235 self.tk.call(self._w, 'deselect')
3236
3237 def flash(self):
3238 """Flash the button."""
3239 self.tk.call(self._w, 'flash')
3240
3241 def invoke(self):
3242 """Toggle the button and invoke a command if given as option."""
3243 return self.tk.call(self._w, 'invoke')
3244
3245 def select(self):
3246 """Put the button in on-state."""
3247 self.tk.call(self._w, 'select')
3248
3249 def toggle(self):
3250 """Toggle the button."""
3251 self.tk.call(self._w, 'toggle')
3252
3253
3254 class Entry(Widget, XView):
3255 """Entry widget which allows displaying simple text."""
3256
3257 def __init__(self, master=None, cnf={}, **kw):
3258 """Construct an entry widget with the parent MASTER.
3259
3260 Valid option names: background, bd, bg, borderwidth, cursor,
3261 exportselection, fg, font, foreground, highlightbackground,
3262 highlightcolor, highlightthickness, insertbackground,
3263 insertborderwidth, insertofftime, insertontime, insertwidth,
3264 invalidcommand, invcmd, justify, relief, selectbackground,
3265 selectborderwidth, selectforeground, show, state, takefocus,
3266 textvariable, validate, validatecommand, vcmd, width,
3267 xscrollcommand."""
3268 Widget.__init__(self, master, 'entry', cnf, kw)
3269
3270 def delete(self, first, last=None):
3271 """Delete text from FIRST to LAST (not included)."""
3272 self.tk.call(self._w, 'delete', first, last)
3273
3274 def get(self):
3275 """Return the text."""
3276 return self.tk.call(self._w, 'get')
3277
3278 def icursor(self, index):
3279 """Insert cursor at INDEX."""
3280 self.tk.call(self._w, 'icursor', index)
3281
3282 def index(self, index):
3283 """Return position of cursor."""
3284 return self.tk.getint(self.tk.call(
3285 self._w, 'index', index))
3286
3287 def insert(self, index, string):
3288 """Insert STRING at INDEX."""
3289 self.tk.call(self._w, 'insert', index, string)
3290
3291 def scan_mark(self, x):
3292 """Remember the current X, Y coordinates."""
3293 self.tk.call(self._w, 'scan', 'mark', x)
3294
3295 def scan_dragto(self, x):
3296 """Adjust the view of the canvas to 10 times the
3297 difference between X and Y and the coordinates given in
3298 scan_mark."""
3299 self.tk.call(self._w, 'scan', 'dragto', x)
3300
3301 def selection_adjust(self, index):
3302 """Adjust the end of the selection near the cursor to INDEX."""
3303 self.tk.call(self._w, 'selection', 'adjust', index)
3304
3305 select_adjust = selection_adjust
3306
3307 def selection_clear(self):
3308 """Clear the selection if it is in this widget."""
3309 self.tk.call(self._w, 'selection', 'clear')
3310
3311 select_clear = selection_clear
3312
3313 def selection_from(self, index):
3314 """Set the fixed end of a selection to INDEX."""
3315 self.tk.call(self._w, 'selection', 'from', index)
3316
3317 select_from = selection_from
3318
3319 def selection_present(self):
3320 """Return True if there are characters selected in the entry, False
3321 otherwise."""
3322 return self.tk.getboolean(
3323 self.tk.call(self._w, 'selection', 'present'))
3324
3325 select_present = selection_present
3326
3327 def selection_range(self, start, end):
3328 """Set the selection from START to END (not included)."""
3329 self.tk.call(self._w, 'selection', 'range', start, end)
3330
3331 select_range = selection_range
3332
3333 def selection_to(self, index):
3334 """Set the variable end of a selection to INDEX."""
3335 self.tk.call(self._w, 'selection', 'to', index)
3336
3337 select_to = selection_to
3338
3339
3340 class Frame(Widget):
3341 """Frame widget which may contain other widgets and can have a 3D border."""
3342
3343 def __init__(self, master=None, cnf={}, **kw):
3344 """Construct a frame widget with the parent MASTER.
3345
3346 Valid option names: background, bd, bg, borderwidth, class,
3347 colormap, container, cursor, height, highlightbackground,
3348 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
3349 cnf = _cnfmerge((cnf, kw))
3350 extra = ()
3351 if 'class_' in cnf:
3352 extra = ('-class', cnf['class_'])
3353 del cnf['class_']
3354 elif 'class' in cnf:
3355 extra = ('-class', cnf['class'])
3356 del cnf['class']
3357 Widget.__init__(self, master, 'frame', cnf, {}, extra)
3358
3359
3360 class Label(Widget):
3361 """Label widget which can display text and bitmaps."""
3362
3363 def __init__(self, master=None, cnf={}, **kw):
3364 """Construct a label widget with the parent MASTER.
3365
3366 STANDARD OPTIONS
3367
3368 activebackground, activeforeground, anchor,
3369 background, bitmap, borderwidth, cursor,
3370 disabledforeground, font, foreground,
3371 highlightbackground, highlightcolor,
3372 highlightthickness, image, justify,
3373 padx, pady, relief, takefocus, text,
3374 textvariable, underline, wraplength
3375
3376 WIDGET-SPECIFIC OPTIONS
3377
3378 height, state, width
3379
3380 """
3381 Widget.__init__(self, master, 'label', cnf, kw)
3382
3383
3384 class Listbox(Widget, XView, YView):
3385 """Listbox widget which can display a list of strings."""
3386
3387 def __init__(self, master=None, cnf={}, **kw):
3388 """Construct a listbox widget with the parent MASTER.
3389
3390 Valid option names: background, bd, bg, borderwidth, cursor,
3391 exportselection, fg, font, foreground, height, highlightbackground,
3392 highlightcolor, highlightthickness, relief, selectbackground,
3393 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
3394 width, xscrollcommand, yscrollcommand, listvariable."""
3395 Widget.__init__(self, master, 'listbox', cnf, kw)
3396
3397 def activate(self, index):
3398 """Activate item identified by INDEX."""
3399 self.tk.call(self._w, 'activate', index)
3400
3401 def bbox(self, index):
3402 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
3403 which encloses the item identified by the given index."""
3404 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
3405
3406 def curselection(self):
3407 """Return the indices of currently selected item."""
3408 return self._getints(self.tk.call(self._w, 'curselection')) or ()
3409
3410 def delete(self, first, last=None):
3411 """Delete items from FIRST to LAST (included)."""
3412 self.tk.call(self._w, 'delete', first, last)
3413
3414 def get(self, first, last=None):
3415 """Get list of items from FIRST to LAST (included)."""
3416 if last is not None:
3417 return self.tk.splitlist(self.tk.call(
3418 self._w, 'get', first, last))
3419 else:
3420 return self.tk.call(self._w, 'get', first)
3421
3422 def index(self, index):
3423 """Return index of item identified with INDEX."""
3424 i = self.tk.call(self._w, 'index', index)
3425 if i == 'none': return None
3426 return self.tk.getint(i)
3427
3428 def insert(self, index, *elements):
3429 """Insert ELEMENTS at INDEX."""
3430 self.tk.call((self._w, 'insert', index) + elements)
3431
3432 def nearest(self, y):
3433 """Get index of item which is nearest to y coordinate Y."""
3434 return self.tk.getint(self.tk.call(
3435 self._w, 'nearest', y))
3436
3437 def scan_mark(self, x, y):
3438 """Remember the current X, Y coordinates."""
3439 self.tk.call(self._w, 'scan', 'mark', x, y)
3440
3441 def scan_dragto(self, x, y):
3442 """Adjust the view of the listbox to 10 times the
3443 difference between X and Y and the coordinates given in
3444 scan_mark."""
3445 self.tk.call(self._w, 'scan', 'dragto', x, y)
3446
3447 def see(self, index):
3448 """Scroll such that INDEX is visible."""
3449 self.tk.call(self._w, 'see', index)
3450
3451 def selection_anchor(self, index):
3452 """Set the fixed end oft the selection to INDEX."""
3453 self.tk.call(self._w, 'selection', 'anchor', index)
3454
3455 select_anchor = selection_anchor
3456
3457 def selection_clear(self, first, last=None):
3458 """Clear the selection from FIRST to LAST (included)."""
3459 self.tk.call(self._w,
3460 'selection', 'clear', first, last)
3461
3462 select_clear = selection_clear
3463
3464 def selection_includes(self, index):
3465 """Return True if INDEX is part of the selection."""
3466 return self.tk.getboolean(self.tk.call(
3467 self._w, 'selection', 'includes', index))
3468
3469 select_includes = selection_includes
3470
3471 def selection_set(self, first, last=None):
3472 """Set the selection from FIRST to LAST (included) without
3473 changing the currently selected elements."""
3474 self.tk.call(self._w, 'selection', 'set', first, last)
3475
3476 select_set = selection_set
3477
3478 def size(self):
3479 """Return the number of elements in the listbox."""
3480 return self.tk.getint(self.tk.call(self._w, 'size'))
3481
3482 def itemcget(self, index, option):
3483 """Return the value of OPTION for item at INDEX."""
3484 return self.tk.call(
3485 (self._w, 'itemcget') + (index, '-'+option))
3486
3487 def itemconfigure(self, index, cnf=None, **kw):
3488 """Query or modify the configuration options of an item at INDEX.
3489
3490 Similar to configure() except that it applies to the specified item.
3491 """
3492 return self._configure(('itemconfigure', index), cnf, kw)
3493
3494 itemconfig = itemconfigure
3495
3496
3497 class Menu(Widget):
3498 """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
3499
3500 def __init__(self, master=None, cnf={}, **kw):
3501 """Construct menu widget with the parent MASTER.
3502
3503 Valid option names: activebackground, activeborderwidth,
3504 activeforeground, background, bd, bg, borderwidth, cursor,
3505 disabledforeground, fg, font, foreground, postcommand, relief,
3506 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
3507 Widget.__init__(self, master, 'menu', cnf, kw)
3508
3509 def tk_popup(self, x, y, entry=""):
3510 """Post the menu at position X,Y with entry ENTRY."""
3511 self.tk.call('tk_popup', self._w, x, y, entry)
3512
3513 def activate(self, index):
3514 """Activate entry at INDEX."""
3515 self.tk.call(self._w, 'activate', index)
3516
3517 def add(self, itemType, cnf={}, **kw):
3518 """Internal function."""
3519 self.tk.call((self._w, 'add', itemType) +
3520 self._options(cnf, kw))
3521
3522 def add_cascade(self, cnf={}, **kw):
3523 """Add hierarchical menu item."""
3524 self.add('cascade', cnf or kw)
3525
3526 def add_checkbutton(self, cnf={}, **kw):
3527 """Add checkbutton menu item."""
3528 self.add('checkbutton', cnf or kw)
3529
3530 def add_command(self, cnf={}, **kw):
3531 """Add command menu item."""
3532 self.add('command', cnf or kw)
3533
3534 def add_radiobutton(self, cnf={}, **kw):
3535 """Add radio menu item."""
3536 self.add('radiobutton', cnf or kw)
3537
3538 def add_separator(self, cnf={}, **kw):
3539 """Add separator."""
3540 self.add('separator', cnf or kw)
3541
3542 def insert(self, index, itemType, cnf={}, **kw):
3543 """Internal function."""
3544 self.tk.call((self._w, 'insert', index, itemType) +
3545 self._options(cnf, kw))
3546
3547 def insert_cascade(self, index, cnf={}, **kw):
3548 """Add hierarchical menu item at INDEX."""
3549 self.insert(index, 'cascade', cnf or kw)
3550
3551 def insert_checkbutton(self, index, cnf={}, **kw):
3552 """Add checkbutton menu item at INDEX."""
3553 self.insert(index, 'checkbutton', cnf or kw)
3554
3555 def insert_command(self, index, cnf={}, **kw):
3556 """Add command menu item at INDEX."""
3557 self.insert(index, 'command', cnf or kw)
3558
3559 def insert_radiobutton(self, index, cnf={}, **kw):
3560 """Add radio menu item at INDEX."""
3561 self.insert(index, 'radiobutton', cnf or kw)
3562
3563 def insert_separator(self, index, cnf={}, **kw):
3564 """Add separator at INDEX."""
3565 self.insert(index, 'separator', cnf or kw)
3566
3567 def delete(self, index1, index2=None):
3568 """Delete menu items between INDEX1 and INDEX2 (included)."""
3569 if index2 is None:
3570 index2 = index1
3571
3572 num_index1, num_index2 = self.index(index1), self.index(index2)
3573 if (num_index1 is None) or (num_index2 is None):
3574 num_index1, num_index2 = 0, -1
3575
3576 for i in range(num_index1, num_index2 + 1):
3577 if 'command' in self.entryconfig(i):
3578 c = str(self.entrycget(i, 'command'))
3579 if c:
3580 self.deletecommand(c)
3581 self.tk.call(self._w, 'delete', index1, index2)
3582
3583 def entrycget(self, index, option):
3584 """Return the value of OPTION for a menu item at INDEX."""
3585 return self.tk.call(self._w, 'entrycget', index, '-' + option)
3586
3587 def entryconfigure(self, index, cnf=None, **kw):
3588 """Query or modify the configuration options of a menu item at INDEX.
3589
3590 Similar to configure() except that it applies to the specified
3591 menu item.
3592 """
3593 return self._configure(('entryconfigure', index), cnf, kw)
3594
3595 entryconfig = entryconfigure
3596
3597 def index(self, index):
3598 """Return the index of a menu item identified by INDEX."""
3599 i = self.tk.call(self._w, 'index', index)
3600 return None if i in ('', 'none') else self.tk.getint(i) # GH-103685.
3601
3602 def invoke(self, index):
3603 """Invoke a menu item identified by INDEX and execute
3604 the associated command."""
3605 return self.tk.call(self._w, 'invoke', index)
3606
3607 def post(self, x, y):
3608 """Display a menu at position X,Y."""
3609 self.tk.call(self._w, 'post', x, y)
3610
3611 def type(self, index):
3612 """Return the type of the menu item at INDEX."""
3613 return self.tk.call(self._w, 'type', index)
3614
3615 def unpost(self):
3616 """Unmap a menu."""
3617 self.tk.call(self._w, 'unpost')
3618
3619 def xposition(self, index): # new in Tk 8.5
3620 """Return the x-position of the leftmost pixel of the menu item
3621 at INDEX."""
3622 return self.tk.getint(self.tk.call(self._w, 'xposition', index))
3623
3624 def yposition(self, index):
3625 """Return the y-position of the topmost pixel of the menu item at INDEX."""
3626 return self.tk.getint(self.tk.call(
3627 self._w, 'yposition', index))
3628
3629
3630 class Menubutton(Widget):
3631 """Menubutton widget, obsolete since Tk8.0."""
3632
3633 def __init__(self, master=None, cnf={}, **kw):
3634 Widget.__init__(self, master, 'menubutton', cnf, kw)
3635
3636
3637 class Message(Widget):
3638 """Message widget to display multiline text. Obsolete since Label does it too."""
3639
3640 def __init__(self, master=None, cnf={}, **kw):
3641 Widget.__init__(self, master, 'message', cnf, kw)
3642
3643
3644 class Radiobutton(Widget):
3645 """Radiobutton widget which shows only one of several buttons in on-state."""
3646
3647 def __init__(self, master=None, cnf={}, **kw):
3648 """Construct a radiobutton widget with the parent MASTER.
3649
3650 Valid option names: activebackground, activeforeground, anchor,
3651 background, bd, bg, bitmap, borderwidth, command, cursor,
3652 disabledforeground, fg, font, foreground, height,
3653 highlightbackground, highlightcolor, highlightthickness, image,
3654 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
3655 state, takefocus, text, textvariable, underline, value, variable,
3656 width, wraplength."""
3657 Widget.__init__(self, master, 'radiobutton', cnf, kw)
3658
3659 def deselect(self):
3660 """Put the button in off-state."""
3661
3662 self.tk.call(self._w, 'deselect')
3663
3664 def flash(self):
3665 """Flash the button."""
3666 self.tk.call(self._w, 'flash')
3667
3668 def invoke(self):
3669 """Toggle the button and invoke a command if given as option."""
3670 return self.tk.call(self._w, 'invoke')
3671
3672 def select(self):
3673 """Put the button in on-state."""
3674 self.tk.call(self._w, 'select')
3675
3676
3677 class Scale(Widget):
3678 """Scale widget which can display a numerical scale."""
3679
3680 def __init__(self, master=None, cnf={}, **kw):
3681 """Construct a scale widget with the parent MASTER.
3682
3683 Valid option names: activebackground, background, bigincrement, bd,
3684 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
3685 highlightbackground, highlightcolor, highlightthickness, label,
3686 length, orient, relief, repeatdelay, repeatinterval, resolution,
3687 showvalue, sliderlength, sliderrelief, state, takefocus,
3688 tickinterval, to, troughcolor, variable, width."""
3689 Widget.__init__(self, master, 'scale', cnf, kw)
3690
3691 def get(self):
3692 """Get the current value as integer or float."""
3693 value = self.tk.call(self._w, 'get')
3694 try:
3695 return self.tk.getint(value)
3696 except (ValueError, TypeError, TclError):
3697 return self.tk.getdouble(value)
3698
3699 def set(self, value):
3700 """Set the value to VALUE."""
3701 self.tk.call(self._w, 'set', value)
3702
3703 def coords(self, value=None):
3704 """Return a tuple (X,Y) of the point along the centerline of the
3705 trough that corresponds to VALUE or the current value if None is
3706 given."""
3707
3708 return self._getints(self.tk.call(self._w, 'coords', value))
3709
3710 def identify(self, x, y):
3711 """Return where the point X,Y lies. Valid return values are "slider",
3712 "though1" and "though2"."""
3713 return self.tk.call(self._w, 'identify', x, y)
3714
3715
3716 class Scrollbar(Widget):
3717 """Scrollbar widget which displays a slider at a certain position."""
3718
3719 def __init__(self, master=None, cnf={}, **kw):
3720 """Construct a scrollbar widget with the parent MASTER.
3721
3722 Valid option names: activebackground, activerelief,
3723 background, bd, bg, borderwidth, command, cursor,
3724 elementborderwidth, highlightbackground,
3725 highlightcolor, highlightthickness, jump, orient,
3726 relief, repeatdelay, repeatinterval, takefocus,
3727 troughcolor, width."""
3728 Widget.__init__(self, master, 'scrollbar', cnf, kw)
3729
3730 def activate(self, index=None):
3731 """Marks the element indicated by index as active.
3732 The only index values understood by this method are "arrow1",
3733 "slider", or "arrow2". If any other value is specified then no
3734 element of the scrollbar will be active. If index is not specified,
3735 the method returns the name of the element that is currently active,
3736 or None if no element is active."""
3737 return self.tk.call(self._w, 'activate', index) or None
3738
3739 def delta(self, deltax, deltay):
3740 """Return the fractional change of the scrollbar setting if it
3741 would be moved by DELTAX or DELTAY pixels."""
3742 return self.tk.getdouble(
3743 self.tk.call(self._w, 'delta', deltax, deltay))
3744
3745 def fraction(self, x, y):
3746 """Return the fractional value which corresponds to a slider
3747 position of X,Y."""
3748 return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y))
3749
3750 def identify(self, x, y):
3751 """Return the element under position X,Y as one of
3752 "arrow1","slider","arrow2" or ""."""
3753 return self.tk.call(self._w, 'identify', x, y)
3754
3755 def get(self):
3756 """Return the current fractional values (upper and lower end)
3757 of the slider position."""
3758 return self._getdoubles(self.tk.call(self._w, 'get'))
3759
3760 def set(self, first, last):
3761 """Set the fractional values of the slider position (upper and
3762 lower ends as value between 0 and 1)."""
3763 self.tk.call(self._w, 'set', first, last)
3764
3765
3766 class Text(Widget, XView, YView):
3767 """Text widget which can display text in various forms."""
3768
3769 def __init__(self, master=None, cnf={}, **kw):
3770 """Construct a text widget with the parent MASTER.
3771
3772 STANDARD OPTIONS
3773
3774 background, borderwidth, cursor,
3775 exportselection, font, foreground,
3776 highlightbackground, highlightcolor,
3777 highlightthickness, insertbackground,
3778 insertborderwidth, insertofftime,
3779 insertontime, insertwidth, padx, pady,
3780 relief, selectbackground,
3781 selectborderwidth, selectforeground,
3782 setgrid, takefocus,
3783 xscrollcommand, yscrollcommand,
3784
3785 WIDGET-SPECIFIC OPTIONS
3786
3787 autoseparators, height, maxundo,
3788 spacing1, spacing2, spacing3,
3789 state, tabs, undo, width, wrap,
3790
3791 """
3792 Widget.__init__(self, master, 'text', cnf, kw)
3793
3794 def bbox(self, index):
3795 """Return a tuple of (x,y,width,height) which gives the bounding
3796 box of the visible part of the character at the given index."""
3797 return self._getints(
3798 self.tk.call(self._w, 'bbox', index)) or None
3799
3800 def compare(self, index1, op, index2):
3801 """Return whether between index INDEX1 and index INDEX2 the
3802 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
3803 return self.tk.getboolean(self.tk.call(
3804 self._w, 'compare', index1, op, index2))
3805
3806 def count(self, index1, index2, *options, return_ints=False): # new in Tk 8.5
3807 """Counts the number of relevant things between the two indices.
3808
3809 If INDEX1 is after INDEX2, the result will be a negative number
3810 (and this holds for each of the possible options).
3811
3812 The actual items which are counted depends on the options given.
3813 The result is a tuple of integers, one for the result of each
3814 counting option given, if more than one option is specified or
3815 return_ints is false (default), otherwise it is an integer.
3816 Valid counting options are "chars", "displaychars",
3817 "displayindices", "displaylines", "indices", "lines", "xpixels"
3818 and "ypixels". The default value, if no option is specified, is
3819 "indices". There is an additional possible option "update",
3820 which if given then all subsequent options ensure that any
3821 possible out of date information is recalculated.
3822 """
3823 options = ['-%s' % arg for arg in options]
3824 res = self.tk.call(self._w, 'count', *options, index1, index2)
3825 if not isinstance(res, int):
3826 res = self._getints(res)
3827 if len(res) == 1:
3828 res, = res
3829 if not return_ints:
3830 if not res:
3831 res = None
3832 elif len(options) <= 1:
3833 res = (res,)
3834 return res
3835
3836 def debug(self, boolean=None):
3837 """Turn on the internal consistency checks of the B-Tree inside the text
3838 widget according to BOOLEAN."""
3839 if boolean is None:
3840 return self.tk.getboolean(self.tk.call(self._w, 'debug'))
3841 self.tk.call(self._w, 'debug', boolean)
3842
3843 def delete(self, index1, index2=None):
3844 """Delete the characters between INDEX1 and INDEX2 (not included)."""
3845 self.tk.call(self._w, 'delete', index1, index2)
3846
3847 def dlineinfo(self, index):
3848 """Return tuple (x,y,width,height,baseline) giving the bounding box
3849 and baseline position of the visible part of the line containing
3850 the character at INDEX."""
3851 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
3852
3853 def dump(self, index1, index2=None, command=None, **kw):
3854 """Return the contents of the widget between index1 and index2.
3855
3856 The type of contents returned in filtered based on the keyword
3857 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
3858 given and true, then the corresponding items are returned. The result
3859 is a list of triples of the form (key, value, index). If none of the
3860 keywords are true then 'all' is used by default.
3861
3862 If the 'command' argument is given, it is called once for each element
3863 of the list of triples, with the values of each triple serving as the
3864 arguments to the function. In this case the list is not returned."""
3865 args = []
3866 func_name = None
3867 result = None
3868 if not command:
3869 # Never call the dump command without the -command flag, since the
3870 # output could involve Tcl quoting and would be a pain to parse
3871 # right. Instead just set the command to build a list of triples
3872 # as if we had done the parsing.
3873 result = []
3874 def append_triple(key, value, index, result=result):
3875 result.append((key, value, index))
3876 command = append_triple
3877 try:
3878 if not isinstance(command, str):
3879 func_name = command = self._register(command)
3880 args += ["-command", command]
3881 for key in kw:
3882 if kw[key]: args.append("-" + key)
3883 args.append(index1)
3884 if index2:
3885 args.append(index2)
3886 self.tk.call(self._w, "dump", *args)
3887 return result
3888 finally:
3889 if func_name:
3890 self.deletecommand(func_name)
3891
3892 ## new in tk8.4
3893 def edit(self, *args):
3894 """Internal method
3895
3896 This method controls the undo mechanism and
3897 the modified flag. The exact behavior of the
3898 command depends on the option argument that
3899 follows the edit argument. The following forms
3900 of the command are currently supported:
3901
3902 edit_modified, edit_redo, edit_reset, edit_separator
3903 and edit_undo
3904
3905 """
3906 return self.tk.call(self._w, 'edit', *args)
3907
3908 def edit_modified(self, arg=None):
3909 """Get or Set the modified flag
3910
3911 If arg is not specified, returns the modified
3912 flag of the widget. The insert, delete, edit undo and
3913 edit redo commands or the user can set or clear the
3914 modified flag. If boolean is specified, sets the
3915 modified flag of the widget to arg.
3916 """
3917 return self.edit("modified", arg)
3918
3919 def edit_redo(self):
3920 """Redo the last undone edit
3921
3922 When the undo option is true, reapplies the last
3923 undone edits provided no other edits were done since
3924 then. Generates an error when the redo stack is empty.
3925 Does nothing when the undo option is false.
3926 """
3927 return self.edit("redo")
3928
3929 def edit_reset(self):
3930 """Clears the undo and redo stacks
3931 """
3932 return self.edit("reset")
3933
3934 def edit_separator(self):
3935 """Inserts a separator (boundary) on the undo stack.
3936
3937 Does nothing when the undo option is false
3938 """
3939 return self.edit("separator")
3940
3941 def edit_undo(self):
3942 """Undoes the last edit action
3943
3944 If the undo option is true. An edit action is defined
3945 as all the insert and delete commands that are recorded
3946 on the undo stack in between two separators. Generates
3947 an error when the undo stack is empty. Does nothing
3948 when the undo option is false
3949 """
3950 return self.edit("undo")
3951
3952 def get(self, index1, index2=None):
3953 """Return the text from INDEX1 to INDEX2 (not included)."""
3954 return self.tk.call(self._w, 'get', index1, index2)
3955 # (Image commands are new in 8.0)
3956
3957 def image_cget(self, index, option):
3958 """Return the value of OPTION of an embedded image at INDEX."""
3959 if option[:1] != "-":
3960 option = "-" + option
3961 if option[-1:] == "_":
3962 option = option[:-1]
3963 return self.tk.call(self._w, "image", "cget", index, option)
3964
3965 def image_configure(self, index, cnf=None, **kw):
3966 """Query or modify the configuration options of an embedded image at INDEX.
3967
3968 Similar to configure() except that it applies to the specified
3969 embedded image.
3970 """
3971 return self._configure(('image', 'configure', index), cnf, kw)
3972
3973 def image_create(self, index, cnf={}, **kw):
3974 """Create an embedded image at INDEX."""
3975 return self.tk.call(
3976 self._w, "image", "create", index,
3977 *self._options(cnf, kw))
3978
3979 def image_names(self):
3980 """Return all names of embedded images in this widget."""
3981 return self.tk.call(self._w, "image", "names")
3982
3983 def index(self, index):
3984 """Return the index in the form line.char for INDEX."""
3985 return str(self.tk.call(self._w, 'index', index))
3986
3987 def insert(self, index, chars, *args):
3988 """Insert CHARS before the characters at INDEX. An additional
3989 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3990 self.tk.call((self._w, 'insert', index, chars) + args)
3991
3992 def mark_gravity(self, markName, direction=None):
3993 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3994 Return the current value if None is given for DIRECTION."""
3995 return self.tk.call(
3996 (self._w, 'mark', 'gravity', markName, direction))
3997
3998 def mark_names(self):
3999 """Return all mark names."""
4000 return self.tk.splitlist(self.tk.call(
4001 self._w, 'mark', 'names'))
4002
4003 def mark_set(self, markName, index):
4004 """Set mark MARKNAME before the character at INDEX."""
4005 self.tk.call(self._w, 'mark', 'set', markName, index)
4006
4007 def mark_unset(self, *markNames):
4008 """Delete all marks in MARKNAMES."""
4009 self.tk.call((self._w, 'mark', 'unset') + markNames)
4010
4011 def mark_next(self, index):
4012 """Return the name of the next mark after INDEX."""
4013 return self.tk.call(self._w, 'mark', 'next', index) or None
4014
4015 def mark_previous(self, index):
4016 """Return the name of the previous mark before INDEX."""
4017 return self.tk.call(self._w, 'mark', 'previous', index) or None
4018
4019 def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
4020 """Creates a peer text widget with the given newPathName, and any
4021 optional standard configuration options. By default the peer will
4022 have the same start and end line as the parent widget, but
4023 these can be overridden with the standard configuration options."""
4024 self.tk.call(self._w, 'peer', 'create', newPathName,
4025 *self._options(cnf, kw))
4026
4027 def peer_names(self): # new in Tk 8.5
4028 """Returns a list of peers of this widget (this does not include
4029 the widget itself)."""
4030 return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
4031
4032 def replace(self, index1, index2, chars, *args): # new in Tk 8.5
4033 """Replaces the range of characters between index1 and index2 with
4034 the given characters and tags specified by args.
4035
4036 See the method insert for some more information about args, and the
4037 method delete for information about the indices."""
4038 self.tk.call(self._w, 'replace', index1, index2, chars, *args)
4039
4040 def scan_mark(self, x, y):
4041 """Remember the current X, Y coordinates."""
4042 self.tk.call(self._w, 'scan', 'mark', x, y)
4043
4044 def scan_dragto(self, x, y):
4045 """Adjust the view of the text to 10 times the
4046 difference between X and Y and the coordinates given in
4047 scan_mark."""
4048 self.tk.call(self._w, 'scan', 'dragto', x, y)
4049
4050 def search(self, pattern, index, stopindex=None,
4051 forwards=None, backwards=None, exact=None,
4052 regexp=None, nocase=None, count=None, elide=None):
4053 """Search PATTERN beginning from INDEX until STOPINDEX.
4054 Return the index of the first character of a match or an
4055 empty string."""
4056 args = [self._w, 'search']
4057 if forwards: args.append('-forwards')
4058 if backwards: args.append('-backwards')
4059 if exact: args.append('-exact')
4060 if regexp: args.append('-regexp')
4061 if nocase: args.append('-nocase')
4062 if elide: args.append('-elide')
4063 if count: args.append('-count'); args.append(count)
4064 if pattern and pattern[0] == '-': args.append('--')
4065 args.append(pattern)
4066 args.append(index)
4067 if stopindex: args.append(stopindex)
4068 return str(self.tk.call(tuple(args)))
4069
4070 def see(self, index):
4071 """Scroll such that the character at INDEX is visible."""
4072 self.tk.call(self._w, 'see', index)
4073
4074 def tag_add(self, tagName, index1, *args):
4075 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
4076 Additional pairs of indices may follow in ARGS."""
4077 self.tk.call(
4078 (self._w, 'tag', 'add', tagName, index1) + args)
4079
4080 def tag_unbind(self, tagName, sequence, funcid=None):
4081 """Unbind for all characters with TAGNAME for event SEQUENCE the
4082 function identified with FUNCID."""
4083 return self._unbind((self._w, 'tag', 'bind', tagName, sequence), funcid)
4084
4085 def tag_bind(self, tagName, sequence, func, add=None):
4086 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
4087
4088 An additional boolean parameter ADD specifies whether FUNC will be
4089 called additionally to the other bound function or whether it will
4090 replace the previous function. See bind for the return value."""
4091 return self._bind((self._w, 'tag', 'bind', tagName),
4092 sequence, func, add)
4093
4094 def _tag_bind(self, tagName, sequence=None, func=None, add=None):
4095 # For tests only
4096 return self._bind((self._w, 'tag', 'bind', tagName),
4097 sequence, func, add)
4098
4099 def tag_cget(self, tagName, option):
4100 """Return the value of OPTION for tag TAGNAME."""
4101 if option[:1] != '-':
4102 option = '-' + option
4103 if option[-1:] == '_':
4104 option = option[:-1]
4105 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
4106
4107 def tag_configure(self, tagName, cnf=None, **kw):
4108 """Query or modify the configuration options of a tag TAGNAME.
4109
4110 Similar to configure() except that it applies to the specified tag.
4111 """
4112 return self._configure(('tag', 'configure', tagName), cnf, kw)
4113
4114 tag_config = tag_configure
4115
4116 def tag_delete(self, *tagNames):
4117 """Delete all tags in TAGNAMES."""
4118 self.tk.call((self._w, 'tag', 'delete') + tagNames)
4119
4120 def tag_lower(self, tagName, belowThis=None):
4121 """Change the priority of tag TAGNAME such that it is lower
4122 than the priority of BELOWTHIS."""
4123 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
4124
4125 def tag_names(self, index=None):
4126 """Return a list of all tag names."""
4127 return self.tk.splitlist(
4128 self.tk.call(self._w, 'tag', 'names', index))
4129
4130 def tag_nextrange(self, tagName, index1, index2=None):
4131 """Return a list of start and end index for the first sequence of
4132 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
4133 The text is searched forward from INDEX1."""
4134 return self.tk.splitlist(self.tk.call(
4135 self._w, 'tag', 'nextrange', tagName, index1, index2))
4136
4137 def tag_prevrange(self, tagName, index1, index2=None):
4138 """Return a list of start and end index for the first sequence of
4139 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
4140 The text is searched backwards from INDEX1."""
4141 return self.tk.splitlist(self.tk.call(
4142 self._w, 'tag', 'prevrange', tagName, index1, index2))
4143
4144 def tag_raise(self, tagName, aboveThis=None):
4145 """Change the priority of tag TAGNAME such that it is higher
4146 than the priority of ABOVETHIS."""
4147 self.tk.call(
4148 self._w, 'tag', 'raise', tagName, aboveThis)
4149
4150 def tag_ranges(self, tagName):
4151 """Return a list of ranges of text which have tag TAGNAME."""
4152 return self.tk.splitlist(self.tk.call(
4153 self._w, 'tag', 'ranges', tagName))
4154
4155 def tag_remove(self, tagName, index1, index2=None):
4156 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
4157 self.tk.call(
4158 self._w, 'tag', 'remove', tagName, index1, index2)
4159
4160 def window_cget(self, index, option):
4161 """Return the value of OPTION of an embedded window at INDEX."""
4162 if option[:1] != '-':
4163 option = '-' + option
4164 if option[-1:] == '_':
4165 option = option[:-1]
4166 return self.tk.call(self._w, 'window', 'cget', index, option)
4167
4168 def window_configure(self, index, cnf=None, **kw):
4169 """Query or modify the configuration options of an embedded window at INDEX.
4170
4171 Similar to configure() except that it applies to the specified
4172 embedded window.
4173 """
4174 return self._configure(('window', 'configure', index), cnf, kw)
4175
4176 window_config = window_configure
4177
4178 def window_create(self, index, cnf={}, **kw):
4179 """Create a window at INDEX."""
4180 self.tk.call(
4181 (self._w, 'window', 'create', index)
4182 + self._options(cnf, kw))
4183
4184 def window_names(self):
4185 """Return all names of embedded windows in this widget."""
4186 return self.tk.splitlist(
4187 self.tk.call(self._w, 'window', 'names'))
4188
4189 def yview_pickplace(self, *what):
4190 """Obsolete function, use see."""
4191 self.tk.call((self._w, 'yview', '-pickplace') + what)
4192
4193
4194 class _setit:
4195 """Internal class. It wraps the command in the widget OptionMenu."""
4196
4197 def __init__(self, var, value, callback=None):
4198 self.__value = value
4199 self.__var = var
4200 self.__callback = callback
4201
4202 def __call__(self, *args):
4203 self.__var.set(self.__value)
4204 if self.__callback is not None:
4205 self.__callback(self.__value, *args)
4206
4207
4208 class OptionMenu(Menubutton):
4209 """OptionMenu which allows the user to select a value from a menu."""
4210
4211 def __init__(self, master, variable, value, *values, **kwargs):
4212 """Construct an optionmenu widget with the parent MASTER, with
4213 the option textvariable set to VARIABLE, the initially selected
4214 value VALUE, the other menu values VALUES and an additional
4215 keyword argument command."""
4216 kw = {"borderwidth": 2, "textvariable": variable,
4217 "indicatoron": 1, "relief": RAISED, "anchor": "c",
4218 "highlightthickness": 2}
4219 Widget.__init__(self, master, "menubutton", kw)
4220 self.widgetName = 'tk_optionMenu'
4221 menu = self.__menu = Menu(self, name="menu", tearoff=0)
4222 self.menuname = menu._w
4223 # 'command' is the only supported keyword
4224 callback = kwargs.get('command')
4225 if 'command' in kwargs:
4226 del kwargs['command']
4227 if kwargs:
4228 raise TclError('unknown option -'+next(iter(kwargs)))
4229 menu.add_command(label=value,
4230 command=_setit(variable, value, callback))
4231 for v in values:
4232 menu.add_command(label=v,
4233 command=_setit(variable, v, callback))
4234 self["menu"] = menu
4235
4236 def __getitem__(self, name):
4237 if name == 'menu':
4238 return self.__menu
4239 return Widget.__getitem__(self, name)
4240
4241 def destroy(self):
4242 """Destroy this widget and the associated menu."""
4243 Menubutton.destroy(self)
4244 self.__menu = None
4245
4246
4247 class Image:
4248 """Base class for images."""
4249 _last_id = 0
4250
4251 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
4252 self.name = None
4253 if master is None:
4254 master = _get_default_root('create image')
4255 self.tk = getattr(master, 'tk', master)
4256 if not name:
4257 Image._last_id += 1
4258 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
4259 if kw and cnf: cnf = _cnfmerge((cnf, kw))
4260 elif kw: cnf = kw
4261 options = ()
4262 for k, v in cnf.items():
4263 options = options + ('-'+k, v)
4264 self.tk.call(('image', 'create', imgtype, name,) + options)
4265 self.name = name
4266
4267 def __str__(self): return self.name
4268
4269 def __del__(self):
4270 if self.name:
4271 try:
4272 self.tk.call('image', 'delete', self.name)
4273 except TclError:
4274 # May happen if the root was destroyed
4275 pass
4276
4277 def __setitem__(self, key, value):
4278 self.tk.call(self.name, 'configure', '-'+key, value)
4279
4280 def __getitem__(self, key):
4281 return self.tk.call(self.name, 'configure', '-'+key)
4282
4283 def configure(self, **kw):
4284 """Configure the image."""
4285 res = ()
4286 for k, v in _cnfmerge(kw).items():
4287 if v is not None:
4288 if k[-1] == '_': k = k[:-1]
4289 res = res + ('-'+k, v)
4290 self.tk.call((self.name, 'config') + res)
4291
4292 config = configure
4293
4294 def height(self):
4295 """Return the height of the image."""
4296 return self.tk.getint(
4297 self.tk.call('image', 'height', self.name))
4298
4299 def type(self):
4300 """Return the type of the image, e.g. "photo" or "bitmap"."""
4301 return self.tk.call('image', 'type', self.name)
4302
4303 def width(self):
4304 """Return the width of the image."""
4305 return self.tk.getint(
4306 self.tk.call('image', 'width', self.name))
4307
4308
4309 class PhotoImage(Image):
4310 """Widget which can display images in PGM, PPM, GIF, PNG format."""
4311
4312 def __init__(self, name=None, cnf={}, master=None, **kw):
4313 """Create an image with NAME.
4314
4315 Valid option names: data, format, file, gamma, height, palette,
4316 width."""
4317 Image.__init__(self, 'photo', name, cnf, master, **kw)
4318
4319 def blank(self):
4320 """Display a transparent image."""
4321 self.tk.call(self.name, 'blank')
4322
4323 def cget(self, option):
4324 """Return the value of OPTION."""
4325 return self.tk.call(self.name, 'cget', '-' + option)
4326 # XXX config
4327
4328 def __getitem__(self, key):
4329 return self.tk.call(self.name, 'cget', '-' + key)
4330
4331 def copy(self, *, from_coords=None, zoom=None, subsample=None):
4332 """Return a new PhotoImage with the same image as this widget.
4333
4334 The FROM_COORDS option specifies a rectangular sub-region of the
4335 source image to be copied. It must be a tuple or a list of 1 to 4
4336 integers (x1, y1, x2, y2). (x1, y1) and (x2, y2) specify diagonally
4337 opposite corners of the rectangle. If x2 and y2 are not specified,
4338 the default value is the bottom-right corner of the source image.
4339 The pixels copied will include the left and top edges of the
4340 specified rectangle but not the bottom or right edges. If the
4341 FROM_COORDS option is not given, the default is the whole source
4342 image.
4343
4344 If SUBSAMPLE or ZOOM are specified, the image is transformed as in
4345 the subsample() or zoom() methods. The value must be a single
4346 integer or a pair of integers.
4347 """
4348 destImage = PhotoImage(master=self.tk)
4349 destImage.copy_replace(self, from_coords=from_coords,
4350 zoom=zoom, subsample=subsample)
4351 return destImage
4352
4353 def zoom(self, x, y='', *, from_coords=None):
4354 """Return a new PhotoImage with the same image as this widget
4355 but zoom it with a factor of X in the X direction and Y in the Y
4356 direction. If Y is not given, the default value is the same as X.
4357
4358 The FROM_COORDS option specifies a rectangular sub-region of the
4359 source image to be copied, as in the copy() method.
4360 """
4361 if y=='': y=x
4362 return self.copy(zoom=(x, y), from_coords=from_coords)
4363
4364 def subsample(self, x, y='', *, from_coords=None):
4365 """Return a new PhotoImage based on the same image as this widget
4366 but use only every Xth or Yth pixel. If Y is not given, the
4367 default value is the same as X.
4368
4369 The FROM_COORDS option specifies a rectangular sub-region of the
4370 source image to be copied, as in the copy() method.
4371 """
4372 if y=='': y=x
4373 return self.copy(subsample=(x, y), from_coords=from_coords)
4374
4375 def copy_replace(self, sourceImage, *, from_coords=None, to=None, shrink=False,
4376 zoom=None, subsample=None, compositingrule=None):
4377 """Copy a region from the source image (which must be a PhotoImage) to
4378 this image, possibly with pixel zooming and/or subsampling. If no
4379 options are specified, this command copies the whole of the source
4380 image into this image, starting at coordinates (0, 0).
4381
4382 The FROM_COORDS option specifies a rectangular sub-region of the
4383 source image to be copied. It must be a tuple or a list of 1 to 4
4384 integers (x1, y1, x2, y2). (x1, y1) and (x2, y2) specify diagonally
4385 opposite corners of the rectangle. If x2 and y2 are not specified,
4386 the default value is the bottom-right corner of the source image.
4387 The pixels copied will include the left and top edges of the
4388 specified rectangle but not the bottom or right edges. If the
4389 FROM_COORDS option is not given, the default is the whole source
4390 image.
4391
4392 The TO option specifies a rectangular sub-region of the destination
4393 image to be affected. It must be a tuple or a list of 1 to 4
4394 integers (x1, y1, x2, y2). (x1, y1) and (x2, y2) specify diagonally
4395 opposite corners of the rectangle. If x2 and y2 are not specified,
4396 the default value is (x1,y1) plus the size of the source region
4397 (after subsampling and zooming, if specified). If x2 and y2 are
4398 specified, the source region will be replicated if necessary to fill
4399 the destination region in a tiled fashion.
4400
4401 If SHRINK is true, the size of the destination image should be
4402 reduced, if necessary, so that the region being copied into is at
4403 the bottom-right corner of the image.
4404
4405 If SUBSAMPLE or ZOOM are specified, the image is transformed as in
4406 the subsample() or zoom() methods. The value must be a single
4407 integer or a pair of integers.
4408
4409 The COMPOSITINGRULE option specifies how transparent pixels in the
4410 source image are combined with the destination image. When a
4411 compositing rule of 'overlay' is set, the old contents of the
4412 destination image are visible, as if the source image were printed
4413 on a piece of transparent film and placed over the top of the
4414 destination. When a compositing rule of 'set' is set, the old
4415 contents of the destination image are discarded and the source image
4416 is used as-is. The default compositing rule is 'overlay'.
4417 """
4418 options = []
4419 if from_coords is not None:
4420 options.extend(('-from', *from_coords))
4421 if to is not None:
4422 options.extend(('-to', *to))
4423 if shrink:
4424 options.append('-shrink')
4425 if zoom is not None:
4426 if not isinstance(zoom, (tuple, list)):
4427 zoom = (zoom,)
4428 options.extend(('-zoom', *zoom))
4429 if subsample is not None:
4430 if not isinstance(subsample, (tuple, list)):
4431 subsample = (subsample,)
4432 options.extend(('-subsample', *subsample))
4433 if compositingrule:
4434 options.extend(('-compositingrule', compositingrule))
4435 self.tk.call(self.name, 'copy', sourceImage, *options)
4436
4437 def get(self, x, y):
4438 """Return the color (red, green, blue) of the pixel at X,Y."""
4439 return self.tk.call(self.name, 'get', x, y)
4440
4441 def put(self, data, to=None):
4442 """Put row formatted colors to image starting from
4443 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
4444 args = (self.name, 'put', data)
4445 if to:
4446 if to[0] == '-to':
4447 to = to[1:]
4448 args = args + ('-to',) + tuple(to)
4449 self.tk.call(args)
4450
4451 def read(self, filename, format=None, *, from_coords=None, to=None, shrink=False):
4452 """Reads image data from the file named FILENAME into the image.
4453
4454 The FORMAT option specifies the format of the image data in the
4455 file.
4456
4457 The FROM_COORDS option specifies a rectangular sub-region of the image
4458 file data to be copied to the destination image. It must be a tuple
4459 or a list of 1 to 4 integers (x1, y1, x2, y2). (x1, y1) and
4460 (x2, y2) specify diagonally opposite corners of the rectangle. If
4461 x2 and y2 are not specified, the default value is the bottom-right
4462 corner of the source image. The default, if this option is not
4463 specified, is the whole of the image in the image file.
4464
4465 The TO option specifies the coordinates of the top-left corner of
4466 the region of the image into which data from filename are to be
4467 read. The default is (0, 0).
4468
4469 If SHRINK is true, the size of the destination image will be
4470 reduced, if necessary, so that the region into which the image file
4471 data are read is at the bottom-right corner of the image.
4472 """
4473 options = ()
4474 if format is not None:
4475 options += ('-format', format)
4476 if from_coords is not None:
4477 options += ('-from', *from_coords)
4478 if shrink:
4479 options += ('-shrink',)
4480 if to is not None:
4481 options += ('-to', *to)
4482 self.tk.call(self.name, 'read', filename, *options)
4483
4484 def write(self, filename, format=None, from_coords=None, *,
4485 background=None, grayscale=False):
4486 """Writes image data from the image to a file named FILENAME.
4487
4488 The FORMAT option specifies the name of the image file format
4489 handler to be used to write the data to the file. If this option
4490 is not given, the format is guessed from the file extension.
4491
4492 The FROM_COORDS option specifies a rectangular region of the image
4493 to be written to the image file. It must be a tuple or a list of 1
4494 to 4 integers (x1, y1, x2, y2). If only x1 and y1 are specified,
4495 the region extends from (x1,y1) to the bottom-right corner of the
4496 image. If all four coordinates are given, they specify diagonally
4497 opposite corners of the rectangular region. The default, if this
4498 option is not given, is the whole image.
4499
4500 If BACKGROUND is specified, the data will not contain any
4501 transparency information. In all transparent pixels the color will
4502 be replaced by the specified color.
4503
4504 If GRAYSCALE is true, the data will not contain color information.
4505 All pixel data will be transformed into grayscale.
4506 """
4507 options = ()
4508 if format is not None:
4509 options += ('-format', format)
4510 if from_coords is not None:
4511 options += ('-from', *from_coords)
4512 if grayscale:
4513 options += ('-grayscale',)
4514 if background is not None:
4515 options += ('-background', background)
4516 self.tk.call(self.name, 'write', filename, *options)
4517
4518 def data(self, format=None, *, from_coords=None,
4519 background=None, grayscale=False):
4520 """Returns image data.
4521
4522 The FORMAT option specifies the name of the image file format
4523 handler to be used. If this option is not given, this method uses
4524 a format that consists of a tuple (one element per row) of strings
4525 containings space separated (one element per pixel/column) colors
4526 in “#RRGGBB” format (where RR is a pair of hexadecimal digits for
4527 the red channel, GG for green, and BB for blue).
4528
4529 The FROM_COORDS option specifies a rectangular region of the image
4530 to be returned. It must be a tuple or a list of 1 to 4 integers
4531 (x1, y1, x2, y2). If only x1 and y1 are specified, the region
4532 extends from (x1,y1) to the bottom-right corner of the image. If
4533 all four coordinates are given, they specify diagonally opposite
4534 corners of the rectangular region, including (x1, y1) and excluding
4535 (x2, y2). The default, if this option is not given, is the whole
4536 image.
4537
4538 If BACKGROUND is specified, the data will not contain any
4539 transparency information. In all transparent pixels the color will
4540 be replaced by the specified color.
4541
4542 If GRAYSCALE is true, the data will not contain color information.
4543 All pixel data will be transformed into grayscale.
4544 """
4545 options = ()
4546 if format is not None:
4547 options += ('-format', format)
4548 if from_coords is not None:
4549 options += ('-from', *from_coords)
4550 if grayscale:
4551 options += ('-grayscale',)
4552 if background is not None:
4553 options += ('-background', background)
4554 data = self.tk.call(self.name, 'data', *options)
4555 if isinstance(data, str): # For wantobjects = 0.
4556 if format is None:
4557 data = self.tk.splitlist(data)
4558 else:
4559 data = bytes(data, 'latin1')
4560 return data
4561
4562 def transparency_get(self, x, y):
4563 """Return True if the pixel at x,y is transparent."""
4564 return self.tk.getboolean(self.tk.call(
4565 self.name, 'transparency', 'get', x, y))
4566
4567 def transparency_set(self, x, y, boolean):
4568 """Set the transparency of the pixel at x,y."""
4569 self.tk.call(self.name, 'transparency', 'set', x, y, boolean)
4570
4571
4572 class BitmapImage(Image):
4573 """Widget which can display images in XBM format."""
4574
4575 def __init__(self, name=None, cnf={}, master=None, **kw):
4576 """Create a bitmap with NAME.
4577
4578 Valid option names: background, data, file, foreground, maskdata, maskfile."""
4579 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
4580
4581
4582 def image_names():
4583 tk = _get_default_root('use image_names()').tk
4584 return tk.splitlist(tk.call('image', 'names'))
4585
4586
4587 def image_types():
4588 tk = _get_default_root('use image_types()').tk
4589 return tk.splitlist(tk.call('image', 'types'))
4590
4591
4592 class Spinbox(Widget, XView):
4593 """spinbox widget."""
4594
4595 def __init__(self, master=None, cnf={}, **kw):
4596 """Construct a spinbox widget with the parent MASTER.
4597
4598 STANDARD OPTIONS
4599
4600 activebackground, background, borderwidth,
4601 cursor, exportselection, font, foreground,
4602 highlightbackground, highlightcolor,
4603 highlightthickness, insertbackground,
4604 insertborderwidth, insertofftime,
4605 insertontime, insertwidth, justify, relief,
4606 repeatdelay, repeatinterval,
4607 selectbackground, selectborderwidth
4608 selectforeground, takefocus, textvariable
4609 xscrollcommand.
4610
4611 WIDGET-SPECIFIC OPTIONS
4612
4613 buttonbackground, buttoncursor,
4614 buttondownrelief, buttonuprelief,
4615 command, disabledbackground,
4616 disabledforeground, format, from,
4617 invalidcommand, increment,
4618 readonlybackground, state, to,
4619 validate, validatecommand values,
4620 width, wrap,
4621 """
4622 Widget.__init__(self, master, 'spinbox', cnf, kw)
4623
4624 def bbox(self, index):
4625 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
4626 rectangle which encloses the character given by index.
4627
4628 The first two elements of the list give the x and y
4629 coordinates of the upper-left corner of the screen
4630 area covered by the character (in pixels relative
4631 to the widget) and the last two elements give the
4632 width and height of the character, in pixels. The
4633 bounding box may refer to a region outside the
4634 visible area of the window.
4635 """
4636 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
4637
4638 def delete(self, first, last=None):
4639 """Delete one or more elements of the spinbox.
4640
4641 First is the index of the first character to delete,
4642 and last is the index of the character just after
4643 the last one to delete. If last isn't specified it
4644 defaults to first+1, i.e. a single character is
4645 deleted. This command returns an empty string.
4646 """
4647 return self.tk.call(self._w, 'delete', first, last)
4648
4649 def get(self):
4650 """Returns the spinbox's string"""
4651 return self.tk.call(self._w, 'get')
4652
4653 def icursor(self, index):
4654 """Alter the position of the insertion cursor.
4655
4656 The insertion cursor will be displayed just before
4657 the character given by index. Returns an empty string
4658 """
4659 return self.tk.call(self._w, 'icursor', index)
4660
4661 def identify(self, x, y):
4662 """Returns the name of the widget at position x, y
4663
4664 Return value is one of: none, buttondown, buttonup, entry
4665 """
4666 return self.tk.call(self._w, 'identify', x, y)
4667
4668 def index(self, index):
4669 """Returns the numerical index corresponding to index
4670 """
4671 return self.tk.call(self._w, 'index', index)
4672
4673 def insert(self, index, s):
4674 """Insert string s at index
4675
4676 Returns an empty string.
4677 """
4678 return self.tk.call(self._w, 'insert', index, s)
4679
4680 def invoke(self, element):
4681 """Causes the specified element to be invoked
4682
4683 The element could be buttondown or buttonup
4684 triggering the action associated with it.
4685 """
4686 return self.tk.call(self._w, 'invoke', element)
4687
4688 def scan(self, *args):
4689 """Internal function."""
4690 return self._getints(
4691 self.tk.call((self._w, 'scan') + args)) or ()
4692
4693 def scan_mark(self, x):
4694 """Records x and the current view in the spinbox window;
4695
4696 used in conjunction with later scan dragto commands.
4697 Typically this command is associated with a mouse button
4698 press in the widget. It returns an empty string.
4699 """
4700 return self.scan("mark", x)
4701
4702 def scan_dragto(self, x):
4703 """Compute the difference between the given x argument
4704 and the x argument to the last scan mark command
4705
4706 It then adjusts the view left or right by 10 times the
4707 difference in x-coordinates. This command is typically
4708 associated with mouse motion events in the widget, to
4709 produce the effect of dragging the spinbox at high speed
4710 through the window. The return value is an empty string.
4711 """
4712 return self.scan("dragto", x)
4713
4714 def selection(self, *args):
4715 """Internal function."""
4716 return self._getints(
4717 self.tk.call((self._w, 'selection') + args)) or ()
4718
4719 def selection_adjust(self, index):
4720 """Locate the end of the selection nearest to the character
4721 given by index,
4722
4723 Then adjust that end of the selection to be at index
4724 (i.e including but not going beyond index). The other
4725 end of the selection is made the anchor point for future
4726 select to commands. If the selection isn't currently in
4727 the spinbox, then a new selection is created to include
4728 the characters between index and the most recent selection
4729 anchor point, inclusive.
4730 """
4731 return self.selection("adjust", index)
4732
4733 def selection_clear(self):
4734 """Clear the selection
4735
4736 If the selection isn't in this widget then the
4737 command has no effect.
4738 """
4739 return self.selection("clear")
4740
4741 def selection_element(self, element=None):
4742 """Sets or gets the currently selected element.
4743
4744 If a spinbutton element is specified, it will be
4745 displayed depressed.
4746 """
4747 return self.tk.call(self._w, 'selection', 'element', element)
4748
4749 def selection_from(self, index):
4750 """Set the fixed end of a selection to INDEX."""
4751 self.selection('from', index)
4752
4753 def selection_present(self):
4754 """Return True if there are characters selected in the spinbox, False
4755 otherwise."""
4756 return self.tk.getboolean(
4757 self.tk.call(self._w, 'selection', 'present'))
4758
4759 def selection_range(self, start, end):
4760 """Set the selection from START to END (not included)."""
4761 self.selection('range', start, end)
4762
4763 def selection_to(self, index):
4764 """Set the variable end of a selection to INDEX."""
4765 self.selection('to', index)
4766
4767 ###########################################################################
4768
4769
4770 class LabelFrame(Widget):
4771 """labelframe widget."""
4772
4773 def __init__(self, master=None, cnf={}, **kw):
4774 """Construct a labelframe widget with the parent MASTER.
4775
4776 STANDARD OPTIONS
4777
4778 borderwidth, cursor, font, foreground,
4779 highlightbackground, highlightcolor,
4780 highlightthickness, padx, pady, relief,
4781 takefocus, text
4782
4783 WIDGET-SPECIFIC OPTIONS
4784
4785 background, class, colormap, container,
4786 height, labelanchor, labelwidget,
4787 visual, width
4788 """
4789 Widget.__init__(self, master, 'labelframe', cnf, kw)
4790
4791 ########################################################################
4792
4793
4794 class PanedWindow(Widget):
4795 """panedwindow widget."""
4796
4797 def __init__(self, master=None, cnf={}, **kw):
4798 """Construct a panedwindow widget with the parent MASTER.
4799
4800 STANDARD OPTIONS
4801
4802 background, borderwidth, cursor, height,
4803 orient, relief, width
4804
4805 WIDGET-SPECIFIC OPTIONS
4806
4807 handlepad, handlesize, opaqueresize,
4808 sashcursor, sashpad, sashrelief,
4809 sashwidth, showhandle,
4810 """
4811 Widget.__init__(self, master, 'panedwindow', cnf, kw)
4812
4813 def add(self, child, **kw):
4814 """Add a child widget to the panedwindow in a new pane.
4815
4816 The child argument is the name of the child widget
4817 followed by pairs of arguments that specify how to
4818 manage the windows. The possible options and values
4819 are the ones accepted by the paneconfigure method.
4820 """
4821 self.tk.call((self._w, 'add', child) + self._options(kw))
4822
4823 def remove(self, child):
4824 """Remove the pane containing child from the panedwindow
4825
4826 All geometry management options for child will be forgotten.
4827 """
4828 self.tk.call(self._w, 'forget', child)
4829
4830 forget = remove
4831
4832 def identify(self, x, y):
4833 """Identify the panedwindow component at point x, y
4834
4835 If the point is over a sash or a sash handle, the result
4836 is a two element list containing the index of the sash or
4837 handle, and a word indicating whether it is over a sash
4838 or a handle, such as {0 sash} or {2 handle}. If the point
4839 is over any other part of the panedwindow, the result is
4840 an empty list.
4841 """
4842 return self.tk.call(self._w, 'identify', x, y)
4843
4844 def proxy(self, *args):
4845 """Internal function."""
4846 return self._getints(
4847 self.tk.call((self._w, 'proxy') + args)) or ()
4848
4849 def proxy_coord(self):
4850 """Return the x and y pair of the most recent proxy location
4851 """
4852 return self.proxy("coord")
4853
4854 def proxy_forget(self):
4855 """Remove the proxy from the display.
4856 """
4857 return self.proxy("forget")
4858
4859 def proxy_place(self, x, y):
4860 """Place the proxy at the given x and y coordinates.
4861 """
4862 return self.proxy("place", x, y)
4863
4864 def sash(self, *args):
4865 """Internal function."""
4866 return self._getints(
4867 self.tk.call((self._w, 'sash') + args)) or ()
4868
4869 def sash_coord(self, index):
4870 """Return the current x and y pair for the sash given by index.
4871
4872 Index must be an integer between 0 and 1 less than the
4873 number of panes in the panedwindow. The coordinates given are
4874 those of the top left corner of the region containing the sash.
4875 pathName sash dragto index x y This command computes the
4876 difference between the given coordinates and the coordinates
4877 given to the last sash coord command for the given sash. It then
4878 moves that sash the computed difference. The return value is the
4879 empty string.
4880 """
4881 return self.sash("coord", index)
4882
4883 def sash_mark(self, index):
4884 """Records x and y for the sash given by index;
4885
4886 Used in conjunction with later dragto commands to move the sash.
4887 """
4888 return self.sash("mark", index)
4889
4890 def sash_place(self, index, x, y):
4891 """Place the sash given by index at the given coordinates
4892 """
4893 return self.sash("place", index, x, y)
4894
4895 def panecget(self, child, option):
4896 """Return the value of option for a child window."""
4897 return self.tk.call(
4898 (self._w, 'panecget') + (child, '-'+option))
4899
4900 def paneconfigure(self, tagOrId, cnf=None, **kw):
4901 """Query or modify the configuration options for a child window.
4902
4903 Similar to configure() except that it applies to the specified
4904 window.
4905
4906 The following options are supported:
4907
4908 after window
4909 Insert the window after the window specified. window
4910 should be the name of a window already managed by pathName.
4911 before window
4912 Insert the window before the window specified. window
4913 should be the name of a window already managed by pathName.
4914 height size
4915 Specify a height for the window. The height will be the
4916 outer dimension of the window including its border, if
4917 any. If size is an empty string, or if -height is not
4918 specified, then the height requested internally by the
4919 window will be used initially; the height may later be
4920 adjusted by the movement of sashes in the panedwindow.
4921 Size may be any value accepted by Tk_GetPixels.
4922 minsize n
4923 Specifies that the size of the window cannot be made
4924 less than n. This constraint only affects the size of
4925 the widget in the paned dimension -- the x dimension
4926 for horizontal panedwindows, the y dimension for
4927 vertical panedwindows. May be any value accepted by
4928 Tk_GetPixels.
4929 padx n
4930 Specifies a non-negative value indicating how much
4931 extra space to leave on each side of the window in
4932 the X-direction. The value may have any of the forms
4933 accepted by Tk_GetPixels.
4934 pady n
4935 Specifies a non-negative value indicating how much
4936 extra space to leave on each side of the window in
4937 the Y-direction. The value may have any of the forms
4938 accepted by Tk_GetPixels.
4939 sticky style
4940 If a window's pane is larger than the requested
4941 dimensions of the window, this option may be used
4942 to position (or stretch) the window within its pane.
4943 Style is a string that contains zero or more of the
4944 characters n, s, e or w. The string can optionally
4945 contains spaces or commas, but they are ignored. Each
4946 letter refers to a side (north, south, east, or west)
4947 that the window will "stick" to. If both n and s
4948 (or e and w) are specified, the window will be
4949 stretched to fill the entire height (or width) of
4950 its cavity.
4951 width size
4952 Specify a width for the window. The width will be
4953 the outer dimension of the window including its
4954 border, if any. If size is an empty string, or
4955 if -width is not specified, then the width requested
4956 internally by the window will be used initially; the
4957 width may later be adjusted by the movement of sashes
4958 in the panedwindow. Size may be any value accepted by
4959 Tk_GetPixels.
4960
4961 """
4962 if cnf is None and not kw:
4963 return self._getconfigure(self._w, 'paneconfigure', tagOrId)
4964 if isinstance(cnf, str) and not kw:
4965 return self._getconfigure1(
4966 self._w, 'paneconfigure', tagOrId, '-'+cnf)
4967 self.tk.call((self._w, 'paneconfigure', tagOrId) +
4968 self._options(cnf, kw))
4969
4970 paneconfig = paneconfigure
4971
4972 def panes(self):
4973 """Returns an ordered list of the child panes."""
4974 return self.tk.splitlist(self.tk.call(self._w, 'panes'))
4975
4976 # Test:
4977
4978
4979 def _test():
4980 root = Tk()
4981 text = "This is Tcl/Tk %s" % root.globalgetvar('tk_patchLevel')
4982 text += "\nThis should be a cedilla: \xe7"
4983 label = Label(root, text=text)
4984 label.pack()
4985 test = Button(root, text="Click me!",
4986 command=lambda root=root: root.test.configure(
4987 text="[%s]" % root.test['text']))
4988 test.pack()
4989 root.test = test
4990 quit = Button(root, text="QUIT", command=root.destroy)
4991 quit.pack()
4992 # The following three commands are needed so the window pops
4993 # up on top on Windows...
4994 root.iconify()
4995 root.update()
4996 root.deiconify()
4997 root.mainloop()
4998
4999
5000 __all__ = [name for name, obj in globals().items()
5001 if not name.startswith('_') and not isinstance(obj, types.ModuleType)
5002 and name not in {'wantobjects'}]
5003
5004 if __name__ == '__main__':
5005 _test()