Debian Codegraph @

lib-python/3/tkinter/__init__.py

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