Debian Codegraph @

Lib/tkinter/__init__.py

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