Debian Codegraph @

Lib/tkinter/__init__.py

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