Debian Codegraph @

Lib/tkinter/__init__.py

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