Debian Codegraph @

lib-python/3/tkinter/__init__.py

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