blob: f46642f5bb99db9d70970fb19c9520ffe4bc6005 [file] [log] [blame]
Georg Brandl33cece02008-05-20 06:58:21 +00001"""Wrapper functions for Tcl/Tk.
2
3Tkinter provides classes which allow the display, positioning and
4control of widgets. Toplevel widgets are Tk and Toplevel. Other
5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
6Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
7LabelFrame and PanedWindow.
8
9Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
11under Tk.
12
13Widgets are positioned with one of the geometry managers Place, Pack
14or Grid. These managers can be called with methods place, pack, grid
15available in every Widget.
16
17Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
19
20Example (Hello, World):
Georg Brandl6634bf22008-05-20 07:13:37 +000021import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
Georg Brandl33cece02008-05-20 06:58:21 +000025frame.pack(fill=BOTH,expand=1)
Georg Brandl6634bf22008-05-20 07:13:37 +000026label = Tkinter.Label(frame, text="Hello, World")
Georg Brandl33cece02008-05-20 06:58:21 +000027label.pack(fill=X, expand=1)
Georg Brandl6634bf22008-05-20 07:13:37 +000028button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
Georg Brandl33cece02008-05-20 06:58:21 +000029button.pack(side=BOTTOM)
30tk.mainloop()
31"""
32
Senthil Kumaran4af1c6a2011-07-28 22:30:27 +080033__version__ = "$Revision: 81008 $"
Georg Brandl33cece02008-05-20 06:58:21 +000034
35import sys
36if sys.platform == "win32":
37 # Attempt to configure Tcl/Tk without requiring PATH
Georg Brandl6634bf22008-05-20 07:13:37 +000038 import FixTk
Georg Brandl33cece02008-05-20 06:58:21 +000039import _tkinter # If this fails your Python may not be configured for Tk
Georg Brandl6634bf22008-05-20 07:13:37 +000040tkinter = _tkinter # b/w compat for export
Georg Brandl33cece02008-05-20 06:58:21 +000041TclError = _tkinter.TclError
42from types import *
Georg Brandl6634bf22008-05-20 07:13:37 +000043from Tkconstants import *
Serhiy Storchakae39ba042013-01-15 18:01:21 +020044import re
Georg Brandl33cece02008-05-20 06:58:21 +000045
46wantobjects = 1
47
48TkVersion = float(_tkinter.TK_VERSION)
49TclVersion = float(_tkinter.TCL_VERSION)
50
51READABLE = _tkinter.READABLE
52WRITABLE = _tkinter.WRITABLE
53EXCEPTION = _tkinter.EXCEPTION
54
55# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
56try: _tkinter.createfilehandler
57except AttributeError: _tkinter.createfilehandler = None
58try: _tkinter.deletefilehandler
59except AttributeError: _tkinter.deletefilehandler = None
60
61
Serhiy Storchakae39ba042013-01-15 18:01:21 +020062_magic_re = re.compile(r'([\\{}])')
63_space_re = re.compile(r'([\s])')
64
65def _join(value):
66 """Internal function."""
67 return ' '.join(map(_stringify, value))
68
69def _stringify(value):
70 """Internal function."""
71 if isinstance(value, (list, tuple)):
72 if len(value) == 1:
73 value = _stringify(value[0])
74 if value[0] == '{':
75 value = '{%s}' % value
76 else:
77 value = '{%s}' % _join(value)
78 else:
Serhiy Storchaka9be238d2014-01-07 19:32:58 +020079 if isinstance(value, str):
80 value = unicode(value, 'utf-8')
81 elif not isinstance(value, unicode):
Serhiy Storchakae39ba042013-01-15 18:01:21 +020082 value = str(value)
83 if not value:
84 value = '{}'
85 elif _magic_re.search(value):
86 # add '\' before special characters and spaces
87 value = _magic_re.sub(r'\\\1', value)
88 value = _space_re.sub(r'\\\1', value)
89 elif value[0] == '"' or _space_re.search(value):
90 value = '{%s}' % value
91 return value
92
Georg Brandl33cece02008-05-20 06:58:21 +000093def _flatten(tuple):
94 """Internal function."""
95 res = ()
96 for item in tuple:
97 if type(item) in (TupleType, ListType):
98 res = res + _flatten(item)
99 elif item is not None:
100 res = res + (item,)
101 return res
102
103try: _flatten = _tkinter._flatten
104except AttributeError: pass
105
106def _cnfmerge(cnfs):
107 """Internal function."""
108 if type(cnfs) is DictionaryType:
109 return cnfs
110 elif type(cnfs) in (NoneType, StringType):
111 return cnfs
112 else:
113 cnf = {}
114 for c in _flatten(cnfs):
115 try:
116 cnf.update(c)
117 except (AttributeError, TypeError), msg:
118 print "_cnfmerge: fallback due to:", msg
119 for k, v in c.items():
120 cnf[k] = v
121 return cnf
122
123try: _cnfmerge = _tkinter._cnfmerge
124except AttributeError: pass
125
Serhiy Storchakaceaf6822014-09-06 22:47:02 +0300126def _splitdict(tk, v, cut_minus=True, conv=None):
127 """Return a properly formatted dict built from Tcl list pairs.
128
129 If cut_minus is True, the supposed '-' prefix will be removed from
130 keys. If conv is specified, it is used to convert values.
131
132 Tcl list is expected to contain an even number of elements.
133 """
134 t = tk.splitlist(v)
135 if len(t) % 2:
136 raise RuntimeError('Tcl list representing a dict is expected '
137 'to contain an even number of elements')
138 it = iter(t)
139 dict = {}
140 for key, value in zip(it, it):
141 key = str(key)
142 if cut_minus and key[0] == '-':
143 key = key[1:]
144 if conv:
145 value = conv(value)
146 dict[key] = value
147 return dict
148
Georg Brandl33cece02008-05-20 06:58:21 +0000149class Event:
150 """Container for the properties of an event.
151
152 Instances of this type are generated if one of the following events occurs:
153
154 KeyPress, KeyRelease - for keyboard events
155 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
156 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
157 Colormap, Gravity, Reparent, Property, Destroy, Activate,
158 Deactivate - for window events.
159
160 If a callback function for one of these events is registered
161 using bind, bind_all, bind_class, or tag_bind, the callback is
162 called with an Event as first argument. It will have the
163 following attributes (in braces are the event types for which
164 the attribute is valid):
165
166 serial - serial number of event
167 num - mouse button pressed (ButtonPress, ButtonRelease)
168 focus - whether the window has the focus (Enter, Leave)
169 height - height of the exposed window (Configure, Expose)
170 width - width of the exposed window (Configure, Expose)
171 keycode - keycode of the pressed key (KeyPress, KeyRelease)
172 state - state of the event as a number (ButtonPress, ButtonRelease,
173 Enter, KeyPress, KeyRelease,
174 Leave, Motion)
175 state - state as a string (Visibility)
176 time - when the event occurred
177 x - x-position of the mouse
178 y - y-position of the mouse
179 x_root - x-position of the mouse on the screen
180 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
181 y_root - y-position of the mouse on the screen
182 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
183 char - pressed character (KeyPress, KeyRelease)
184 send_event - see X/Windows documentation
185 keysym - keysym of the event as a string (KeyPress, KeyRelease)
186 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
187 type - type of the event as a number
188 widget - widget in which the event occurred
189 delta - delta of wheel movement (MouseWheel)
190 """
191 pass
192
193_support_default_root = 1
194_default_root = None
195
196def NoDefaultRoot():
197 """Inhibit setting of default root window.
198
199 Call this function to inhibit that the first instance of
200 Tk is used for windows without an explicit parent window.
201 """
202 global _support_default_root
203 _support_default_root = 0
204 global _default_root
205 _default_root = None
206 del _default_root
207
208def _tkerror(err):
209 """Internal function."""
210 pass
211
Andrew Svetlov33b9b712012-12-10 00:05:08 +0200212def _exit(code=0):
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200213 """Internal function. Calling it will raise the exception SystemExit."""
Andrew Svetlov33b9b712012-12-10 00:05:08 +0200214 try:
215 code = int(code)
216 except ValueError:
217 pass
Georg Brandl33cece02008-05-20 06:58:21 +0000218 raise SystemExit, code
219
220_varnum = 0
221class Variable:
222 """Class to define value holders for e.g. buttons.
223
224 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
225 that constrain the type of the value returned from get()."""
226 _default = ""
Serhiy Storchaka44ae5132014-08-17 15:31:41 +0300227 _tclCommands = None
Georg Brandl33cece02008-05-20 06:58:21 +0000228 def __init__(self, master=None, value=None, name=None):
229 """Construct a variable
230
231 MASTER can be given as master widget.
232 VALUE is an optional value (defaults to "")
233 NAME is an optional Tcl name (defaults to PY_VARnum).
234
235 If NAME matches an existing variable and VALUE is omitted
236 then the existing value is retained.
237 """
238 global _varnum
239 if not master:
240 master = _default_root
Serhiy Storchaka44ae5132014-08-17 15:31:41 +0300241 self._root = master._root()
Georg Brandl33cece02008-05-20 06:58:21 +0000242 self._tk = master.tk
243 if name:
244 self._name = name
245 else:
246 self._name = 'PY_VAR' + repr(_varnum)
247 _varnum += 1
248 if value is not None:
249 self.set(value)
Serhiy Storchaka5e116552013-12-26 20:05:53 +0200250 elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)):
Georg Brandl33cece02008-05-20 06:58:21 +0000251 self.set(self._default)
252 def __del__(self):
253 """Unset the variable in Tcl."""
Serhiy Storchaka44ae5132014-08-17 15:31:41 +0300254 if self._tk is None:
255 return
256 if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
Serhiy Storchaka5e116552013-12-26 20:05:53 +0200257 self._tk.globalunsetvar(self._name)
Serhiy Storchaka44ae5132014-08-17 15:31:41 +0300258 if self._tclCommands is not None:
259 for name in self._tclCommands:
260 #print '- Tkinter: deleted command', name
261 self._tk.deletecommand(name)
262 self._tclCommands = None
Georg Brandl33cece02008-05-20 06:58:21 +0000263 def __str__(self):
264 """Return the name of the variable in Tcl."""
265 return self._name
266 def set(self, value):
267 """Set the variable to VALUE."""
268 return self._tk.globalsetvar(self._name, value)
269 def get(self):
270 """Return value of variable."""
271 return self._tk.globalgetvar(self._name)
272 def trace_variable(self, mode, callback):
273 """Define a trace callback for the variable.
274
275 MODE is one of "r", "w", "u" for read, write, undefine.
276 CALLBACK must be a function which is called when
277 the variable is read, written or undefined.
278
279 Return the name of the callback.
280 """
Serhiy Storchaka44ae5132014-08-17 15:31:41 +0300281 f = CallWrapper(callback, None, self._root).__call__
282 cbname = repr(id(f))
283 try:
284 callback = callback.im_func
285 except AttributeError:
286 pass
287 try:
288 cbname = cbname + callback.__name__
289 except AttributeError:
290 pass
291 self._tk.createcommand(cbname, f)
292 if self._tclCommands is None:
293 self._tclCommands = []
294 self._tclCommands.append(cbname)
Georg Brandl33cece02008-05-20 06:58:21 +0000295 self._tk.call("trace", "variable", self._name, mode, cbname)
296 return cbname
297 trace = trace_variable
298 def trace_vdelete(self, mode, cbname):
299 """Delete the trace callback for a variable.
300
301 MODE is one of "r", "w", "u" for read, write, undefine.
302 CBNAME is the name of the callback returned from trace_variable or trace.
303 """
304 self._tk.call("trace", "vdelete", self._name, mode, cbname)
Serhiy Storchaka199b7d52016-06-26 17:41:14 +0300305 cbname = self._tk.splitlist(cbname)[0]
306 for m, ca in self.trace_vinfo():
307 if self._tk.splitlist(ca)[0] == cbname:
308 break
309 else:
310 self._tk.deletecommand(cbname)
311 try:
312 self._tclCommands.remove(cbname)
313 except ValueError:
314 pass
Georg Brandl33cece02008-05-20 06:58:21 +0000315 def trace_vinfo(self):
316 """Return all trace callback information."""
Serhiy Storchaka199b7d52016-06-26 17:41:14 +0300317 return map(self._tk.splitlist, self._tk.splitlist(
Georg Brandl33cece02008-05-20 06:58:21 +0000318 self._tk.call("trace", "vinfo", self._name)))
319 def __eq__(self, other):
320 """Comparison for equality (==).
321
322 Note: if the Variable's master matters to behavior
323 also compare self._master == other._master
324 """
325 return self.__class__.__name__ == other.__class__.__name__ \
326 and self._name == other._name
327
328class StringVar(Variable):
329 """Value holder for strings variables."""
330 _default = ""
331 def __init__(self, master=None, value=None, name=None):
332 """Construct a string variable.
333
334 MASTER can be given as master widget.
335 VALUE is an optional value (defaults to "")
336 NAME is an optional Tcl name (defaults to PY_VARnum).
337
338 If NAME matches an existing variable and VALUE is omitted
339 then the existing value is retained.
340 """
341 Variable.__init__(self, master, value, name)
342
343 def get(self):
344 """Return value of variable as string."""
345 value = self._tk.globalgetvar(self._name)
346 if isinstance(value, basestring):
347 return value
348 return str(value)
349
350class IntVar(Variable):
351 """Value holder for integer variables."""
352 _default = 0
353 def __init__(self, master=None, value=None, name=None):
354 """Construct an integer variable.
355
356 MASTER can be given as master widget.
357 VALUE is an optional value (defaults to 0)
358 NAME is an optional Tcl name (defaults to PY_VARnum).
359
360 If NAME matches an existing variable and VALUE is omitted
361 then the existing value is retained.
362 """
363 Variable.__init__(self, master, value, name)
364
365 def set(self, value):
366 """Set the variable to value, converting booleans to integers."""
367 if isinstance(value, bool):
368 value = int(value)
369 return Variable.set(self, value)
370
371 def get(self):
372 """Return the value of the variable as an integer."""
373 return getint(self._tk.globalgetvar(self._name))
374
375class DoubleVar(Variable):
376 """Value holder for float variables."""
377 _default = 0.0
378 def __init__(self, master=None, value=None, name=None):
379 """Construct a float variable.
380
381 MASTER can be given as master widget.
382 VALUE is an optional value (defaults to 0.0)
383 NAME is an optional Tcl name (defaults to PY_VARnum).
384
385 If NAME matches an existing variable and VALUE is omitted
386 then the existing value is retained.
387 """
388 Variable.__init__(self, master, value, name)
389
390 def get(self):
391 """Return the value of the variable as a float."""
392 return getdouble(self._tk.globalgetvar(self._name))
393
394class BooleanVar(Variable):
395 """Value holder for boolean variables."""
396 _default = False
397 def __init__(self, master=None, value=None, name=None):
398 """Construct a boolean variable.
399
400 MASTER can be given as master widget.
401 VALUE is an optional value (defaults to False)
402 NAME is an optional Tcl name (defaults to PY_VARnum).
403
404 If NAME matches an existing variable and VALUE is omitted
405 then the existing value is retained.
406 """
407 Variable.__init__(self, master, value, name)
408
Serhiy Storchakaf29bc702015-04-04 12:42:25 +0300409 def set(self, value):
410 """Set the variable to VALUE."""
411 return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
412
Georg Brandl33cece02008-05-20 06:58:21 +0000413 def get(self):
414 """Return the value of the variable as a bool."""
415 return self._tk.getboolean(self._tk.globalgetvar(self._name))
416
417def mainloop(n=0):
418 """Run the main loop of Tcl."""
419 _default_root.tk.mainloop(n)
420
421getint = int
422
423getdouble = float
424
425def getboolean(s):
426 """Convert true and false to integer values 1 and 0."""
427 return _default_root.tk.getboolean(s)
428
429# Methods defined on both toplevel and interior widgets
430class Misc:
431 """Internal class.
432
433 Base class which defines methods common for interior widgets."""
434
435 # XXX font command?
436 _tclCommands = None
437 def destroy(self):
438 """Internal function.
439
440 Delete all Tcl commands created for
441 this widget in the Tcl interpreter."""
442 if self._tclCommands is not None:
443 for name in self._tclCommands:
444 #print '- Tkinter: deleted command', name
445 self.tk.deletecommand(name)
446 self._tclCommands = None
447 def deletecommand(self, name):
448 """Internal function.
449
450 Delete the Tcl command provided in NAME."""
451 #print '- Tkinter: deleted command', name
452 self.tk.deletecommand(name)
453 try:
454 self._tclCommands.remove(name)
455 except ValueError:
456 pass
457 def tk_strictMotif(self, boolean=None):
458 """Set Tcl internal variable, whether the look and feel
459 should adhere to Motif.
460
461 A parameter of 1 means adhere to Motif (e.g. no color
462 change if mouse passes over slider).
463 Returns the set value."""
464 return self.tk.getboolean(self.tk.call(
465 'set', 'tk_strictMotif', boolean))
466 def tk_bisque(self):
467 """Change the color scheme to light brown as used in Tk 3.6 and before."""
468 self.tk.call('tk_bisque')
469 def tk_setPalette(self, *args, **kw):
470 """Set a new color scheme for all widget elements.
471
472 A single color as argument will cause that all colors of Tk
473 widget elements are derived from this.
474 Alternatively several keyword parameters and its associated
475 colors can be given. The following keywords are valid:
476 activeBackground, foreground, selectColor,
477 activeForeground, highlightBackground, selectBackground,
478 background, highlightColor, selectForeground,
479 disabledForeground, insertBackground, troughColor."""
480 self.tk.call(('tk_setPalette',)
481 + _flatten(args) + _flatten(kw.items()))
482 def tk_menuBar(self, *args):
483 """Do not use. Needed in Tk 3.6 and earlier."""
Serhiy Storchaka2ce9ddd2014-07-25 12:23:08 +0300484 # obsolete since Tk 4.0
485 import warnings
486 warnings.warn('tk_menuBar() does nothing and will be removed in 3.6',
487 DeprecationWarning, stacklevel=2)
Georg Brandl33cece02008-05-20 06:58:21 +0000488 def wait_variable(self, name='PY_VAR'):
489 """Wait until the variable is modified.
490
491 A parameter of type IntVar, StringVar, DoubleVar or
492 BooleanVar must be given."""
493 self.tk.call('tkwait', 'variable', name)
494 waitvar = wait_variable # XXX b/w compat
495 def wait_window(self, window=None):
496 """Wait until a WIDGET is destroyed.
497
498 If no parameter is given self is used."""
499 if window is None:
500 window = self
501 self.tk.call('tkwait', 'window', window._w)
502 def wait_visibility(self, window=None):
503 """Wait until the visibility of a WIDGET changes
504 (e.g. it appears).
505
506 If no parameter is given self is used."""
507 if window is None:
508 window = self
509 self.tk.call('tkwait', 'visibility', window._w)
510 def setvar(self, name='PY_VAR', value='1'):
511 """Set Tcl variable NAME to VALUE."""
512 self.tk.setvar(name, value)
513 def getvar(self, name='PY_VAR'):
514 """Return value of Tcl variable NAME."""
515 return self.tk.getvar(name)
516 getint = int
517 getdouble = float
518 def getboolean(self, s):
519 """Return a boolean value for Tcl boolean values true and false given as parameter."""
520 return self.tk.getboolean(s)
521 def focus_set(self):
522 """Direct input focus to this widget.
523
524 If the application currently does not have the focus
525 this widget will get the focus if the application gets
526 the focus through the window manager."""
527 self.tk.call('focus', self._w)
528 focus = focus_set # XXX b/w compat?
529 def focus_force(self):
530 """Direct input focus to this widget even if the
531 application does not have the focus. Use with
532 caution!"""
533 self.tk.call('focus', '-force', self._w)
534 def focus_get(self):
535 """Return the widget which has currently the focus in the
536 application.
537
538 Use focus_displayof to allow working with several
539 displays. Return None if application does not have
540 the focus."""
541 name = self.tk.call('focus')
542 if name == 'none' or not name: return None
543 return self._nametowidget(name)
544 def focus_displayof(self):
545 """Return the widget which has currently the focus on the
546 display where this widget is located.
547
548 Return None if the application does not have the focus."""
549 name = self.tk.call('focus', '-displayof', self._w)
550 if name == 'none' or not name: return None
551 return self._nametowidget(name)
552 def focus_lastfor(self):
553 """Return the widget which would have the focus if top level
554 for this widget gets the focus from the window manager."""
555 name = self.tk.call('focus', '-lastfor', self._w)
556 if name == 'none' or not name: return None
557 return self._nametowidget(name)
558 def tk_focusFollowsMouse(self):
559 """The widget under mouse will get automatically focus. Can not
560 be disabled easily."""
561 self.tk.call('tk_focusFollowsMouse')
562 def tk_focusNext(self):
563 """Return the next widget in the focus order which follows
564 widget which has currently the focus.
565
566 The focus order first goes to the next child, then to
567 the children of the child recursively and then to the
568 next sibling which is higher in the stacking order. A
569 widget is omitted if it has the takefocus resource set
570 to 0."""
571 name = self.tk.call('tk_focusNext', self._w)
572 if not name: return None
573 return self._nametowidget(name)
574 def tk_focusPrev(self):
575 """Return previous widget in the focus order. See tk_focusNext for details."""
576 name = self.tk.call('tk_focusPrev', self._w)
577 if not name: return None
578 return self._nametowidget(name)
579 def after(self, ms, func=None, *args):
580 """Call function once after given time.
581
582 MS specifies the time in milliseconds. FUNC gives the
583 function which shall be called. Additional parameters
584 are given as parameters to the function call. Return
585 identifier to cancel scheduling with after_cancel."""
586 if not func:
587 # I'd rather use time.sleep(ms*0.001)
588 self.tk.call('after', ms)
Cheryl Sabella3a045982018-05-05 06:10:48 -0700589 return None
Georg Brandl33cece02008-05-20 06:58:21 +0000590 else:
591 def callit():
592 try:
593 func(*args)
594 finally:
595 try:
596 self.deletecommand(name)
597 except TclError:
598 pass
Serhiy Storchakad3ea0652014-08-24 09:07:09 +0300599 callit.__name__ = func.__name__
Georg Brandl33cece02008-05-20 06:58:21 +0000600 name = self._register(callit)
601 return self.tk.call('after', ms, name)
602 def after_idle(self, func, *args):
603 """Call FUNC once if the Tcl main loop has no event to
604 process.
605
606 Return an identifier to cancel the scheduling with
607 after_cancel."""
608 return self.after('idle', func, *args)
609 def after_cancel(self, id):
610 """Cancel scheduling of function identified with ID.
611
612 Identifier returned by after or after_idle must be
Cheryl Sabella3a045982018-05-05 06:10:48 -0700613 given as first parameter.
614 """
615 if not id:
616 raise ValueError('id must be a valid identifier returned from '
617 'after or after_idle')
Georg Brandl33cece02008-05-20 06:58:21 +0000618 try:
619 data = self.tk.call('after', 'info', id)
Georg Brandl33cece02008-05-20 06:58:21 +0000620 script = self.tk.splitlist(data)[0]
621 self.deletecommand(script)
622 except TclError:
623 pass
624 self.tk.call('after', 'cancel', id)
625 def bell(self, displayof=0):
626 """Ring a display's bell."""
627 self.tk.call(('bell',) + self._displayof(displayof))
628
629 # Clipboard handling:
630 def clipboard_get(self, **kw):
631 """Retrieve data from the clipboard on window's display.
632
633 The window keyword defaults to the root window of the Tkinter
634 application.
635
636 The type keyword specifies the form in which the data is
637 to be returned and should be an atom name such as STRING
Ned Deily724a55c2012-05-15 18:05:57 -0700638 or FILE_NAME. Type defaults to STRING, except on X11, where the default
639 is to try UTF8_STRING and fall back to STRING.
Georg Brandl33cece02008-05-20 06:58:21 +0000640
641 This command is equivalent to:
642
643 selection_get(CLIPBOARD)
644 """
Ned Deily724a55c2012-05-15 18:05:57 -0700645 if 'type' not in kw and self._windowingsystem == 'x11':
646 try:
647 kw['type'] = 'UTF8_STRING'
648 return self.tk.call(('clipboard', 'get') + self._options(kw))
649 except TclError:
650 del kw['type']
Georg Brandl33cece02008-05-20 06:58:21 +0000651 return self.tk.call(('clipboard', 'get') + self._options(kw))
652
653 def clipboard_clear(self, **kw):
654 """Clear the data in the Tk clipboard.
655
656 A widget specified for the optional displayof keyword
657 argument specifies the target display."""
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000658 if 'displayof' not in kw: kw['displayof'] = self._w
Georg Brandl33cece02008-05-20 06:58:21 +0000659 self.tk.call(('clipboard', 'clear') + self._options(kw))
660 def clipboard_append(self, string, **kw):
661 """Append STRING to the Tk clipboard.
662
663 A widget specified at the optional displayof keyword
664 argument specifies the target display. The clipboard
665 can be retrieved with selection_get."""
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000666 if 'displayof' not in kw: kw['displayof'] = self._w
Georg Brandl33cece02008-05-20 06:58:21 +0000667 self.tk.call(('clipboard', 'append') + self._options(kw)
668 + ('--', string))
669 # XXX grab current w/o window argument
670 def grab_current(self):
671 """Return widget which has currently the grab in this application
672 or None."""
673 name = self.tk.call('grab', 'current', self._w)
674 if not name: return None
675 return self._nametowidget(name)
676 def grab_release(self):
677 """Release grab for this widget if currently set."""
678 self.tk.call('grab', 'release', self._w)
679 def grab_set(self):
680 """Set grab for this widget.
681
682 A grab directs all events to this and descendant
683 widgets in the application."""
684 self.tk.call('grab', 'set', self._w)
685 def grab_set_global(self):
686 """Set global grab for this widget.
687
688 A global grab directs all events to this and
689 descendant widgets on the display. Use with caution -
690 other applications do not get events anymore."""
691 self.tk.call('grab', 'set', '-global', self._w)
692 def grab_status(self):
693 """Return None, "local" or "global" if this widget has
694 no, a local or a global grab."""
695 status = self.tk.call('grab', 'status', self._w)
696 if status == 'none': status = None
697 return status
698 def option_add(self, pattern, value, priority = None):
699 """Set a VALUE (second parameter) for an option
700 PATTERN (first parameter).
701
702 An optional third parameter gives the numeric priority
703 (defaults to 80)."""
704 self.tk.call('option', 'add', pattern, value, priority)
705 def option_clear(self):
706 """Clear the option database.
707
708 It will be reloaded if option_add is called."""
709 self.tk.call('option', 'clear')
710 def option_get(self, name, className):
711 """Return the value for an option NAME for this widget
712 with CLASSNAME.
713
714 Values with higher priority override lower values."""
715 return self.tk.call('option', 'get', self._w, name, className)
716 def option_readfile(self, fileName, priority = None):
717 """Read file FILENAME into the option database.
718
719 An optional second parameter gives the numeric
720 priority."""
721 self.tk.call('option', 'readfile', fileName, priority)
722 def selection_clear(self, **kw):
723 """Clear the current X selection."""
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000724 if 'displayof' not in kw: kw['displayof'] = self._w
Georg Brandl33cece02008-05-20 06:58:21 +0000725 self.tk.call(('selection', 'clear') + self._options(kw))
726 def selection_get(self, **kw):
727 """Return the contents of the current X selection.
728
729 A keyword parameter selection specifies the name of
730 the selection and defaults to PRIMARY. A keyword
731 parameter displayof specifies a widget on the display
Ned Deily724a55c2012-05-15 18:05:57 -0700732 to use. A keyword parameter type specifies the form of data to be
733 fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
734 before STRING."""
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000735 if 'displayof' not in kw: kw['displayof'] = self._w
Ned Deily724a55c2012-05-15 18:05:57 -0700736 if 'type' not in kw and self._windowingsystem == 'x11':
737 try:
738 kw['type'] = 'UTF8_STRING'
739 return self.tk.call(('selection', 'get') + self._options(kw))
740 except TclError:
741 del kw['type']
Georg Brandl33cece02008-05-20 06:58:21 +0000742 return self.tk.call(('selection', 'get') + self._options(kw))
743 def selection_handle(self, command, **kw):
744 """Specify a function COMMAND to call if the X
745 selection owned by this widget is queried by another
746 application.
747
748 This function must return the contents of the
749 selection. The function will be called with the
750 arguments OFFSET and LENGTH which allows the chunking
751 of very long selections. The following keyword
752 parameters can be provided:
753 selection - name of the selection (default PRIMARY),
754 type - type of the selection (e.g. STRING, FILE_NAME)."""
755 name = self._register(command)
756 self.tk.call(('selection', 'handle') + self._options(kw)
757 + (self._w, name))
758 def selection_own(self, **kw):
759 """Become owner of X selection.
760
761 A keyword parameter selection specifies the name of
762 the selection (default PRIMARY)."""
763 self.tk.call(('selection', 'own') +
764 self._options(kw) + (self._w,))
765 def selection_own_get(self, **kw):
766 """Return owner of X selection.
767
768 The following keyword parameter can
769 be provided:
770 selection - name of the selection (default PRIMARY),
771 type - type of the selection (e.g. STRING, FILE_NAME)."""
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +0000772 if 'displayof' not in kw: kw['displayof'] = self._w
Georg Brandl33cece02008-05-20 06:58:21 +0000773 name = self.tk.call(('selection', 'own') + self._options(kw))
774 if not name: return None
775 return self._nametowidget(name)
776 def send(self, interp, cmd, *args):
777 """Send Tcl command CMD to different interpreter INTERP to be executed."""
778 return self.tk.call(('send', interp, cmd) + args)
779 def lower(self, belowThis=None):
780 """Lower this widget in the stacking order."""
781 self.tk.call('lower', self._w, belowThis)
782 def tkraise(self, aboveThis=None):
783 """Raise this widget in the stacking order."""
784 self.tk.call('raise', self._w, aboveThis)
785 lift = tkraise
786 def colormodel(self, value=None):
787 """Useless. Not implemented in Tk."""
788 return self.tk.call('tk', 'colormodel', self._w, value)
789 def winfo_atom(self, name, displayof=0):
790 """Return integer which represents atom NAME."""
791 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
792 return getint(self.tk.call(args))
793 def winfo_atomname(self, id, displayof=0):
794 """Return name of atom with identifier ID."""
795 args = ('winfo', 'atomname') \
796 + self._displayof(displayof) + (id,)
797 return self.tk.call(args)
798 def winfo_cells(self):
799 """Return number of cells in the colormap for this widget."""
800 return getint(
801 self.tk.call('winfo', 'cells', self._w))
802 def winfo_children(self):
803 """Return a list of all widgets which are children of this widget."""
804 result = []
805 for child in self.tk.splitlist(
806 self.tk.call('winfo', 'children', self._w)):
807 try:
808 # Tcl sometimes returns extra windows, e.g. for
809 # menus; those need to be skipped
810 result.append(self._nametowidget(child))
811 except KeyError:
812 pass
813 return result
814
815 def winfo_class(self):
816 """Return window class name of this widget."""
817 return self.tk.call('winfo', 'class', self._w)
818 def winfo_colormapfull(self):
819 """Return true if at the last color request the colormap was full."""
820 return self.tk.getboolean(
821 self.tk.call('winfo', 'colormapfull', self._w))
822 def winfo_containing(self, rootX, rootY, displayof=0):
823 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
824 args = ('winfo', 'containing') \
825 + self._displayof(displayof) + (rootX, rootY)
826 name = self.tk.call(args)
827 if not name: return None
828 return self._nametowidget(name)
829 def winfo_depth(self):
830 """Return the number of bits per pixel."""
831 return getint(self.tk.call('winfo', 'depth', self._w))
832 def winfo_exists(self):
833 """Return true if this widget exists."""
834 return getint(
835 self.tk.call('winfo', 'exists', self._w))
836 def winfo_fpixels(self, number):
837 """Return the number of pixels for the given distance NUMBER
838 (e.g. "3c") as float."""
839 return getdouble(self.tk.call(
840 'winfo', 'fpixels', self._w, number))
841 def winfo_geometry(self):
842 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
843 return self.tk.call('winfo', 'geometry', self._w)
844 def winfo_height(self):
845 """Return height of this widget."""
846 return getint(
847 self.tk.call('winfo', 'height', self._w))
848 def winfo_id(self):
849 """Return identifier ID for this widget."""
Victor Stinnerf6d64802017-07-06 10:22:50 +0200850 return int(self.tk.call('winfo', 'id', self._w), 0)
Georg Brandl33cece02008-05-20 06:58:21 +0000851 def winfo_interps(self, displayof=0):
852 """Return the name of all Tcl interpreters for this display."""
853 args = ('winfo', 'interps') + self._displayof(displayof)
854 return self.tk.splitlist(self.tk.call(args))
855 def winfo_ismapped(self):
856 """Return true if this widget is mapped."""
857 return getint(
858 self.tk.call('winfo', 'ismapped', self._w))
859 def winfo_manager(self):
Vijay Kumarf31f2252017-05-23 11:46:27 +0530860 """Return the window manager name for this widget."""
Georg Brandl33cece02008-05-20 06:58:21 +0000861 return self.tk.call('winfo', 'manager', self._w)
862 def winfo_name(self):
863 """Return the name of this widget."""
864 return self.tk.call('winfo', 'name', self._w)
865 def winfo_parent(self):
866 """Return the name of the parent of this widget."""
867 return self.tk.call('winfo', 'parent', self._w)
868 def winfo_pathname(self, id, displayof=0):
869 """Return the pathname of the widget given by ID."""
870 args = ('winfo', 'pathname') \
871 + self._displayof(displayof) + (id,)
872 return self.tk.call(args)
873 def winfo_pixels(self, number):
874 """Rounded integer value of winfo_fpixels."""
875 return getint(
876 self.tk.call('winfo', 'pixels', self._w, number))
877 def winfo_pointerx(self):
878 """Return the x coordinate of the pointer on the root window."""
879 return getint(
880 self.tk.call('winfo', 'pointerx', self._w))
881 def winfo_pointerxy(self):
882 """Return a tuple of x and y coordinates of the pointer on the root window."""
883 return self._getints(
884 self.tk.call('winfo', 'pointerxy', self._w))
885 def winfo_pointery(self):
886 """Return the y coordinate of the pointer on the root window."""
887 return getint(
888 self.tk.call('winfo', 'pointery', self._w))
889 def winfo_reqheight(self):
890 """Return requested height of this widget."""
891 return getint(
892 self.tk.call('winfo', 'reqheight', self._w))
893 def winfo_reqwidth(self):
894 """Return requested width of this widget."""
895 return getint(
896 self.tk.call('winfo', 'reqwidth', self._w))
897 def winfo_rgb(self, color):
898 """Return tuple of decimal values for red, green, blue for
899 COLOR in this widget."""
900 return self._getints(
901 self.tk.call('winfo', 'rgb', self._w, color))
902 def winfo_rootx(self):
903 """Return x coordinate of upper left corner of this widget on the
904 root window."""
905 return getint(
906 self.tk.call('winfo', 'rootx', self._w))
907 def winfo_rooty(self):
908 """Return y coordinate of upper left corner of this widget on the
909 root window."""
910 return getint(
911 self.tk.call('winfo', 'rooty', self._w))
912 def winfo_screen(self):
913 """Return the screen name of this widget."""
914 return self.tk.call('winfo', 'screen', self._w)
915 def winfo_screencells(self):
916 """Return the number of the cells in the colormap of the screen
917 of this widget."""
918 return getint(
919 self.tk.call('winfo', 'screencells', self._w))
920 def winfo_screendepth(self):
921 """Return the number of bits per pixel of the root window of the
922 screen of this widget."""
923 return getint(
924 self.tk.call('winfo', 'screendepth', self._w))
925 def winfo_screenheight(self):
926 """Return the number of pixels of the height of the screen of this widget
927 in pixel."""
928 return getint(
929 self.tk.call('winfo', 'screenheight', self._w))
930 def winfo_screenmmheight(self):
931 """Return the number of pixels of the height of the screen of
932 this widget in mm."""
933 return getint(
934 self.tk.call('winfo', 'screenmmheight', self._w))
935 def winfo_screenmmwidth(self):
936 """Return the number of pixels of the width of the screen of
937 this widget in mm."""
938 return getint(
939 self.tk.call('winfo', 'screenmmwidth', self._w))
940 def winfo_screenvisual(self):
941 """Return one of the strings directcolor, grayscale, pseudocolor,
942 staticcolor, staticgray, or truecolor for the default
943 colormodel of this screen."""
944 return self.tk.call('winfo', 'screenvisual', self._w)
945 def winfo_screenwidth(self):
946 """Return the number of pixels of the width of the screen of
947 this widget in pixel."""
948 return getint(
949 self.tk.call('winfo', 'screenwidth', self._w))
950 def winfo_server(self):
951 """Return information of the X-Server of the screen of this widget in
952 the form "XmajorRminor vendor vendorVersion"."""
953 return self.tk.call('winfo', 'server', self._w)
954 def winfo_toplevel(self):
955 """Return the toplevel widget of this widget."""
956 return self._nametowidget(self.tk.call(
957 'winfo', 'toplevel', self._w))
958 def winfo_viewable(self):
959 """Return true if the widget and all its higher ancestors are mapped."""
960 return getint(
961 self.tk.call('winfo', 'viewable', self._w))
962 def winfo_visual(self):
963 """Return one of the strings directcolor, grayscale, pseudocolor,
964 staticcolor, staticgray, or truecolor for the
965 colormodel of this widget."""
966 return self.tk.call('winfo', 'visual', self._w)
967 def winfo_visualid(self):
968 """Return the X identifier for the visual for this widget."""
969 return self.tk.call('winfo', 'visualid', self._w)
970 def winfo_visualsavailable(self, includeids=0):
971 """Return a list of all visuals available for the screen
972 of this widget.
973
974 Each item in the list consists of a visual name (see winfo_visual), a
975 depth and if INCLUDEIDS=1 is given also the X identifier."""
976 data = self.tk.split(
977 self.tk.call('winfo', 'visualsavailable', self._w,
978 includeids and 'includeids' or None))
979 if type(data) is StringType:
980 data = [self.tk.split(data)]
981 return map(self.__winfo_parseitem, data)
982 def __winfo_parseitem(self, t):
983 """Internal function."""
984 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
985 def __winfo_getint(self, x):
986 """Internal function."""
987 return int(x, 0)
988 def winfo_vrootheight(self):
989 """Return the height of the virtual root window associated with this
990 widget in pixels. If there is no virtual root window return the
991 height of the screen."""
992 return getint(
993 self.tk.call('winfo', 'vrootheight', self._w))
994 def winfo_vrootwidth(self):
995 """Return the width of the virtual root window associated with this
996 widget in pixel. If there is no virtual root window return the
997 width of the screen."""
998 return getint(
999 self.tk.call('winfo', 'vrootwidth', self._w))
1000 def winfo_vrootx(self):
1001 """Return the x offset of the virtual root relative to the root
1002 window of the screen of this widget."""
1003 return getint(
1004 self.tk.call('winfo', 'vrootx', self._w))
1005 def winfo_vrooty(self):
1006 """Return the y offset of the virtual root relative to the root
1007 window of the screen of this widget."""
1008 return getint(
1009 self.tk.call('winfo', 'vrooty', self._w))
1010 def winfo_width(self):
1011 """Return the width of this widget."""
1012 return getint(
1013 self.tk.call('winfo', 'width', self._w))
1014 def winfo_x(self):
1015 """Return the x coordinate of the upper left corner of this widget
1016 in the parent."""
1017 return getint(
1018 self.tk.call('winfo', 'x', self._w))
1019 def winfo_y(self):
1020 """Return the y coordinate of the upper left corner of this widget
1021 in the parent."""
1022 return getint(
1023 self.tk.call('winfo', 'y', self._w))
1024 def update(self):
1025 """Enter event loop until all pending events have been processed by Tcl."""
1026 self.tk.call('update')
1027 def update_idletasks(self):
1028 """Enter event loop until all idle callbacks have been called. This
1029 will update the display of windows but not process events caused by
1030 the user."""
1031 self.tk.call('update', 'idletasks')
1032 def bindtags(self, tagList=None):
1033 """Set or get the list of bindtags for this widget.
1034
1035 With no argument return the list of all bindtags associated with
1036 this widget. With a list of strings as argument the bindtags are
1037 set to this list. The bindtags determine in which order events are
1038 processed (see bind)."""
1039 if tagList is None:
1040 return self.tk.splitlist(
1041 self.tk.call('bindtags', self._w))
1042 else:
1043 self.tk.call('bindtags', self._w, tagList)
1044 def _bind(self, what, sequence, func, add, needcleanup=1):
1045 """Internal function."""
1046 if type(func) is StringType:
1047 self.tk.call(what + (sequence, func))
1048 elif func:
1049 funcid = self._register(func, self._substitute,
1050 needcleanup)
1051 cmd = ('%sif {"[%s %s]" == "break"} break\n'
1052 %
1053 (add and '+' or '',
1054 funcid, self._subst_format_str))
1055 self.tk.call(what + (sequence, cmd))
1056 return funcid
1057 elif sequence:
1058 return self.tk.call(what + (sequence,))
1059 else:
1060 return self.tk.splitlist(self.tk.call(what))
1061 def bind(self, sequence=None, func=None, add=None):
1062 """Bind to this widget at event SEQUENCE a call to function FUNC.
1063
1064 SEQUENCE is a string of concatenated event
1065 patterns. An event pattern is of the form
1066 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
1067 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
1068 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
1069 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
1070 Mod1, M1. TYPE is one of Activate, Enter, Map,
1071 ButtonPress, Button, Expose, Motion, ButtonRelease
1072 FocusIn, MouseWheel, Circulate, FocusOut, Property,
1073 Colormap, Gravity Reparent, Configure, KeyPress, Key,
1074 Unmap, Deactivate, KeyRelease Visibility, Destroy,
1075 Leave and DETAIL is the button number for ButtonPress,
1076 ButtonRelease and DETAIL is the Keysym for KeyPress and
1077 KeyRelease. Examples are
1078 <Control-Button-1> for pressing Control and mouse button 1 or
1079 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
1080 An event pattern can also be a virtual event of the form
1081 <<AString>> where AString can be arbitrary. This
1082 event can be generated by event_generate.
1083 If events are concatenated they must appear shortly
1084 after each other.
1085
1086 FUNC will be called if the event sequence occurs with an
1087 instance of Event as argument. If the return value of FUNC is
1088 "break" no further bound function is invoked.
1089
1090 An additional boolean parameter ADD specifies whether FUNC will
1091 be called additionally to the other bound function or whether
1092 it will replace the previous function.
1093
1094 Bind will return an identifier to allow deletion of the bound function with
1095 unbind without memory leak.
1096
1097 If FUNC or SEQUENCE is omitted the bound function or list
1098 of bound events are returned."""
1099
1100 return self._bind(('bind', self._w), sequence, func, add)
1101 def unbind(self, sequence, funcid=None):
1102 """Unbind for this widget for event SEQUENCE the
1103 function identified with FUNCID."""
1104 self.tk.call('bind', self._w, sequence, '')
1105 if funcid:
1106 self.deletecommand(funcid)
1107 def bind_all(self, sequence=None, func=None, add=None):
1108 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1109 An additional boolean parameter ADD specifies whether FUNC will
1110 be called additionally to the other bound function or whether
1111 it will replace the previous function. See bind for the return value."""
1112 return self._bind(('bind', 'all'), sequence, func, add, 0)
1113 def unbind_all(self, sequence):
1114 """Unbind for all widgets for event SEQUENCE all functions."""
1115 self.tk.call('bind', 'all' , sequence, '')
1116 def bind_class(self, className, sequence=None, func=None, add=None):
1117
1118 """Bind to widgets with bindtag CLASSNAME at event
1119 SEQUENCE a call of function FUNC. An additional
1120 boolean parameter ADD specifies whether FUNC will be
1121 called additionally to the other bound function or
1122 whether it will replace the previous function. See bind for
1123 the return value."""
1124
1125 return self._bind(('bind', className), sequence, func, add, 0)
1126 def unbind_class(self, className, sequence):
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02001127 """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
Georg Brandl33cece02008-05-20 06:58:21 +00001128 all functions."""
1129 self.tk.call('bind', className , sequence, '')
1130 def mainloop(self, n=0):
1131 """Call the mainloop of Tk."""
1132 self.tk.mainloop(n)
1133 def quit(self):
1134 """Quit the Tcl interpreter. All widgets will be destroyed."""
1135 self.tk.quit()
1136 def _getints(self, string):
1137 """Internal function."""
1138 if string:
1139 return tuple(map(getint, self.tk.splitlist(string)))
1140 def _getdoubles(self, string):
1141 """Internal function."""
1142 if string:
1143 return tuple(map(getdouble, self.tk.splitlist(string)))
1144 def _getboolean(self, string):
1145 """Internal function."""
1146 if string:
1147 return self.tk.getboolean(string)
1148 def _displayof(self, displayof):
1149 """Internal function."""
1150 if displayof:
1151 return ('-displayof', displayof)
1152 if displayof is None:
1153 return ('-displayof', self._w)
1154 return ()
Ned Deily724a55c2012-05-15 18:05:57 -07001155 @property
1156 def _windowingsystem(self):
1157 """Internal function."""
1158 try:
1159 return self._root()._windowingsystem_cached
1160 except AttributeError:
1161 ws = self._root()._windowingsystem_cached = \
1162 self.tk.call('tk', 'windowingsystem')
1163 return ws
Georg Brandl33cece02008-05-20 06:58:21 +00001164 def _options(self, cnf, kw = None):
1165 """Internal function."""
1166 if kw:
1167 cnf = _cnfmerge((cnf, kw))
1168 else:
1169 cnf = _cnfmerge(cnf)
1170 res = ()
1171 for k, v in cnf.items():
1172 if v is not None:
1173 if k[-1] == '_': k = k[:-1]
Benjamin Petersonde055992009-10-09 22:05:45 +00001174 if hasattr(v, '__call__'):
Georg Brandl33cece02008-05-20 06:58:21 +00001175 v = self._register(v)
Georg Brandl7943a322008-05-29 07:18:49 +00001176 elif isinstance(v, (tuple, list)):
Georg Brandl4ed3ed12008-06-03 10:23:15 +00001177 nv = []
Georg Brandl7943a322008-05-29 07:18:49 +00001178 for item in v:
Serhiy Storchaka994f04d2016-12-27 15:09:36 +02001179 if not isinstance(item, (basestring, int, long)):
Georg Brandl7943a322008-05-29 07:18:49 +00001180 break
Serhiy Storchaka994f04d2016-12-27 15:09:36 +02001181 elif isinstance(item, (int, long)):
Georg Brandl4ed3ed12008-06-03 10:23:15 +00001182 nv.append('%d' % item)
1183 else:
1184 # format it to proper Tcl code if it contains space
Serhiy Storchakae39ba042013-01-15 18:01:21 +02001185 nv.append(_stringify(item))
Georg Brandl7943a322008-05-29 07:18:49 +00001186 else:
Georg Brandl4ed3ed12008-06-03 10:23:15 +00001187 v = ' '.join(nv)
Georg Brandl33cece02008-05-20 06:58:21 +00001188 res = res + ('-'+k, v)
1189 return res
1190 def nametowidget(self, name):
1191 """Return the Tkinter instance of a widget identified by
1192 its Tcl name NAME."""
Martin v. Löwisaabf4042008-08-02 07:20:25 +00001193 name = str(name).split('.')
Georg Brandl33cece02008-05-20 06:58:21 +00001194 w = self
Martin v. Löwisaabf4042008-08-02 07:20:25 +00001195
1196 if not name[0]:
Georg Brandl33cece02008-05-20 06:58:21 +00001197 w = w._root()
1198 name = name[1:]
Martin v. Löwisaabf4042008-08-02 07:20:25 +00001199
1200 for n in name:
1201 if not n:
1202 break
1203 w = w.children[n]
1204
Georg Brandl33cece02008-05-20 06:58:21 +00001205 return w
1206 _nametowidget = nametowidget
1207 def _register(self, func, subst=None, needcleanup=1):
1208 """Return a newly created Tcl function. If this
1209 function is called, the Python function FUNC will
1210 be executed. An optional function SUBST can
1211 be given which will be executed before FUNC."""
1212 f = CallWrapper(func, subst, self).__call__
1213 name = repr(id(f))
1214 try:
1215 func = func.im_func
1216 except AttributeError:
1217 pass
1218 try:
1219 name = name + func.__name__
1220 except AttributeError:
1221 pass
1222 self.tk.createcommand(name, f)
1223 if needcleanup:
1224 if self._tclCommands is None:
1225 self._tclCommands = []
1226 self._tclCommands.append(name)
Georg Brandl33cece02008-05-20 06:58:21 +00001227 return name
1228 register = _register
1229 def _root(self):
1230 """Internal function."""
1231 w = self
1232 while w.master: w = w.master
1233 return w
1234 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1235 '%s', '%t', '%w', '%x', '%y',
1236 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1237 _subst_format_str = " ".join(_subst_format)
1238 def _substitute(self, *args):
1239 """Internal function."""
1240 if len(args) != len(self._subst_format): return args
1241 getboolean = self.tk.getboolean
1242
1243 getint = int
1244 def getint_event(s):
1245 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1246 try:
1247 return int(s)
1248 except ValueError:
1249 return s
1250
1251 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1252 # Missing: (a, c, d, m, o, v, B, R)
1253 e = Event()
Martin Panterf2f1c572016-05-08 13:18:25 +00001254 # serial field: valid for all events
Georg Brandl33cece02008-05-20 06:58:21 +00001255 # number of button: ButtonPress and ButtonRelease events only
1256 # height field: Configure, ConfigureRequest, Create,
1257 # ResizeRequest, and Expose events only
1258 # keycode field: KeyPress and KeyRelease events only
1259 # time field: "valid for events that contain a time field"
1260 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1261 # and Expose events only
Martin Panter4f23cab2016-05-08 13:45:55 +00001262 # x field: "valid for events that contain an x field"
Georg Brandl33cece02008-05-20 06:58:21 +00001263 # y field: "valid for events that contain a y field"
1264 # keysym as decimal: KeyPress and KeyRelease events only
1265 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
Martin Panterf2f1c572016-05-08 13:18:25 +00001266 # KeyRelease, and Motion events
Georg Brandl33cece02008-05-20 06:58:21 +00001267 e.serial = getint(nsign)
1268 e.num = getint_event(b)
1269 try: e.focus = getboolean(f)
1270 except TclError: pass
1271 e.height = getint_event(h)
1272 e.keycode = getint_event(k)
1273 e.state = getint_event(s)
1274 e.time = getint_event(t)
1275 e.width = getint_event(w)
1276 e.x = getint_event(x)
1277 e.y = getint_event(y)
1278 e.char = A
1279 try: e.send_event = getboolean(E)
1280 except TclError: pass
1281 e.keysym = K
1282 e.keysym_num = getint_event(N)
1283 e.type = T
1284 try:
1285 e.widget = self._nametowidget(W)
1286 except KeyError:
1287 e.widget = W
1288 e.x_root = getint_event(X)
1289 e.y_root = getint_event(Y)
1290 try:
1291 e.delta = getint(D)
1292 except ValueError:
1293 e.delta = 0
1294 return (e,)
1295 def _report_exception(self):
1296 """Internal function."""
1297 import sys
1298 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1299 root = self._root()
1300 root.report_callback_exception(exc, val, tb)
Serhiy Storchakaec773cc2013-12-25 16:35:20 +02001301
1302 def _getconfigure(self, *args):
1303 """Call Tcl configure command and return the result as a dict."""
1304 cnf = {}
1305 for x in self.tk.splitlist(self.tk.call(*args)):
1306 x = self.tk.splitlist(x)
1307 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1308 return cnf
1309
1310 def _getconfigure1(self, *args):
1311 x = self.tk.splitlist(self.tk.call(*args))
1312 return (x[0][1:],) + x[1:]
1313
Georg Brandl33cece02008-05-20 06:58:21 +00001314 def _configure(self, cmd, cnf, kw):
1315 """Internal function."""
1316 if kw:
1317 cnf = _cnfmerge((cnf, kw))
1318 elif cnf:
1319 cnf = _cnfmerge(cnf)
1320 if cnf is None:
Serhiy Storchakaec773cc2013-12-25 16:35:20 +02001321 return self._getconfigure(_flatten((self._w, cmd)))
Georg Brandl33cece02008-05-20 06:58:21 +00001322 if type(cnf) is StringType:
Serhiy Storchakaec773cc2013-12-25 16:35:20 +02001323 return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
Georg Brandl33cece02008-05-20 06:58:21 +00001324 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1325 # These used to be defined in Widget:
1326 def configure(self, cnf=None, **kw):
1327 """Configure resources of a widget.
1328
1329 The values for resources are specified as keyword
1330 arguments. To get an overview about
1331 the allowed keyword arguments call the method keys.
1332 """
1333 return self._configure('configure', cnf, kw)
1334 config = configure
1335 def cget(self, key):
1336 """Return the resource value for a KEY given as string."""
Georg Brandl33cece02008-05-20 06:58:21 +00001337 return self.tk.call(self._w, 'cget', '-' + key)
1338 __getitem__ = cget
1339 def __setitem__(self, key, value):
1340 self.configure({key: value})
Georg Brandlae019e12008-05-20 08:48:34 +00001341 def __contains__(self, key):
1342 raise TypeError("Tkinter objects don't support 'in' tests.")
Georg Brandl33cece02008-05-20 06:58:21 +00001343 def keys(self):
1344 """Return a list of all resource names of this widget."""
Serhiy Storchaka0fd213c2016-03-09 10:51:41 +02001345 splitlist = self.tk.splitlist
1346 return [splitlist(x)[0][1:] for x in
1347 splitlist(self.tk.call(self._w, 'configure'))]
Georg Brandl33cece02008-05-20 06:58:21 +00001348 def __str__(self):
1349 """Return the window path name of this widget."""
1350 return self._w
1351 # Pack methods that apply to the master
1352 _noarg_ = ['_noarg_']
1353 def pack_propagate(self, flag=_noarg_):
1354 """Set or get the status for propagation of geometry information.
1355
1356 A boolean argument specifies whether the geometry information
1357 of the slaves will determine the size of this widget. If no argument
1358 is given the current setting will be returned.
1359 """
1360 if flag is Misc._noarg_:
1361 return self._getboolean(self.tk.call(
1362 'pack', 'propagate', self._w))
1363 else:
1364 self.tk.call('pack', 'propagate', self._w, flag)
1365 propagate = pack_propagate
1366 def pack_slaves(self):
1367 """Return a list of all slaves of this widget
1368 in its packing order."""
1369 return map(self._nametowidget,
1370 self.tk.splitlist(
1371 self.tk.call('pack', 'slaves', self._w)))
1372 slaves = pack_slaves
1373 # Place method that applies to the master
1374 def place_slaves(self):
1375 """Return a list of all slaves of this widget
1376 in its packing order."""
1377 return map(self._nametowidget,
1378 self.tk.splitlist(
1379 self.tk.call(
1380 'place', 'slaves', self._w)))
1381 # Grid methods that apply to the master
1382 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1383 """Return a tuple of integer coordinates for the bounding
1384 box of this widget controlled by the geometry manager grid.
1385
1386 If COLUMN, ROW is given the bounding box applies from
1387 the cell with row and column 0 to the specified
1388 cell. If COL2 and ROW2 are given the bounding box
1389 starts at that cell.
1390
1391 The returned integers specify the offset of the upper left
1392 corner in the master widget and the width and height.
1393 """
1394 args = ('grid', 'bbox', self._w)
1395 if column is not None and row is not None:
1396 args = args + (column, row)
1397 if col2 is not None and row2 is not None:
1398 args = args + (col2, row2)
1399 return self._getints(self.tk.call(*args)) or None
1400
1401 bbox = grid_bbox
Serhiy Storchaka3e0cb092014-02-19 18:33:30 +02001402
1403 def _gridconvvalue(self, value):
1404 if isinstance(value, (str, _tkinter.Tcl_Obj)):
1405 try:
1406 svalue = str(value)
1407 if not svalue:
1408 return None
1409 elif '.' in svalue:
1410 return getdouble(svalue)
1411 else:
1412 return getint(svalue)
1413 except ValueError:
1414 pass
1415 return value
1416
Georg Brandl33cece02008-05-20 06:58:21 +00001417 def _grid_configure(self, command, index, cnf, kw):
1418 """Internal function."""
1419 if type(cnf) is StringType and not kw:
1420 if cnf[-1:] == '_':
1421 cnf = cnf[:-1]
1422 if cnf[:1] != '-':
1423 cnf = '-'+cnf
1424 options = (cnf,)
1425 else:
1426 options = self._options(cnf, kw)
1427 if not options:
Serhiy Storchakaceaf6822014-09-06 22:47:02 +03001428 return _splitdict(
1429 self.tk,
1430 self.tk.call('grid', command, self._w, index),
1431 conv=self._gridconvvalue)
Georg Brandl33cece02008-05-20 06:58:21 +00001432 res = self.tk.call(
1433 ('grid', command, self._w, index)
1434 + options)
1435 if len(options) == 1:
Serhiy Storchaka3e0cb092014-02-19 18:33:30 +02001436 return self._gridconvvalue(res)
1437
Georg Brandl33cece02008-05-20 06:58:21 +00001438 def grid_columnconfigure(self, index, cnf={}, **kw):
1439 """Configure column INDEX of a grid.
1440
1441 Valid resources are minsize (minimum size of the column),
1442 weight (how much does additional space propagate to this column)
1443 and pad (how much space to let additionally)."""
1444 return self._grid_configure('columnconfigure', index, cnf, kw)
1445 columnconfigure = grid_columnconfigure
1446 def grid_location(self, x, y):
1447 """Return a tuple of column and row which identify the cell
1448 at which the pixel at position X and Y inside the master
1449 widget is located."""
1450 return self._getints(
1451 self.tk.call(
1452 'grid', 'location', self._w, x, y)) or None
1453 def grid_propagate(self, flag=_noarg_):
1454 """Set or get the status for propagation of geometry information.
1455
1456 A boolean argument specifies whether the geometry information
1457 of the slaves will determine the size of this widget. If no argument
1458 is given, the current setting will be returned.
1459 """
1460 if flag is Misc._noarg_:
1461 return self._getboolean(self.tk.call(
1462 'grid', 'propagate', self._w))
1463 else:
1464 self.tk.call('grid', 'propagate', self._w, flag)
1465 def grid_rowconfigure(self, index, cnf={}, **kw):
1466 """Configure row INDEX of a grid.
1467
1468 Valid resources are minsize (minimum size of the row),
1469 weight (how much does additional space propagate to this row)
1470 and pad (how much space to let additionally)."""
1471 return self._grid_configure('rowconfigure', index, cnf, kw)
1472 rowconfigure = grid_rowconfigure
1473 def grid_size(self):
1474 """Return a tuple of the number of column and rows in the grid."""
1475 return self._getints(
1476 self.tk.call('grid', 'size', self._w)) or None
1477 size = grid_size
1478 def grid_slaves(self, row=None, column=None):
1479 """Return a list of all slaves of this widget
1480 in its packing order."""
1481 args = ()
1482 if row is not None:
1483 args = args + ('-row', row)
1484 if column is not None:
1485 args = args + ('-column', column)
1486 return map(self._nametowidget,
1487 self.tk.splitlist(self.tk.call(
1488 ('grid', 'slaves', self._w) + args)))
1489
1490 # Support for the "event" command, new in Tk 4.2.
1491 # By Case Roole.
1492
1493 def event_add(self, virtual, *sequences):
1494 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1495 to an event SEQUENCE such that the virtual event is triggered
1496 whenever SEQUENCE occurs."""
1497 args = ('event', 'add', virtual) + sequences
1498 self.tk.call(args)
1499
1500 def event_delete(self, virtual, *sequences):
1501 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1502 args = ('event', 'delete', virtual) + sequences
1503 self.tk.call(args)
1504
1505 def event_generate(self, sequence, **kw):
1506 """Generate an event SEQUENCE. Additional
1507 keyword arguments specify parameter of the event
1508 (e.g. x, y, rootx, rooty)."""
1509 args = ('event', 'generate', self._w, sequence)
1510 for k, v in kw.items():
1511 args = args + ('-%s' % k, str(v))
1512 self.tk.call(args)
1513
1514 def event_info(self, virtual=None):
1515 """Return a list of all virtual events or the information
1516 about the SEQUENCE bound to the virtual event VIRTUAL."""
1517 return self.tk.splitlist(
1518 self.tk.call('event', 'info', virtual))
1519
1520 # Image related commands
1521
1522 def image_names(self):
1523 """Return a list of all existing image names."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001524 return self.tk.splitlist(self.tk.call('image', 'names'))
Georg Brandl33cece02008-05-20 06:58:21 +00001525
1526 def image_types(self):
Vijay Kumarf31f2252017-05-23 11:46:27 +05301527 """Return a list of all available image types (e.g. photo bitmap)."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001528 return self.tk.splitlist(self.tk.call('image', 'types'))
Georg Brandl33cece02008-05-20 06:58:21 +00001529
1530
1531class CallWrapper:
1532 """Internal class. Stores function to call when some user
1533 defined Tcl function is called e.g. after an event occurred."""
1534 def __init__(self, func, subst, widget):
1535 """Store FUNC, SUBST and WIDGET as members."""
1536 self.func = func
1537 self.subst = subst
1538 self.widget = widget
1539 def __call__(self, *args):
1540 """Apply first function SUBST to arguments, than FUNC."""
1541 try:
1542 if self.subst:
1543 args = self.subst(*args)
1544 return self.func(*args)
1545 except SystemExit, msg:
1546 raise SystemExit, msg
1547 except:
1548 self.widget._report_exception()
1549
1550
Guilherme Poloe45f0172009-08-14 14:36:45 +00001551class XView:
1552 """Mix-in class for querying and changing the horizontal position
1553 of a widget's window."""
1554
1555 def xview(self, *args):
1556 """Query and change the horizontal position of the view."""
1557 res = self.tk.call(self._w, 'xview', *args)
1558 if not args:
1559 return self._getdoubles(res)
1560
1561 def xview_moveto(self, fraction):
1562 """Adjusts the view in the window so that FRACTION of the
1563 total width of the canvas is off-screen to the left."""
1564 self.tk.call(self._w, 'xview', 'moveto', fraction)
1565
1566 def xview_scroll(self, number, what):
1567 """Shift the x-view according to NUMBER which is measured in "units"
1568 or "pages" (WHAT)."""
1569 self.tk.call(self._w, 'xview', 'scroll', number, what)
1570
1571
1572class YView:
1573 """Mix-in class for querying and changing the vertical position
1574 of a widget's window."""
1575
1576 def yview(self, *args):
1577 """Query and change the vertical position of the view."""
1578 res = self.tk.call(self._w, 'yview', *args)
1579 if not args:
1580 return self._getdoubles(res)
1581
1582 def yview_moveto(self, fraction):
1583 """Adjusts the view in the window so that FRACTION of the
1584 total height of the canvas is off-screen to the top."""
1585 self.tk.call(self._w, 'yview', 'moveto', fraction)
1586
1587 def yview_scroll(self, number, what):
1588 """Shift the y-view according to NUMBER which is measured in
1589 "units" or "pages" (WHAT)."""
1590 self.tk.call(self._w, 'yview', 'scroll', number, what)
1591
1592
Georg Brandl33cece02008-05-20 06:58:21 +00001593class Wm:
1594 """Provides functions for the communication with the window manager."""
1595
1596 def wm_aspect(self,
1597 minNumer=None, minDenom=None,
1598 maxNumer=None, maxDenom=None):
1599 """Instruct the window manager to set the aspect ratio (width/height)
1600 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1601 of the actual values if no argument is given."""
1602 return self._getints(
1603 self.tk.call('wm', 'aspect', self._w,
1604 minNumer, minDenom,
1605 maxNumer, maxDenom))
1606 aspect = wm_aspect
1607
1608 def wm_attributes(self, *args):
1609 """This subcommand returns or sets platform specific attributes
1610
1611 The first form returns a list of the platform specific flags and
1612 their values. The second form returns the value for the specific
1613 option. The third form sets one or more of the values. The values
1614 are as follows:
1615
1616 On Windows, -disabled gets or sets whether the window is in a
1617 disabled state. -toolwindow gets or sets the style of the window
1618 to toolwindow (as defined in the MSDN). -topmost gets or sets
1619 whether this is a topmost window (displays above all other
1620 windows).
1621
1622 On Macintosh, XXXXX
1623
1624 On Unix, there are currently no special attribute values.
1625 """
1626 args = ('wm', 'attributes', self._w) + args
1627 return self.tk.call(args)
1628 attributes=wm_attributes
1629
1630 def wm_client(self, name=None):
1631 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1632 current value."""
1633 return self.tk.call('wm', 'client', self._w, name)
1634 client = wm_client
1635 def wm_colormapwindows(self, *wlist):
1636 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1637 of this widget. This list contains windows whose colormaps differ from their
1638 parents. Return current list of widgets if WLIST is empty."""
1639 if len(wlist) > 1:
1640 wlist = (wlist,) # Tk needs a list of windows here
1641 args = ('wm', 'colormapwindows', self._w) + wlist
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001642 if wlist:
1643 self.tk.call(args)
1644 else:
1645 return map(self._nametowidget, self.tk.splitlist(self.tk.call(args)))
Georg Brandl33cece02008-05-20 06:58:21 +00001646 colormapwindows = wm_colormapwindows
1647 def wm_command(self, value=None):
1648 """Store VALUE in WM_COMMAND property. It is the command
1649 which shall be used to invoke the application. Return current
1650 command if VALUE is None."""
1651 return self.tk.call('wm', 'command', self._w, value)
1652 command = wm_command
1653 def wm_deiconify(self):
1654 """Deiconify this widget. If it was never mapped it will not be mapped.
1655 On Windows it will raise this widget and give it the focus."""
1656 return self.tk.call('wm', 'deiconify', self._w)
1657 deiconify = wm_deiconify
1658 def wm_focusmodel(self, model=None):
1659 """Set focus model to MODEL. "active" means that this widget will claim
1660 the focus itself, "passive" means that the window manager shall give
1661 the focus. Return current focus model if MODEL is None."""
1662 return self.tk.call('wm', 'focusmodel', self._w, model)
1663 focusmodel = wm_focusmodel
1664 def wm_frame(self):
1665 """Return identifier for decorative frame of this widget if present."""
1666 return self.tk.call('wm', 'frame', self._w)
1667 frame = wm_frame
1668 def wm_geometry(self, newGeometry=None):
1669 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1670 current value if None is given."""
1671 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1672 geometry = wm_geometry
1673 def wm_grid(self,
1674 baseWidth=None, baseHeight=None,
1675 widthInc=None, heightInc=None):
1676 """Instruct the window manager that this widget shall only be
1677 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1678 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1679 number of grid units requested in Tk_GeometryRequest."""
1680 return self._getints(self.tk.call(
1681 'wm', 'grid', self._w,
1682 baseWidth, baseHeight, widthInc, heightInc))
1683 grid = wm_grid
1684 def wm_group(self, pathName=None):
1685 """Set the group leader widgets for related widgets to PATHNAME. Return
1686 the group leader of this widget if None is given."""
1687 return self.tk.call('wm', 'group', self._w, pathName)
1688 group = wm_group
1689 def wm_iconbitmap(self, bitmap=None, default=None):
1690 """Set bitmap for the iconified widget to BITMAP. Return
1691 the bitmap if None is given.
1692
1693 Under Windows, the DEFAULT parameter can be used to set the icon
1694 for the widget and any descendents that don't have an icon set
1695 explicitly. DEFAULT can be the relative path to a .ico file
1696 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1697 documentation for more information."""
1698 if default:
1699 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1700 else:
1701 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1702 iconbitmap = wm_iconbitmap
1703 def wm_iconify(self):
1704 """Display widget as icon."""
1705 return self.tk.call('wm', 'iconify', self._w)
1706 iconify = wm_iconify
1707 def wm_iconmask(self, bitmap=None):
1708 """Set mask for the icon bitmap of this widget. Return the
1709 mask if None is given."""
1710 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1711 iconmask = wm_iconmask
1712 def wm_iconname(self, newName=None):
1713 """Set the name of the icon for this widget. Return the name if
1714 None is given."""
1715 return self.tk.call('wm', 'iconname', self._w, newName)
1716 iconname = wm_iconname
1717 def wm_iconposition(self, x=None, y=None):
1718 """Set the position of the icon of this widget to X and Y. Return
1719 a tuple of the current values of X and X if None is given."""
1720 return self._getints(self.tk.call(
1721 'wm', 'iconposition', self._w, x, y))
1722 iconposition = wm_iconposition
1723 def wm_iconwindow(self, pathName=None):
1724 """Set widget PATHNAME to be displayed instead of icon. Return the current
1725 value if None is given."""
1726 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1727 iconwindow = wm_iconwindow
1728 def wm_maxsize(self, width=None, height=None):
1729 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1730 the values are given in grid units. Return the current values if None
1731 is given."""
1732 return self._getints(self.tk.call(
1733 'wm', 'maxsize', self._w, width, height))
1734 maxsize = wm_maxsize
1735 def wm_minsize(self, width=None, height=None):
1736 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1737 the values are given in grid units. Return the current values if None
1738 is given."""
1739 return self._getints(self.tk.call(
1740 'wm', 'minsize', self._w, width, height))
1741 minsize = wm_minsize
1742 def wm_overrideredirect(self, boolean=None):
1743 """Instruct the window manager to ignore this widget
1744 if BOOLEAN is given with 1. Return the current value if None
1745 is given."""
1746 return self._getboolean(self.tk.call(
1747 'wm', 'overrideredirect', self._w, boolean))
1748 overrideredirect = wm_overrideredirect
1749 def wm_positionfrom(self, who=None):
1750 """Instruct the window manager that the position of this widget shall
1751 be defined by the user if WHO is "user", and by its own policy if WHO is
1752 "program"."""
1753 return self.tk.call('wm', 'positionfrom', self._w, who)
1754 positionfrom = wm_positionfrom
1755 def wm_protocol(self, name=None, func=None):
1756 """Bind function FUNC to command NAME for this widget.
1757 Return the function bound to NAME if None is given. NAME could be
1758 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Brett Cannonff6868c2008-08-04 21:24:43 +00001759 if hasattr(func, '__call__'):
Georg Brandl33cece02008-05-20 06:58:21 +00001760 command = self._register(func)
1761 else:
1762 command = func
1763 return self.tk.call(
1764 'wm', 'protocol', self._w, name, command)
1765 protocol = wm_protocol
1766 def wm_resizable(self, width=None, height=None):
1767 """Instruct the window manager whether this width can be resized
1768 in WIDTH or HEIGHT. Both values are boolean values."""
1769 return self.tk.call('wm', 'resizable', self._w, width, height)
1770 resizable = wm_resizable
1771 def wm_sizefrom(self, who=None):
1772 """Instruct the window manager that the size of this widget shall
1773 be defined by the user if WHO is "user", and by its own policy if WHO is
1774 "program"."""
1775 return self.tk.call('wm', 'sizefrom', self._w, who)
1776 sizefrom = wm_sizefrom
1777 def wm_state(self, newstate=None):
1778 """Query or set the state of this widget as one of normal, icon,
1779 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1780 return self.tk.call('wm', 'state', self._w, newstate)
1781 state = wm_state
1782 def wm_title(self, string=None):
1783 """Set the title of this widget."""
1784 return self.tk.call('wm', 'title', self._w, string)
1785 title = wm_title
1786 def wm_transient(self, master=None):
1787 """Instruct the window manager that this widget is transient
1788 with regard to widget MASTER."""
1789 return self.tk.call('wm', 'transient', self._w, master)
1790 transient = wm_transient
1791 def wm_withdraw(self):
1792 """Withdraw this widget from the screen such that it is unmapped
1793 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1794 return self.tk.call('wm', 'withdraw', self._w)
1795 withdraw = wm_withdraw
1796
1797
1798class Tk(Misc, Wm):
1799 """Toplevel widget of Tk which represents mostly the main window
Ezio Melotti24b07bc2011-03-15 18:55:01 +02001800 of an application. It has an associated Tcl interpreter."""
Georg Brandl33cece02008-05-20 06:58:21 +00001801 _w = '.'
1802 def __init__(self, screenName=None, baseName=None, className='Tk',
1803 useTk=1, sync=0, use=None):
1804 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1805 be created. BASENAME will be used for the identification of the profile file (see
1806 readprofile).
1807 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1808 is the name of the widget class."""
1809 self.master = None
1810 self.children = {}
1811 self._tkloaded = 0
1812 # to avoid recursions in the getattr code in case of failure, we
1813 # ensure that self.tk is always _something_.
1814 self.tk = None
1815 if baseName is None:
Antoine Pitrouba7620c2013-08-01 22:25:12 +02001816 import os
Georg Brandl33cece02008-05-20 06:58:21 +00001817 baseName = os.path.basename(sys.argv[0])
1818 baseName, ext = os.path.splitext(baseName)
1819 if ext not in ('.py', '.pyc', '.pyo'):
1820 baseName = baseName + ext
1821 interactive = 0
1822 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
1823 if useTk:
1824 self._loadtk()
Antoine Pitrou7dddec42012-12-09 14:46:18 +01001825 if not sys.flags.ignore_environment:
1826 # Issue #16248: Honor the -E flag to avoid code injection.
1827 self.readprofile(baseName, className)
Georg Brandl33cece02008-05-20 06:58:21 +00001828 def loadtk(self):
1829 if not self._tkloaded:
1830 self.tk.loadtk()
1831 self._loadtk()
1832 def _loadtk(self):
1833 self._tkloaded = 1
1834 global _default_root
Georg Brandl33cece02008-05-20 06:58:21 +00001835 # Version sanity checks
1836 tk_version = self.tk.getvar('tk_version')
1837 if tk_version != _tkinter.TK_VERSION:
1838 raise RuntimeError, \
1839 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1840 % (_tkinter.TK_VERSION, tk_version)
1841 # Under unknown circumstances, tcl_version gets coerced to float
1842 tcl_version = str(self.tk.getvar('tcl_version'))
1843 if tcl_version != _tkinter.TCL_VERSION:
1844 raise RuntimeError, \
1845 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1846 % (_tkinter.TCL_VERSION, tcl_version)
1847 if TkVersion < 4.0:
1848 raise RuntimeError, \
1849 "Tk 4.0 or higher is required; found Tk %s" \
1850 % str(TkVersion)
1851 # Create and register the tkerror and exit commands
1852 # We need to inline parts of _register here, _ register
1853 # would register differently-named commands.
1854 if self._tclCommands is None:
1855 self._tclCommands = []
1856 self.tk.createcommand('tkerror', _tkerror)
1857 self.tk.createcommand('exit', _exit)
1858 self._tclCommands.append('tkerror')
1859 self._tclCommands.append('exit')
1860 if _support_default_root and not _default_root:
1861 _default_root = self
1862 self.protocol("WM_DELETE_WINDOW", self.destroy)
1863 def destroy(self):
1864 """Destroy this and all descendants widgets. This will
1865 end the application of this Tcl interpreter."""
1866 for c in self.children.values(): c.destroy()
1867 self.tk.call('destroy', self._w)
1868 Misc.destroy(self)
1869 global _default_root
1870 if _support_default_root and _default_root is self:
1871 _default_root = None
1872 def readprofile(self, baseName, className):
1873 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1874 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1875 such a file exists in the home directory."""
1876 import os
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00001877 if 'HOME' in os.environ: home = os.environ['HOME']
Georg Brandl33cece02008-05-20 06:58:21 +00001878 else: home = os.curdir
1879 class_tcl = os.path.join(home, '.%s.tcl' % className)
1880 class_py = os.path.join(home, '.%s.py' % className)
1881 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1882 base_py = os.path.join(home, '.%s.py' % baseName)
1883 dir = {'self': self}
Georg Brandl6634bf22008-05-20 07:13:37 +00001884 exec 'from Tkinter import *' in dir
Georg Brandl33cece02008-05-20 06:58:21 +00001885 if os.path.isfile(class_tcl):
1886 self.tk.call('source', class_tcl)
1887 if os.path.isfile(class_py):
1888 execfile(class_py, dir)
1889 if os.path.isfile(base_tcl):
1890 self.tk.call('source', base_tcl)
1891 if os.path.isfile(base_py):
1892 execfile(base_py, dir)
1893 def report_callback_exception(self, exc, val, tb):
Serhiy Storchaka2971c5e2014-09-14 21:17:16 +03001894 """Report callback exception on sys.stderr.
1895
1896 Applications may want to override this internal function, and
1897 should when sys.stderr is None."""
Georg Brandl33cece02008-05-20 06:58:21 +00001898 import traceback, sys
Serhiy Storchaka2971c5e2014-09-14 21:17:16 +03001899 print >>sys.stderr, "Exception in Tkinter callback"
Georg Brandl33cece02008-05-20 06:58:21 +00001900 sys.last_type = exc
1901 sys.last_value = val
1902 sys.last_traceback = tb
1903 traceback.print_exception(exc, val, tb)
1904 def __getattr__(self, attr):
1905 "Delegate attribute access to the interpreter object"
1906 return getattr(self.tk, attr)
1907
1908# Ideally, the classes Pack, Place and Grid disappear, the
1909# pack/place/grid methods are defined on the Widget class, and
1910# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1911# ...), with pack(), place() and grid() being short for
1912# pack_configure(), place_configure() and grid_columnconfigure(), and
1913# forget() being short for pack_forget(). As a practical matter, I'm
1914# afraid that there is too much code out there that may be using the
1915# Pack, Place or Grid class, so I leave them intact -- but only as
1916# backwards compatibility features. Also note that those methods that
1917# take a master as argument (e.g. pack_propagate) have been moved to
1918# the Misc class (which now incorporates all methods common between
1919# toplevel and interior widgets). Again, for compatibility, these are
1920# copied into the Pack, Place or Grid class.
1921
1922
1923def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1924 return Tk(screenName, baseName, className, useTk)
1925
1926class Pack:
1927 """Geometry manager Pack.
1928
1929 Base class to use the methods pack_* in every widget."""
1930 def pack_configure(self, cnf={}, **kw):
1931 """Pack a widget in the parent widget. Use as options:
1932 after=widget - pack it after you have packed widget
1933 anchor=NSEW (or subset) - position widget according to
1934 given direction
Georg Brandl7943a322008-05-29 07:18:49 +00001935 before=widget - pack it before you will pack widget
Georg Brandl33cece02008-05-20 06:58:21 +00001936 expand=bool - expand widget if parent size grows
1937 fill=NONE or X or Y or BOTH - fill widget if widget grows
1938 in=master - use master to contain this widget
Georg Brandl7943a322008-05-29 07:18:49 +00001939 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001940 ipadx=amount - add internal padding in x direction
1941 ipady=amount - add internal padding in y direction
1942 padx=amount - add padding in x direction
1943 pady=amount - add padding in y direction
1944 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1945 """
1946 self.tk.call(
1947 ('pack', 'configure', self._w)
1948 + self._options(cnf, kw))
1949 pack = configure = config = pack_configure
1950 def pack_forget(self):
1951 """Unmap this widget and do not use it for the packing order."""
1952 self.tk.call('pack', 'forget', self._w)
1953 forget = pack_forget
1954 def pack_info(self):
1955 """Return information about the packing options
1956 for this widget."""
Serhiy Storchakaceaf6822014-09-06 22:47:02 +03001957 d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
1958 if 'in' in d:
1959 d['in'] = self.nametowidget(d['in'])
1960 return d
Georg Brandl33cece02008-05-20 06:58:21 +00001961 info = pack_info
1962 propagate = pack_propagate = Misc.pack_propagate
1963 slaves = pack_slaves = Misc.pack_slaves
1964
1965class Place:
1966 """Geometry manager Place.
1967
1968 Base class to use the methods place_* in every widget."""
1969 def place_configure(self, cnf={}, **kw):
1970 """Place a widget in the parent widget. Use as options:
Georg Brandl7943a322008-05-29 07:18:49 +00001971 in=master - master relative to which the widget is placed
1972 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00001973 x=amount - locate anchor of this widget at position x of master
1974 y=amount - locate anchor of this widget at position y of master
1975 relx=amount - locate anchor of this widget between 0.0 and 1.0
1976 relative to width of master (1.0 is right edge)
Georg Brandl7943a322008-05-29 07:18:49 +00001977 rely=amount - locate anchor of this widget between 0.0 and 1.0
Georg Brandl33cece02008-05-20 06:58:21 +00001978 relative to height of master (1.0 is bottom edge)
Georg Brandl7943a322008-05-29 07:18:49 +00001979 anchor=NSEW (or subset) - position anchor according to given direction
Georg Brandl33cece02008-05-20 06:58:21 +00001980 width=amount - width of this widget in pixel
1981 height=amount - height of this widget in pixel
1982 relwidth=amount - width of this widget between 0.0 and 1.0
1983 relative to width of master (1.0 is the same width
Georg Brandl7943a322008-05-29 07:18:49 +00001984 as the master)
1985 relheight=amount - height of this widget between 0.0 and 1.0
Georg Brandl33cece02008-05-20 06:58:21 +00001986 relative to height of master (1.0 is the same
Georg Brandl7943a322008-05-29 07:18:49 +00001987 height as the master)
1988 bordermode="inside" or "outside" - whether to take border width of
1989 master widget into account
1990 """
Georg Brandl33cece02008-05-20 06:58:21 +00001991 self.tk.call(
1992 ('place', 'configure', self._w)
1993 + self._options(cnf, kw))
1994 place = configure = config = place_configure
1995 def place_forget(self):
1996 """Unmap this widget."""
1997 self.tk.call('place', 'forget', self._w)
1998 forget = place_forget
1999 def place_info(self):
2000 """Return information about the placing options
2001 for this widget."""
Serhiy Storchakaceaf6822014-09-06 22:47:02 +03002002 d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
2003 if 'in' in d:
2004 d['in'] = self.nametowidget(d['in'])
2005 return d
Georg Brandl33cece02008-05-20 06:58:21 +00002006 info = place_info
2007 slaves = place_slaves = Misc.place_slaves
2008
2009class Grid:
2010 """Geometry manager Grid.
2011
2012 Base class to use the methods grid_* in every widget."""
2013 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
2014 def grid_configure(self, cnf={}, **kw):
2015 """Position a widget in the parent widget in a grid. Use as options:
2016 column=number - use cell identified with given column (starting with 0)
2017 columnspan=number - this widget will span several columns
2018 in=master - use master to contain this widget
Georg Brandl7943a322008-05-29 07:18:49 +00002019 in_=master - see 'in' option description
Georg Brandl33cece02008-05-20 06:58:21 +00002020 ipadx=amount - add internal padding in x direction
2021 ipady=amount - add internal padding in y direction
2022 padx=amount - add padding in x direction
2023 pady=amount - add padding in y direction
2024 row=number - use cell identified with given row (starting with 0)
2025 rowspan=number - this widget will span several rows
2026 sticky=NSEW - if cell is larger on which sides will this
2027 widget stick to the cell boundary
2028 """
2029 self.tk.call(
2030 ('grid', 'configure', self._w)
2031 + self._options(cnf, kw))
2032 grid = configure = config = grid_configure
2033 bbox = grid_bbox = Misc.grid_bbox
2034 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
2035 def grid_forget(self):
2036 """Unmap this widget."""
2037 self.tk.call('grid', 'forget', self._w)
2038 forget = grid_forget
2039 def grid_remove(self):
2040 """Unmap this widget but remember the grid options."""
2041 self.tk.call('grid', 'remove', self._w)
2042 def grid_info(self):
2043 """Return information about the options
2044 for positioning this widget in a grid."""
Serhiy Storchakaceaf6822014-09-06 22:47:02 +03002045 d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
2046 if 'in' in d:
2047 d['in'] = self.nametowidget(d['in'])
2048 return d
Georg Brandl33cece02008-05-20 06:58:21 +00002049 info = grid_info
2050 location = grid_location = Misc.grid_location
2051 propagate = grid_propagate = Misc.grid_propagate
2052 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
2053 size = grid_size = Misc.grid_size
2054 slaves = grid_slaves = Misc.grid_slaves
2055
2056class BaseWidget(Misc):
2057 """Internal class."""
2058 def _setup(self, master, cnf):
2059 """Internal function. Sets up information about children."""
2060 if _support_default_root:
2061 global _default_root
2062 if not master:
2063 if not _default_root:
2064 _default_root = Tk()
2065 master = _default_root
2066 self.master = master
2067 self.tk = master.tk
2068 name = None
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002069 if 'name' in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002070 name = cnf['name']
2071 del cnf['name']
2072 if not name:
2073 name = repr(id(self))
2074 self._name = name
2075 if master._w=='.':
2076 self._w = '.' + name
2077 else:
2078 self._w = master._w + '.' + name
2079 self.children = {}
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002080 if self._name in self.master.children:
Georg Brandl33cece02008-05-20 06:58:21 +00002081 self.master.children[self._name].destroy()
2082 self.master.children[self._name] = self
2083 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2084 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2085 and appropriate options."""
2086 if kw:
2087 cnf = _cnfmerge((cnf, kw))
2088 self.widgetName = widgetName
2089 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotob9828f62008-11-03 18:03:06 +00002090 if self._tclCommands is None:
2091 self._tclCommands = []
Georg Brandl33cece02008-05-20 06:58:21 +00002092 classes = []
2093 for k in cnf.keys():
2094 if type(k) is ClassType:
2095 classes.append((k, cnf[k]))
2096 del cnf[k]
2097 self.tk.call(
2098 (widgetName, self._w) + extra + self._options(cnf))
2099 for k, v in classes:
2100 k.configure(self, v)
2101 def destroy(self):
2102 """Destroy this and all descendants widgets."""
2103 for c in self.children.values(): c.destroy()
2104 self.tk.call('destroy', self._w)
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002105 if self._name in self.master.children:
Georg Brandl33cece02008-05-20 06:58:21 +00002106 del self.master.children[self._name]
2107 Misc.destroy(self)
2108 def _do(self, name, args=()):
2109 # XXX Obsolete -- better use self.tk.call directly!
2110 return self.tk.call((self._w, name) + args)
2111
2112class Widget(BaseWidget, Pack, Place, Grid):
2113 """Internal class.
2114
2115 Base class for a widget which can be positioned with the geometry managers
2116 Pack, Place or Grid."""
2117 pass
2118
2119class Toplevel(BaseWidget, Wm):
2120 """Toplevel widget, e.g. for dialogs."""
2121 def __init__(self, master=None, cnf={}, **kw):
2122 """Construct a toplevel widget with the parent MASTER.
2123
2124 Valid resource names: background, bd, bg, borderwidth, class,
2125 colormap, container, cursor, height, highlightbackground,
2126 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2127 use, visual, width."""
2128 if kw:
2129 cnf = _cnfmerge((cnf, kw))
2130 extra = ()
2131 for wmkey in ['screen', 'class_', 'class', 'visual',
2132 'colormap']:
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002133 if wmkey in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002134 val = cnf[wmkey]
2135 # TBD: a hack needed because some keys
2136 # are not valid as keyword arguments
2137 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2138 else: opt = '-'+wmkey
2139 extra = extra + (opt, val)
2140 del cnf[wmkey]
2141 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2142 root = self._root()
2143 self.iconname(root.iconname())
2144 self.title(root.title())
2145 self.protocol("WM_DELETE_WINDOW", self.destroy)
2146
2147class Button(Widget):
2148 """Button widget."""
2149 def __init__(self, master=None, cnf={}, **kw):
2150 """Construct a button widget with the parent MASTER.
2151
2152 STANDARD OPTIONS
2153
2154 activebackground, activeforeground, anchor,
2155 background, bitmap, borderwidth, cursor,
2156 disabledforeground, font, foreground
2157 highlightbackground, highlightcolor,
2158 highlightthickness, image, justify,
2159 padx, pady, relief, repeatdelay,
2160 repeatinterval, takefocus, text,
2161 textvariable, underline, wraplength
2162
2163 WIDGET-SPECIFIC OPTIONS
2164
2165 command, compound, default, height,
2166 overrelief, state, width
2167 """
2168 Widget.__init__(self, master, 'button', cnf, kw)
2169
2170 def tkButtonEnter(self, *dummy):
2171 self.tk.call('tkButtonEnter', self._w)
2172
2173 def tkButtonLeave(self, *dummy):
2174 self.tk.call('tkButtonLeave', self._w)
2175
2176 def tkButtonDown(self, *dummy):
2177 self.tk.call('tkButtonDown', self._w)
2178
2179 def tkButtonUp(self, *dummy):
2180 self.tk.call('tkButtonUp', self._w)
2181
2182 def tkButtonInvoke(self, *dummy):
2183 self.tk.call('tkButtonInvoke', self._w)
2184
2185 def flash(self):
2186 """Flash the button.
2187
2188 This is accomplished by redisplaying
2189 the button several times, alternating between active and
2190 normal colors. At the end of the flash the button is left
2191 in the same normal/active state as when the command was
2192 invoked. This command is ignored if the button's state is
2193 disabled.
2194 """
2195 self.tk.call(self._w, 'flash')
2196
2197 def invoke(self):
2198 """Invoke the command associated with the button.
2199
2200 The return value is the return value from the command,
2201 or an empty string if there is no command associated with
2202 the button. This command is ignored if the button's state
2203 is disabled.
2204 """
2205 return self.tk.call(self._w, 'invoke')
2206
2207# Indices:
2208# XXX I don't like these -- take them away
2209def AtEnd():
2210 return 'end'
2211def AtInsert(*args):
2212 s = 'insert'
2213 for a in args:
2214 if a: s = s + (' ' + a)
2215 return s
2216def AtSelFirst():
2217 return 'sel.first'
2218def AtSelLast():
2219 return 'sel.last'
2220def At(x, y=None):
2221 if y is None:
2222 return '@%r' % (x,)
2223 else:
2224 return '@%r,%r' % (x, y)
2225
Guilherme Poloe45f0172009-08-14 14:36:45 +00002226class Canvas(Widget, XView, YView):
Georg Brandl33cece02008-05-20 06:58:21 +00002227 """Canvas widget to display graphical elements like lines or text."""
2228 def __init__(self, master=None, cnf={}, **kw):
2229 """Construct a canvas widget with the parent MASTER.
2230
2231 Valid resource names: background, bd, bg, borderwidth, closeenough,
2232 confine, cursor, height, highlightbackground, highlightcolor,
2233 highlightthickness, insertbackground, insertborderwidth,
2234 insertofftime, insertontime, insertwidth, offset, relief,
2235 scrollregion, selectbackground, selectborderwidth, selectforeground,
2236 state, takefocus, width, xscrollcommand, xscrollincrement,
2237 yscrollcommand, yscrollincrement."""
2238 Widget.__init__(self, master, 'canvas', cnf, kw)
2239 def addtag(self, *args):
2240 """Internal function."""
2241 self.tk.call((self._w, 'addtag') + args)
2242 def addtag_above(self, newtag, tagOrId):
2243 """Add tag NEWTAG to all items above TAGORID."""
2244 self.addtag(newtag, 'above', tagOrId)
2245 def addtag_all(self, newtag):
2246 """Add tag NEWTAG to all items."""
2247 self.addtag(newtag, 'all')
2248 def addtag_below(self, newtag, tagOrId):
2249 """Add tag NEWTAG to all items below TAGORID."""
2250 self.addtag(newtag, 'below', tagOrId)
2251 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2252 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2253 If several match take the top-most.
2254 All items closer than HALO are considered overlapping (all are
2255 closests). If START is specified the next below this tag is taken."""
2256 self.addtag(newtag, 'closest', x, y, halo, start)
2257 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2258 """Add tag NEWTAG to all items in the rectangle defined
2259 by X1,Y1,X2,Y2."""
2260 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2261 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2262 """Add tag NEWTAG to all items which overlap the rectangle
2263 defined by X1,Y1,X2,Y2."""
2264 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2265 def addtag_withtag(self, newtag, tagOrId):
2266 """Add tag NEWTAG to all items with TAGORID."""
2267 self.addtag(newtag, 'withtag', tagOrId)
2268 def bbox(self, *args):
2269 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2270 which encloses all items with tags specified as arguments."""
2271 return self._getints(
2272 self.tk.call((self._w, 'bbox') + args)) or None
2273 def tag_unbind(self, tagOrId, sequence, funcid=None):
2274 """Unbind for all items with TAGORID for event SEQUENCE the
2275 function identified with FUNCID."""
2276 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2277 if funcid:
2278 self.deletecommand(funcid)
2279 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2280 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
2281
2282 An additional boolean parameter ADD specifies whether FUNC will be
2283 called additionally to the other bound function or whether it will
2284 replace the previous function. See bind for the return value."""
2285 return self._bind((self._w, 'bind', tagOrId),
2286 sequence, func, add)
2287 def canvasx(self, screenx, gridspacing=None):
2288 """Return the canvas x coordinate of pixel position SCREENX rounded
2289 to nearest multiple of GRIDSPACING units."""
2290 return getdouble(self.tk.call(
2291 self._w, 'canvasx', screenx, gridspacing))
2292 def canvasy(self, screeny, gridspacing=None):
2293 """Return the canvas y coordinate of pixel position SCREENY rounded
2294 to nearest multiple of GRIDSPACING units."""
2295 return getdouble(self.tk.call(
2296 self._w, 'canvasy', screeny, gridspacing))
2297 def coords(self, *args):
2298 """Return a list of coordinates for the item given in ARGS."""
2299 # XXX Should use _flatten on args
2300 return map(getdouble,
2301 self.tk.splitlist(
2302 self.tk.call((self._w, 'coords') + args)))
2303 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2304 """Internal function."""
2305 args = _flatten(args)
2306 cnf = args[-1]
2307 if type(cnf) in (DictionaryType, TupleType):
2308 args = args[:-1]
2309 else:
2310 cnf = {}
2311 return getint(self.tk.call(
2312 self._w, 'create', itemType,
2313 *(args + self._options(cnf, kw))))
2314 def create_arc(self, *args, **kw):
2315 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2316 return self._create('arc', args, kw)
2317 def create_bitmap(self, *args, **kw):
2318 """Create bitmap with coordinates x1,y1."""
2319 return self._create('bitmap', args, kw)
2320 def create_image(self, *args, **kw):
2321 """Create image item with coordinates x1,y1."""
2322 return self._create('image', args, kw)
2323 def create_line(self, *args, **kw):
2324 """Create line with coordinates x1,y1,...,xn,yn."""
2325 return self._create('line', args, kw)
2326 def create_oval(self, *args, **kw):
2327 """Create oval with coordinates x1,y1,x2,y2."""
2328 return self._create('oval', args, kw)
2329 def create_polygon(self, *args, **kw):
2330 """Create polygon with coordinates x1,y1,...,xn,yn."""
2331 return self._create('polygon', args, kw)
2332 def create_rectangle(self, *args, **kw):
2333 """Create rectangle with coordinates x1,y1,x2,y2."""
2334 return self._create('rectangle', args, kw)
2335 def create_text(self, *args, **kw):
2336 """Create text with coordinates x1,y1."""
2337 return self._create('text', args, kw)
2338 def create_window(self, *args, **kw):
2339 """Create window with coordinates x1,y1,x2,y2."""
2340 return self._create('window', args, kw)
2341 def dchars(self, *args):
2342 """Delete characters of text items identified by tag or id in ARGS (possibly
2343 several times) from FIRST to LAST character (including)."""
2344 self.tk.call((self._w, 'dchars') + args)
2345 def delete(self, *args):
2346 """Delete items identified by all tag or ids contained in ARGS."""
2347 self.tk.call((self._w, 'delete') + args)
2348 def dtag(self, *args):
2349 """Delete tag or id given as last arguments in ARGS from items
2350 identified by first argument in ARGS."""
2351 self.tk.call((self._w, 'dtag') + args)
2352 def find(self, *args):
2353 """Internal function."""
2354 return self._getints(
2355 self.tk.call((self._w, 'find') + args)) or ()
2356 def find_above(self, tagOrId):
2357 """Return items above TAGORID."""
2358 return self.find('above', tagOrId)
2359 def find_all(self):
2360 """Return all items."""
2361 return self.find('all')
2362 def find_below(self, tagOrId):
2363 """Return all items below TAGORID."""
2364 return self.find('below', tagOrId)
2365 def find_closest(self, x, y, halo=None, start=None):
2366 """Return item which is closest to pixel at X, Y.
2367 If several match take the top-most.
2368 All items closer than HALO are considered overlapping (all are
Vijay Kumarf31f2252017-05-23 11:46:27 +05302369 closest). If START is specified the next below this tag is taken."""
Georg Brandl33cece02008-05-20 06:58:21 +00002370 return self.find('closest', x, y, halo, start)
2371 def find_enclosed(self, x1, y1, x2, y2):
2372 """Return all items in rectangle defined
2373 by X1,Y1,X2,Y2."""
2374 return self.find('enclosed', x1, y1, x2, y2)
2375 def find_overlapping(self, x1, y1, x2, y2):
2376 """Return all items which overlap the rectangle
2377 defined by X1,Y1,X2,Y2."""
2378 return self.find('overlapping', x1, y1, x2, y2)
2379 def find_withtag(self, tagOrId):
2380 """Return all items with TAGORID."""
2381 return self.find('withtag', tagOrId)
2382 def focus(self, *args):
2383 """Set focus to the first item specified in ARGS."""
2384 return self.tk.call((self._w, 'focus') + args)
2385 def gettags(self, *args):
2386 """Return tags associated with the first item specified in ARGS."""
2387 return self.tk.splitlist(
2388 self.tk.call((self._w, 'gettags') + args))
2389 def icursor(self, *args):
2390 """Set cursor at position POS in the item identified by TAGORID.
2391 In ARGS TAGORID must be first."""
2392 self.tk.call((self._w, 'icursor') + args)
2393 def index(self, *args):
2394 """Return position of cursor as integer in item specified in ARGS."""
2395 return getint(self.tk.call((self._w, 'index') + args))
2396 def insert(self, *args):
2397 """Insert TEXT in item TAGORID at position POS. ARGS must
2398 be TAGORID POS TEXT."""
2399 self.tk.call((self._w, 'insert') + args)
2400 def itemcget(self, tagOrId, option):
2401 """Return the resource value for an OPTION for item TAGORID."""
2402 return self.tk.call(
2403 (self._w, 'itemcget') + (tagOrId, '-'+option))
2404 def itemconfigure(self, tagOrId, cnf=None, **kw):
2405 """Configure resources of an item TAGORID.
2406
2407 The values for resources are specified as keyword
2408 arguments. To get an overview about
2409 the allowed keyword arguments call the method without arguments.
2410 """
2411 return self._configure(('itemconfigure', tagOrId), cnf, kw)
2412 itemconfig = itemconfigure
2413 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2414 # so the preferred name for them is tag_lower, tag_raise
2415 # (similar to tag_bind, and similar to the Text widget);
2416 # unfortunately can't delete the old ones yet (maybe in 1.6)
2417 def tag_lower(self, *args):
2418 """Lower an item TAGORID given in ARGS
2419 (optional below another item)."""
2420 self.tk.call((self._w, 'lower') + args)
2421 lower = tag_lower
2422 def move(self, *args):
2423 """Move an item TAGORID given in ARGS."""
2424 self.tk.call((self._w, 'move') + args)
2425 def postscript(self, cnf={}, **kw):
2426 """Print the contents of the canvas to a postscript
2427 file. Valid options: colormap, colormode, file, fontmap,
2428 height, pageanchor, pageheight, pagewidth, pagex, pagey,
Vijay Kumarf31f2252017-05-23 11:46:27 +05302429 rotate, width, x, y."""
Georg Brandl33cece02008-05-20 06:58:21 +00002430 return self.tk.call((self._w, 'postscript') +
2431 self._options(cnf, kw))
2432 def tag_raise(self, *args):
2433 """Raise an item TAGORID given in ARGS
2434 (optional above another item)."""
2435 self.tk.call((self._w, 'raise') + args)
2436 lift = tkraise = tag_raise
2437 def scale(self, *args):
2438 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2439 self.tk.call((self._w, 'scale') + args)
2440 def scan_mark(self, x, y):
2441 """Remember the current X, Y coordinates."""
2442 self.tk.call(self._w, 'scan', 'mark', x, y)
2443 def scan_dragto(self, x, y, gain=10):
2444 """Adjust the view of the canvas to GAIN times the
2445 difference between X and Y and the coordinates given in
2446 scan_mark."""
2447 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
2448 def select_adjust(self, tagOrId, index):
2449 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2450 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2451 def select_clear(self):
2452 """Clear the selection if it is in this widget."""
2453 self.tk.call(self._w, 'select', 'clear')
2454 def select_from(self, tagOrId, index):
2455 """Set the fixed end of a selection in item TAGORID to INDEX."""
2456 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2457 def select_item(self):
2458 """Return the item which has the selection."""
2459 return self.tk.call(self._w, 'select', 'item') or None
2460 def select_to(self, tagOrId, index):
2461 """Set the variable end of a selection in item TAGORID to INDEX."""
2462 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2463 def type(self, tagOrId):
2464 """Return the type of the item TAGORID."""
2465 return self.tk.call(self._w, 'type', tagOrId) or None
Georg Brandl33cece02008-05-20 06:58:21 +00002466
2467class Checkbutton(Widget):
2468 """Checkbutton widget which is either in on- or off-state."""
2469 def __init__(self, master=None, cnf={}, **kw):
2470 """Construct a checkbutton widget with the parent MASTER.
2471
2472 Valid resource names: activebackground, activeforeground, anchor,
2473 background, bd, bg, bitmap, borderwidth, command, cursor,
2474 disabledforeground, fg, font, foreground, height,
2475 highlightbackground, highlightcolor, highlightthickness, image,
2476 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2477 selectcolor, selectimage, state, takefocus, text, textvariable,
2478 underline, variable, width, wraplength."""
2479 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2480 def deselect(self):
2481 """Put the button in off-state."""
2482 self.tk.call(self._w, 'deselect')
2483 def flash(self):
2484 """Flash the button."""
2485 self.tk.call(self._w, 'flash')
2486 def invoke(self):
2487 """Toggle the button and invoke a command if given as resource."""
2488 return self.tk.call(self._w, 'invoke')
2489 def select(self):
2490 """Put the button in on-state."""
2491 self.tk.call(self._w, 'select')
2492 def toggle(self):
2493 """Toggle the button."""
2494 self.tk.call(self._w, 'toggle')
2495
Guilherme Poloe45f0172009-08-14 14:36:45 +00002496class Entry(Widget, XView):
Martin Panter53ae0ba2016-02-10 05:44:01 +00002497 """Entry widget which allows displaying simple text."""
Georg Brandl33cece02008-05-20 06:58:21 +00002498 def __init__(self, master=None, cnf={}, **kw):
2499 """Construct an entry widget with the parent MASTER.
2500
2501 Valid resource names: background, bd, bg, borderwidth, cursor,
2502 exportselection, fg, font, foreground, highlightbackground,
2503 highlightcolor, highlightthickness, insertbackground,
2504 insertborderwidth, insertofftime, insertontime, insertwidth,
2505 invalidcommand, invcmd, justify, relief, selectbackground,
2506 selectborderwidth, selectforeground, show, state, takefocus,
2507 textvariable, validate, validatecommand, vcmd, width,
2508 xscrollcommand."""
2509 Widget.__init__(self, master, 'entry', cnf, kw)
2510 def delete(self, first, last=None):
2511 """Delete text from FIRST to LAST (not included)."""
2512 self.tk.call(self._w, 'delete', first, last)
2513 def get(self):
2514 """Return the text."""
2515 return self.tk.call(self._w, 'get')
2516 def icursor(self, index):
2517 """Insert cursor at INDEX."""
2518 self.tk.call(self._w, 'icursor', index)
2519 def index(self, index):
2520 """Return position of cursor."""
2521 return getint(self.tk.call(
2522 self._w, 'index', index))
2523 def insert(self, index, string):
2524 """Insert STRING at INDEX."""
2525 self.tk.call(self._w, 'insert', index, string)
2526 def scan_mark(self, x):
2527 """Remember the current X, Y coordinates."""
2528 self.tk.call(self._w, 'scan', 'mark', x)
2529 def scan_dragto(self, x):
2530 """Adjust the view of the canvas to 10 times the
2531 difference between X and Y and the coordinates given in
2532 scan_mark."""
2533 self.tk.call(self._w, 'scan', 'dragto', x)
2534 def selection_adjust(self, index):
2535 """Adjust the end of the selection near the cursor to INDEX."""
2536 self.tk.call(self._w, 'selection', 'adjust', index)
2537 select_adjust = selection_adjust
2538 def selection_clear(self):
2539 """Clear the selection if it is in this widget."""
2540 self.tk.call(self._w, 'selection', 'clear')
2541 select_clear = selection_clear
2542 def selection_from(self, index):
2543 """Set the fixed end of a selection to INDEX."""
2544 self.tk.call(self._w, 'selection', 'from', index)
2545 select_from = selection_from
2546 def selection_present(self):
Guilherme Polo75e1f992009-08-14 14:43:43 +00002547 """Return True if there are characters selected in the entry, False
2548 otherwise."""
Georg Brandl33cece02008-05-20 06:58:21 +00002549 return self.tk.getboolean(
2550 self.tk.call(self._w, 'selection', 'present'))
2551 select_present = selection_present
2552 def selection_range(self, start, end):
2553 """Set the selection from START to END (not included)."""
2554 self.tk.call(self._w, 'selection', 'range', start, end)
2555 select_range = selection_range
2556 def selection_to(self, index):
2557 """Set the variable end of a selection to INDEX."""
2558 self.tk.call(self._w, 'selection', 'to', index)
2559 select_to = selection_to
Georg Brandl33cece02008-05-20 06:58:21 +00002560
2561class Frame(Widget):
2562 """Frame widget which may contain other widgets and can have a 3D border."""
2563 def __init__(self, master=None, cnf={}, **kw):
2564 """Construct a frame widget with the parent MASTER.
2565
2566 Valid resource names: background, bd, bg, borderwidth, class,
2567 colormap, container, cursor, height, highlightbackground,
2568 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2569 cnf = _cnfmerge((cnf, kw))
2570 extra = ()
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002571 if 'class_' in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002572 extra = ('-class', cnf['class_'])
2573 del cnf['class_']
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00002574 elif 'class' in cnf:
Georg Brandl33cece02008-05-20 06:58:21 +00002575 extra = ('-class', cnf['class'])
2576 del cnf['class']
2577 Widget.__init__(self, master, 'frame', cnf, {}, extra)
2578
2579class Label(Widget):
2580 """Label widget which can display text and bitmaps."""
2581 def __init__(self, master=None, cnf={}, **kw):
2582 """Construct a label widget with the parent MASTER.
2583
2584 STANDARD OPTIONS
2585
2586 activebackground, activeforeground, anchor,
2587 background, bitmap, borderwidth, cursor,
2588 disabledforeground, font, foreground,
2589 highlightbackground, highlightcolor,
2590 highlightthickness, image, justify,
2591 padx, pady, relief, takefocus, text,
2592 textvariable, underline, wraplength
2593
2594 WIDGET-SPECIFIC OPTIONS
2595
2596 height, state, width
2597
2598 """
2599 Widget.__init__(self, master, 'label', cnf, kw)
2600
Guilherme Poloe45f0172009-08-14 14:36:45 +00002601class Listbox(Widget, XView, YView):
Georg Brandl33cece02008-05-20 06:58:21 +00002602 """Listbox widget which can display a list of strings."""
2603 def __init__(self, master=None, cnf={}, **kw):
2604 """Construct a listbox widget with the parent MASTER.
2605
2606 Valid resource names: background, bd, bg, borderwidth, cursor,
2607 exportselection, fg, font, foreground, height, highlightbackground,
2608 highlightcolor, highlightthickness, relief, selectbackground,
2609 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2610 width, xscrollcommand, yscrollcommand, listvariable."""
2611 Widget.__init__(self, master, 'listbox', cnf, kw)
2612 def activate(self, index):
2613 """Activate item identified by INDEX."""
2614 self.tk.call(self._w, 'activate', index)
Serhiy Storchakaf94686f2014-06-02 21:30:53 +03002615 def bbox(self, index):
Georg Brandl33cece02008-05-20 06:58:21 +00002616 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
Serhiy Storchakaf94686f2014-06-02 21:30:53 +03002617 which encloses the item identified by the given index."""
2618 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
Georg Brandl33cece02008-05-20 06:58:21 +00002619 def curselection(self):
Serhiy Storchakaf94686f2014-06-02 21:30:53 +03002620 """Return the indices of currently selected item."""
2621 return self._getints(self.tk.call(self._w, 'curselection')) or ()
Georg Brandl33cece02008-05-20 06:58:21 +00002622 def delete(self, first, last=None):
Serhiy Storchaka417367a2014-06-02 16:50:03 +03002623 """Delete items from FIRST to LAST (included)."""
Georg Brandl33cece02008-05-20 06:58:21 +00002624 self.tk.call(self._w, 'delete', first, last)
2625 def get(self, first, last=None):
Serhiy Storchaka417367a2014-06-02 16:50:03 +03002626 """Get list of items from FIRST to LAST (included)."""
Serhiy Storchakaf94686f2014-06-02 21:30:53 +03002627 if last is not None:
Georg Brandl33cece02008-05-20 06:58:21 +00002628 return self.tk.splitlist(self.tk.call(
2629 self._w, 'get', first, last))
2630 else:
2631 return self.tk.call(self._w, 'get', first)
2632 def index(self, index):
2633 """Return index of item identified with INDEX."""
2634 i = self.tk.call(self._w, 'index', index)
2635 if i == 'none': return None
2636 return getint(i)
2637 def insert(self, index, *elements):
2638 """Insert ELEMENTS at INDEX."""
2639 self.tk.call((self._w, 'insert', index) + elements)
2640 def nearest(self, y):
2641 """Get index of item which is nearest to y coordinate Y."""
2642 return getint(self.tk.call(
2643 self._w, 'nearest', y))
2644 def scan_mark(self, x, y):
2645 """Remember the current X, Y coordinates."""
2646 self.tk.call(self._w, 'scan', 'mark', x, y)
2647 def scan_dragto(self, x, y):
2648 """Adjust the view of the listbox to 10 times the
2649 difference between X and Y and the coordinates given in
2650 scan_mark."""
2651 self.tk.call(self._w, 'scan', 'dragto', x, y)
2652 def see(self, index):
2653 """Scroll such that INDEX is visible."""
2654 self.tk.call(self._w, 'see', index)
2655 def selection_anchor(self, index):
2656 """Set the fixed end oft the selection to INDEX."""
2657 self.tk.call(self._w, 'selection', 'anchor', index)
2658 select_anchor = selection_anchor
2659 def selection_clear(self, first, last=None):
Serhiy Storchaka417367a2014-06-02 16:50:03 +03002660 """Clear the selection from FIRST to LAST (included)."""
Georg Brandl33cece02008-05-20 06:58:21 +00002661 self.tk.call(self._w,
2662 'selection', 'clear', first, last)
2663 select_clear = selection_clear
2664 def selection_includes(self, index):
2665 """Return 1 if INDEX is part of the selection."""
2666 return self.tk.getboolean(self.tk.call(
2667 self._w, 'selection', 'includes', index))
2668 select_includes = selection_includes
2669 def selection_set(self, first, last=None):
Serhiy Storchaka417367a2014-06-02 16:50:03 +03002670 """Set the selection from FIRST to LAST (included) without
Georg Brandl33cece02008-05-20 06:58:21 +00002671 changing the currently selected elements."""
2672 self.tk.call(self._w, 'selection', 'set', first, last)
2673 select_set = selection_set
2674 def size(self):
2675 """Return the number of elements in the listbox."""
2676 return getint(self.tk.call(self._w, 'size'))
Georg Brandl33cece02008-05-20 06:58:21 +00002677 def itemcget(self, index, option):
2678 """Return the resource value for an ITEM and an OPTION."""
2679 return self.tk.call(
2680 (self._w, 'itemcget') + (index, '-'+option))
2681 def itemconfigure(self, index, cnf=None, **kw):
2682 """Configure resources of an ITEM.
2683
2684 The values for resources are specified as keyword arguments.
2685 To get an overview about the allowed keyword arguments
2686 call the method without arguments.
2687 Valid resource names: background, bg, foreground, fg,
2688 selectbackground, selectforeground."""
2689 return self._configure(('itemconfigure', index), cnf, kw)
2690 itemconfig = itemconfigure
2691
2692class Menu(Widget):
Martin Panter53ae0ba2016-02-10 05:44:01 +00002693 """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
Georg Brandl33cece02008-05-20 06:58:21 +00002694 def __init__(self, master=None, cnf={}, **kw):
2695 """Construct menu widget with the parent MASTER.
2696
2697 Valid resource names: activebackground, activeborderwidth,
2698 activeforeground, background, bd, bg, borderwidth, cursor,
2699 disabledforeground, fg, font, foreground, postcommand, relief,
2700 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2701 Widget.__init__(self, master, 'menu', cnf, kw)
2702 def tk_bindForTraversal(self):
Serhiy Storchaka2ce9ddd2014-07-25 12:23:08 +03002703 # obsolete since Tk 4.0
2704 import warnings
2705 warnings.warn('tk_bindForTraversal() does nothing and '
2706 'will be removed in 3.6',
2707 DeprecationWarning, stacklevel=2)
Georg Brandl33cece02008-05-20 06:58:21 +00002708 def tk_mbPost(self):
2709 self.tk.call('tk_mbPost', self._w)
2710 def tk_mbUnpost(self):
2711 self.tk.call('tk_mbUnpost')
2712 def tk_traverseToMenu(self, char):
2713 self.tk.call('tk_traverseToMenu', self._w, char)
2714 def tk_traverseWithinMenu(self, char):
2715 self.tk.call('tk_traverseWithinMenu', self._w, char)
2716 def tk_getMenuButtons(self):
2717 return self.tk.call('tk_getMenuButtons', self._w)
2718 def tk_nextMenu(self, count):
2719 self.tk.call('tk_nextMenu', count)
2720 def tk_nextMenuEntry(self, count):
2721 self.tk.call('tk_nextMenuEntry', count)
2722 def tk_invokeMenu(self):
2723 self.tk.call('tk_invokeMenu', self._w)
2724 def tk_firstMenu(self):
2725 self.tk.call('tk_firstMenu', self._w)
2726 def tk_mbButtonDown(self):
2727 self.tk.call('tk_mbButtonDown', self._w)
2728 def tk_popup(self, x, y, entry=""):
2729 """Post the menu at position X,Y with entry ENTRY."""
2730 self.tk.call('tk_popup', self._w, x, y, entry)
2731 def activate(self, index):
2732 """Activate entry at INDEX."""
2733 self.tk.call(self._w, 'activate', index)
2734 def add(self, itemType, cnf={}, **kw):
2735 """Internal function."""
2736 self.tk.call((self._w, 'add', itemType) +
2737 self._options(cnf, kw))
2738 def add_cascade(self, cnf={}, **kw):
2739 """Add hierarchical menu item."""
2740 self.add('cascade', cnf or kw)
2741 def add_checkbutton(self, cnf={}, **kw):
2742 """Add checkbutton menu item."""
2743 self.add('checkbutton', cnf or kw)
2744 def add_command(self, cnf={}, **kw):
2745 """Add command menu item."""
2746 self.add('command', cnf or kw)
2747 def add_radiobutton(self, cnf={}, **kw):
2748 """Addd radio menu item."""
2749 self.add('radiobutton', cnf or kw)
2750 def add_separator(self, cnf={}, **kw):
2751 """Add separator."""
2752 self.add('separator', cnf or kw)
2753 def insert(self, index, itemType, cnf={}, **kw):
2754 """Internal function."""
2755 self.tk.call((self._w, 'insert', index, itemType) +
2756 self._options(cnf, kw))
2757 def insert_cascade(self, index, cnf={}, **kw):
2758 """Add hierarchical menu item at INDEX."""
2759 self.insert(index, 'cascade', cnf or kw)
2760 def insert_checkbutton(self, index, cnf={}, **kw):
2761 """Add checkbutton menu item at INDEX."""
2762 self.insert(index, 'checkbutton', cnf or kw)
2763 def insert_command(self, index, cnf={}, **kw):
2764 """Add command menu item at INDEX."""
2765 self.insert(index, 'command', cnf or kw)
2766 def insert_radiobutton(self, index, cnf={}, **kw):
2767 """Addd radio menu item at INDEX."""
2768 self.insert(index, 'radiobutton', cnf or kw)
2769 def insert_separator(self, index, cnf={}, **kw):
2770 """Add separator at INDEX."""
2771 self.insert(index, 'separator', cnf or kw)
2772 def delete(self, index1, index2=None):
Hirokazu Yamamotob9828f62008-11-03 18:03:06 +00002773 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies14646332008-08-10 11:01:53 +00002774 if index2 is None:
2775 index2 = index1
Hirokazu Yamamotob9828f62008-11-03 18:03:06 +00002776
2777 num_index1, num_index2 = self.index(index1), self.index(index2)
2778 if (num_index1 is None) or (num_index2 is None):
2779 num_index1, num_index2 = 0, -1
2780
2781 for i in range(num_index1, num_index2 + 1):
2782 if 'command' in self.entryconfig(i):
2783 c = str(self.entrycget(i, 'command'))
2784 if c:
2785 self.deletecommand(c)
Georg Brandl33cece02008-05-20 06:58:21 +00002786 self.tk.call(self._w, 'delete', index1, index2)
Georg Brandl33cece02008-05-20 06:58:21 +00002787 def entrycget(self, index, option):
Serhiy Storchaka9a118f12016-04-17 09:37:36 +03002788 """Return the resource value of a menu item for OPTION at INDEX."""
Georg Brandl33cece02008-05-20 06:58:21 +00002789 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2790 def entryconfigure(self, index, cnf=None, **kw):
2791 """Configure a menu item at INDEX."""
2792 return self._configure(('entryconfigure', index), cnf, kw)
2793 entryconfig = entryconfigure
2794 def index(self, index):
2795 """Return the index of a menu item identified by INDEX."""
2796 i = self.tk.call(self._w, 'index', index)
2797 if i == 'none': return None
2798 return getint(i)
2799 def invoke(self, index):
2800 """Invoke a menu item identified by INDEX and execute
2801 the associated command."""
2802 return self.tk.call(self._w, 'invoke', index)
2803 def post(self, x, y):
2804 """Display a menu at position X,Y."""
2805 self.tk.call(self._w, 'post', x, y)
2806 def type(self, index):
2807 """Return the type of the menu item at INDEX."""
2808 return self.tk.call(self._w, 'type', index)
2809 def unpost(self):
2810 """Unmap a menu."""
2811 self.tk.call(self._w, 'unpost')
2812 def yposition(self, index):
2813 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2814 return getint(self.tk.call(
2815 self._w, 'yposition', index))
2816
2817class Menubutton(Widget):
2818 """Menubutton widget, obsolete since Tk8.0."""
2819 def __init__(self, master=None, cnf={}, **kw):
2820 Widget.__init__(self, master, 'menubutton', cnf, kw)
2821
2822class Message(Widget):
2823 """Message widget to display multiline text. Obsolete since Label does it too."""
2824 def __init__(self, master=None, cnf={}, **kw):
2825 Widget.__init__(self, master, 'message', cnf, kw)
2826
2827class Radiobutton(Widget):
2828 """Radiobutton widget which shows only one of several buttons in on-state."""
2829 def __init__(self, master=None, cnf={}, **kw):
2830 """Construct a radiobutton widget with the parent MASTER.
2831
2832 Valid resource names: activebackground, activeforeground, anchor,
2833 background, bd, bg, bitmap, borderwidth, command, cursor,
2834 disabledforeground, fg, font, foreground, height,
2835 highlightbackground, highlightcolor, highlightthickness, image,
2836 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2837 state, takefocus, text, textvariable, underline, value, variable,
2838 width, wraplength."""
2839 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2840 def deselect(self):
2841 """Put the button in off-state."""
2842
2843 self.tk.call(self._w, 'deselect')
2844 def flash(self):
2845 """Flash the button."""
2846 self.tk.call(self._w, 'flash')
2847 def invoke(self):
2848 """Toggle the button and invoke a command if given as resource."""
2849 return self.tk.call(self._w, 'invoke')
2850 def select(self):
2851 """Put the button in on-state."""
2852 self.tk.call(self._w, 'select')
2853
2854class Scale(Widget):
2855 """Scale widget which can display a numerical scale."""
2856 def __init__(self, master=None, cnf={}, **kw):
2857 """Construct a scale widget with the parent MASTER.
2858
2859 Valid resource names: activebackground, background, bigincrement, bd,
2860 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2861 highlightbackground, highlightcolor, highlightthickness, label,
2862 length, orient, relief, repeatdelay, repeatinterval, resolution,
2863 showvalue, sliderlength, sliderrelief, state, takefocus,
2864 tickinterval, to, troughcolor, variable, width."""
2865 Widget.__init__(self, master, 'scale', cnf, kw)
2866 def get(self):
2867 """Get the current value as integer or float."""
2868 value = self.tk.call(self._w, 'get')
2869 try:
2870 return getint(value)
2871 except ValueError:
2872 return getdouble(value)
2873 def set(self, value):
2874 """Set the value to VALUE."""
2875 self.tk.call(self._w, 'set', value)
2876 def coords(self, value=None):
2877 """Return a tuple (X,Y) of the point along the centerline of the
2878 trough that corresponds to VALUE or the current value if None is
2879 given."""
2880
2881 return self._getints(self.tk.call(self._w, 'coords', value))
2882 def identify(self, x, y):
2883 """Return where the point X,Y lies. Valid return values are "slider",
2884 "though1" and "though2"."""
2885 return self.tk.call(self._w, 'identify', x, y)
2886
2887class Scrollbar(Widget):
2888 """Scrollbar widget which displays a slider at a certain position."""
2889 def __init__(self, master=None, cnf={}, **kw):
2890 """Construct a scrollbar widget with the parent MASTER.
2891
2892 Valid resource names: activebackground, activerelief,
2893 background, bd, bg, borderwidth, command, cursor,
2894 elementborderwidth, highlightbackground,
2895 highlightcolor, highlightthickness, jump, orient,
2896 relief, repeatdelay, repeatinterval, takefocus,
2897 troughcolor, width."""
2898 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2899 def activate(self, index):
2900 """Display the element at INDEX with activebackground and activerelief.
2901 INDEX can be "arrow1","slider" or "arrow2"."""
2902 self.tk.call(self._w, 'activate', index)
2903 def delta(self, deltax, deltay):
2904 """Return the fractional change of the scrollbar setting if it
2905 would be moved by DELTAX or DELTAY pixels."""
2906 return getdouble(
2907 self.tk.call(self._w, 'delta', deltax, deltay))
2908 def fraction(self, x, y):
2909 """Return the fractional value which corresponds to a slider
2910 position of X,Y."""
2911 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2912 def identify(self, x, y):
2913 """Return the element under position X,Y as one of
2914 "arrow1","slider","arrow2" or ""."""
2915 return self.tk.call(self._w, 'identify', x, y)
2916 def get(self):
2917 """Return the current fractional values (upper and lower end)
2918 of the slider position."""
2919 return self._getdoubles(self.tk.call(self._w, 'get'))
2920 def set(self, *args):
2921 """Set the fractional values of the slider position (upper and
2922 lower ends as value between 0 and 1)."""
2923 self.tk.call((self._w, 'set') + args)
2924
2925
2926
Guilherme Poloe45f0172009-08-14 14:36:45 +00002927class Text(Widget, XView, YView):
Georg Brandl33cece02008-05-20 06:58:21 +00002928 """Text widget which can display text in various forms."""
2929 def __init__(self, master=None, cnf={}, **kw):
2930 """Construct a text widget with the parent MASTER.
2931
2932 STANDARD OPTIONS
2933
2934 background, borderwidth, cursor,
2935 exportselection, font, foreground,
2936 highlightbackground, highlightcolor,
2937 highlightthickness, insertbackground,
2938 insertborderwidth, insertofftime,
2939 insertontime, insertwidth, padx, pady,
2940 relief, selectbackground,
2941 selectborderwidth, selectforeground,
2942 setgrid, takefocus,
2943 xscrollcommand, yscrollcommand,
2944
2945 WIDGET-SPECIFIC OPTIONS
2946
2947 autoseparators, height, maxundo,
2948 spacing1, spacing2, spacing3,
2949 state, tabs, undo, width, wrap,
2950
2951 """
2952 Widget.__init__(self, master, 'text', cnf, kw)
2953 def bbox(self, *args):
2954 """Return a tuple of (x,y,width,height) which gives the bounding
2955 box of the visible part of the character at the index in ARGS."""
2956 return self._getints(
2957 self.tk.call((self._w, 'bbox') + args)) or None
2958 def tk_textSelectTo(self, index):
2959 self.tk.call('tk_textSelectTo', self._w, index)
2960 def tk_textBackspace(self):
2961 self.tk.call('tk_textBackspace', self._w)
2962 def tk_textIndexCloser(self, a, b, c):
2963 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2964 def tk_textResetAnchor(self, index):
2965 self.tk.call('tk_textResetAnchor', self._w, index)
2966 def compare(self, index1, op, index2):
2967 """Return whether between index INDEX1 and index INDEX2 the
2968 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2969 return self.tk.getboolean(self.tk.call(
2970 self._w, 'compare', index1, op, index2))
2971 def debug(self, boolean=None):
2972 """Turn on the internal consistency checks of the B-Tree inside the text
2973 widget according to BOOLEAN."""
Serhiy Storchaka31b9c842013-11-03 14:28:29 +02002974 if boolean is None:
Serhiy Storchaka2bca9de2014-01-11 13:12:58 +02002975 return self.tk.getboolean(self.tk.call(self._w, 'debug'))
Serhiy Storchaka31b9c842013-11-03 14:28:29 +02002976 self.tk.call(self._w, 'debug', boolean)
Georg Brandl33cece02008-05-20 06:58:21 +00002977 def delete(self, index1, index2=None):
2978 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2979 self.tk.call(self._w, 'delete', index1, index2)
2980 def dlineinfo(self, index):
2981 """Return tuple (x,y,width,height,baseline) giving the bounding box
2982 and baseline position of the visible part of the line containing
2983 the character at INDEX."""
2984 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
2985 def dump(self, index1, index2=None, command=None, **kw):
2986 """Return the contents of the widget between index1 and index2.
2987
2988 The type of contents returned in filtered based on the keyword
2989 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2990 given and true, then the corresponding items are returned. The result
2991 is a list of triples of the form (key, value, index). If none of the
2992 keywords are true then 'all' is used by default.
2993
2994 If the 'command' argument is given, it is called once for each element
2995 of the list of triples, with the values of each triple serving as the
2996 arguments to the function. In this case the list is not returned."""
2997 args = []
2998 func_name = None
2999 result = None
3000 if not command:
3001 # Never call the dump command without the -command flag, since the
3002 # output could involve Tcl quoting and would be a pain to parse
3003 # right. Instead just set the command to build a list of triples
3004 # as if we had done the parsing.
3005 result = []
3006 def append_triple(key, value, index, result=result):
3007 result.append((key, value, index))
3008 command = append_triple
3009 try:
3010 if not isinstance(command, str):
3011 func_name = command = self._register(command)
3012 args += ["-command", command]
3013 for key in kw:
3014 if kw[key]: args.append("-" + key)
3015 args.append(index1)
3016 if index2:
3017 args.append(index2)
3018 self.tk.call(self._w, "dump", *args)
3019 return result
3020 finally:
3021 if func_name:
3022 self.deletecommand(func_name)
3023
3024 ## new in tk8.4
3025 def edit(self, *args):
3026 """Internal method
3027
3028 This method controls the undo mechanism and
3029 the modified flag. The exact behavior of the
3030 command depends on the option argument that
3031 follows the edit argument. The following forms
3032 of the command are currently supported:
3033
3034 edit_modified, edit_redo, edit_reset, edit_separator
3035 and edit_undo
3036
3037 """
3038 return self.tk.call(self._w, 'edit', *args)
3039
3040 def edit_modified(self, arg=None):
3041 """Get or Set the modified flag
3042
3043 If arg is not specified, returns the modified
3044 flag of the widget. The insert, delete, edit undo and
3045 edit redo commands or the user can set or clear the
3046 modified flag. If boolean is specified, sets the
3047 modified flag of the widget to arg.
3048 """
3049 return self.edit("modified", arg)
3050
3051 def edit_redo(self):
3052 """Redo the last undone edit
3053
3054 When the undo option is true, reapplies the last
3055 undone edits provided no other edits were done since
3056 then. Generates an error when the redo stack is empty.
3057 Does nothing when the undo option is false.
3058 """
3059 return self.edit("redo")
3060
3061 def edit_reset(self):
3062 """Clears the undo and redo stacks
3063 """
3064 return self.edit("reset")
3065
3066 def edit_separator(self):
3067 """Inserts a separator (boundary) on the undo stack.
3068
3069 Does nothing when the undo option is false
3070 """
3071 return self.edit("separator")
3072
3073 def edit_undo(self):
3074 """Undoes the last edit action
3075
3076 If the undo option is true. An edit action is defined
3077 as all the insert and delete commands that are recorded
3078 on the undo stack in between two separators. Generates
3079 an error when the undo stack is empty. Does nothing
3080 when the undo option is false
3081 """
3082 return self.edit("undo")
3083
3084 def get(self, index1, index2=None):
3085 """Return the text from INDEX1 to INDEX2 (not included)."""
3086 return self.tk.call(self._w, 'get', index1, index2)
3087 # (Image commands are new in 8.0)
3088 def image_cget(self, index, option):
3089 """Return the value of OPTION of an embedded image at INDEX."""
3090 if option[:1] != "-":
3091 option = "-" + option
3092 if option[-1:] == "_":
3093 option = option[:-1]
3094 return self.tk.call(self._w, "image", "cget", index, option)
3095 def image_configure(self, index, cnf=None, **kw):
3096 """Configure an embedded image at INDEX."""
3097 return self._configure(('image', 'configure', index), cnf, kw)
3098 def image_create(self, index, cnf={}, **kw):
3099 """Create an embedded image at INDEX."""
3100 return self.tk.call(
3101 self._w, "image", "create", index,
3102 *self._options(cnf, kw))
3103 def image_names(self):
3104 """Return all names of embedded images in this widget."""
3105 return self.tk.call(self._w, "image", "names")
3106 def index(self, index):
3107 """Return the index in the form line.char for INDEX."""
3108 return str(self.tk.call(self._w, 'index', index))
3109 def insert(self, index, chars, *args):
3110 """Insert CHARS before the characters at INDEX. An additional
3111 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3112 self.tk.call((self._w, 'insert', index, chars) + args)
3113 def mark_gravity(self, markName, direction=None):
3114 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3115 Return the current value if None is given for DIRECTION."""
3116 return self.tk.call(
3117 (self._w, 'mark', 'gravity', markName, direction))
3118 def mark_names(self):
3119 """Return all mark names."""
3120 return self.tk.splitlist(self.tk.call(
3121 self._w, 'mark', 'names'))
3122 def mark_set(self, markName, index):
3123 """Set mark MARKNAME before the character at INDEX."""
3124 self.tk.call(self._w, 'mark', 'set', markName, index)
3125 def mark_unset(self, *markNames):
3126 """Delete all marks in MARKNAMES."""
3127 self.tk.call((self._w, 'mark', 'unset') + markNames)
3128 def mark_next(self, index):
3129 """Return the name of the next mark after INDEX."""
3130 return self.tk.call(self._w, 'mark', 'next', index) or None
3131 def mark_previous(self, index):
3132 """Return the name of the previous mark before INDEX."""
3133 return self.tk.call(self._w, 'mark', 'previous', index) or None
3134 def scan_mark(self, x, y):
3135 """Remember the current X, Y coordinates."""
3136 self.tk.call(self._w, 'scan', 'mark', x, y)
3137 def scan_dragto(self, x, y):
3138 """Adjust the view of the text to 10 times the
3139 difference between X and Y and the coordinates given in
3140 scan_mark."""
3141 self.tk.call(self._w, 'scan', 'dragto', x, y)
3142 def search(self, pattern, index, stopindex=None,
3143 forwards=None, backwards=None, exact=None,
3144 regexp=None, nocase=None, count=None, elide=None):
3145 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Polod2ea0332009-02-09 16:41:09 +00003146 Return the index of the first character of a match or an
3147 empty string."""
Georg Brandl33cece02008-05-20 06:58:21 +00003148 args = [self._w, 'search']
3149 if forwards: args.append('-forwards')
3150 if backwards: args.append('-backwards')
3151 if exact: args.append('-exact')
3152 if regexp: args.append('-regexp')
3153 if nocase: args.append('-nocase')
3154 if elide: args.append('-elide')
3155 if count: args.append('-count'); args.append(count)
Guilherme Polod2ea0332009-02-09 16:41:09 +00003156 if pattern and pattern[0] == '-': args.append('--')
Georg Brandl33cece02008-05-20 06:58:21 +00003157 args.append(pattern)
3158 args.append(index)
3159 if stopindex: args.append(stopindex)
Guilherme Polo6d6c1fd2009-03-07 01:19:12 +00003160 return str(self.tk.call(tuple(args)))
Georg Brandl33cece02008-05-20 06:58:21 +00003161 def see(self, index):
3162 """Scroll such that the character at INDEX is visible."""
3163 self.tk.call(self._w, 'see', index)
3164 def tag_add(self, tagName, index1, *args):
3165 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3166 Additional pairs of indices may follow in ARGS."""
3167 self.tk.call(
3168 (self._w, 'tag', 'add', tagName, index1) + args)
3169 def tag_unbind(self, tagName, sequence, funcid=None):
3170 """Unbind for all characters with TAGNAME for event SEQUENCE the
3171 function identified with FUNCID."""
3172 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3173 if funcid:
3174 self.deletecommand(funcid)
3175 def tag_bind(self, tagName, sequence, func, add=None):
3176 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
3177
3178 An additional boolean parameter ADD specifies whether FUNC will be
3179 called additionally to the other bound function or whether it will
3180 replace the previous function. See bind for the return value."""
3181 return self._bind((self._w, 'tag', 'bind', tagName),
3182 sequence, func, add)
3183 def tag_cget(self, tagName, option):
3184 """Return the value of OPTION for tag TAGNAME."""
3185 if option[:1] != '-':
3186 option = '-' + option
3187 if option[-1:] == '_':
3188 option = option[:-1]
3189 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
3190 def tag_configure(self, tagName, cnf=None, **kw):
3191 """Configure a tag TAGNAME."""
3192 return self._configure(('tag', 'configure', tagName), cnf, kw)
3193 tag_config = tag_configure
3194 def tag_delete(self, *tagNames):
3195 """Delete all tags in TAGNAMES."""
3196 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3197 def tag_lower(self, tagName, belowThis=None):
3198 """Change the priority of tag TAGNAME such that it is lower
3199 than the priority of BELOWTHIS."""
3200 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3201 def tag_names(self, index=None):
3202 """Return a list of all tag names."""
3203 return self.tk.splitlist(
3204 self.tk.call(self._w, 'tag', 'names', index))
3205 def tag_nextrange(self, tagName, index1, index2=None):
3206 """Return a list of start and end index for the first sequence of
3207 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3208 The text is searched forward from INDEX1."""
3209 return self.tk.splitlist(self.tk.call(
3210 self._w, 'tag', 'nextrange', tagName, index1, index2))
3211 def tag_prevrange(self, tagName, index1, index2=None):
3212 """Return a list of start and end index for the first sequence of
3213 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3214 The text is searched backwards from INDEX1."""
3215 return self.tk.splitlist(self.tk.call(
3216 self._w, 'tag', 'prevrange', tagName, index1, index2))
3217 def tag_raise(self, tagName, aboveThis=None):
3218 """Change the priority of tag TAGNAME such that it is higher
3219 than the priority of ABOVETHIS."""
3220 self.tk.call(
3221 self._w, 'tag', 'raise', tagName, aboveThis)
3222 def tag_ranges(self, tagName):
3223 """Return a list of ranges of text which have tag TAGNAME."""
3224 return self.tk.splitlist(self.tk.call(
3225 self._w, 'tag', 'ranges', tagName))
3226 def tag_remove(self, tagName, index1, index2=None):
3227 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3228 self.tk.call(
3229 self._w, 'tag', 'remove', tagName, index1, index2)
3230 def window_cget(self, index, option):
3231 """Return the value of OPTION of an embedded window at INDEX."""
3232 if option[:1] != '-':
3233 option = '-' + option
3234 if option[-1:] == '_':
3235 option = option[:-1]
3236 return self.tk.call(self._w, 'window', 'cget', index, option)
3237 def window_configure(self, index, cnf=None, **kw):
3238 """Configure an embedded window at INDEX."""
3239 return self._configure(('window', 'configure', index), cnf, kw)
3240 window_config = window_configure
3241 def window_create(self, index, cnf={}, **kw):
3242 """Create a window at INDEX."""
3243 self.tk.call(
3244 (self._w, 'window', 'create', index)
3245 + self._options(cnf, kw))
3246 def window_names(self):
3247 """Return all names of embedded windows in this widget."""
3248 return self.tk.splitlist(
3249 self.tk.call(self._w, 'window', 'names'))
Georg Brandl33cece02008-05-20 06:58:21 +00003250 def yview_pickplace(self, *what):
3251 """Obsolete function, use see."""
3252 self.tk.call((self._w, 'yview', '-pickplace') + what)
3253
3254
3255class _setit:
3256 """Internal class. It wraps the command in the widget OptionMenu."""
3257 def __init__(self, var, value, callback=None):
3258 self.__value = value
3259 self.__var = var
3260 self.__callback = callback
3261 def __call__(self, *args):
3262 self.__var.set(self.__value)
3263 if self.__callback:
3264 self.__callback(self.__value, *args)
3265
3266class OptionMenu(Menubutton):
3267 """OptionMenu which allows the user to select a value from a menu."""
3268 def __init__(self, master, variable, value, *values, **kwargs):
3269 """Construct an optionmenu widget with the parent MASTER, with
3270 the resource textvariable set to VARIABLE, the initially selected
3271 value VALUE, the other menu values VALUES and an additional
3272 keyword argument command."""
3273 kw = {"borderwidth": 2, "textvariable": variable,
3274 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3275 "highlightthickness": 2}
3276 Widget.__init__(self, master, "menubutton", kw)
3277 self.widgetName = 'tk_optionMenu'
3278 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3279 self.menuname = menu._w
3280 # 'command' is the only supported keyword
3281 callback = kwargs.get('command')
Benjamin Peterson6e3dbbd2009-10-09 22:15:50 +00003282 if 'command' in kwargs:
Georg Brandl33cece02008-05-20 06:58:21 +00003283 del kwargs['command']
3284 if kwargs:
3285 raise TclError, 'unknown option -'+kwargs.keys()[0]
3286 menu.add_command(label=value,
3287 command=_setit(variable, value, callback))
3288 for v in values:
3289 menu.add_command(label=v,
3290 command=_setit(variable, v, callback))
3291 self["menu"] = menu
3292
3293 def __getitem__(self, name):
3294 if name == 'menu':
3295 return self.__menu
3296 return Widget.__getitem__(self, name)
3297
3298 def destroy(self):
3299 """Destroy this widget and the associated menu."""
3300 Menubutton.destroy(self)
3301 self.__menu = None
3302
3303class Image:
3304 """Base class for images."""
3305 _last_id = 0
3306 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3307 self.name = None
3308 if not master:
3309 master = _default_root
3310 if not master:
3311 raise RuntimeError, 'Too early to create image'
Serhiy Storchakad3ea0652014-08-24 09:07:09 +03003312 self.tk = getattr(master, 'tk', master)
Georg Brandl33cece02008-05-20 06:58:21 +00003313 if not name:
3314 Image._last_id += 1
3315 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
3316 # The following is needed for systems where id(x)
3317 # can return a negative number, such as Linux/m68k:
3318 if name[0] == '-': name = '_' + name[1:]
3319 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3320 elif kw: cnf = kw
3321 options = ()
3322 for k, v in cnf.items():
Benjamin Petersonde055992009-10-09 22:05:45 +00003323 if hasattr(v, '__call__'):
Georg Brandl33cece02008-05-20 06:58:21 +00003324 v = self._register(v)
Serhiy Storchaka04fa7042014-07-31 07:48:14 +03003325 elif k in ('data', 'maskdata'):
3326 v = self.tk._createbytearray(v)
Georg Brandl33cece02008-05-20 06:58:21 +00003327 options = options + ('-'+k, v)
3328 self.tk.call(('image', 'create', imgtype, name,) + options)
3329 self.name = name
3330 def __str__(self): return self.name
3331 def __del__(self):
3332 if self.name:
3333 try:
3334 self.tk.call('image', 'delete', self.name)
3335 except TclError:
3336 # May happen if the root was destroyed
3337 pass
3338 def __setitem__(self, key, value):
3339 self.tk.call(self.name, 'configure', '-'+key, value)
3340 def __getitem__(self, key):
3341 return self.tk.call(self.name, 'configure', '-'+key)
3342 def configure(self, **kw):
3343 """Configure the image."""
3344 res = ()
3345 for k, v in _cnfmerge(kw).items():
3346 if v is not None:
3347 if k[-1] == '_': k = k[:-1]
Benjamin Petersonde055992009-10-09 22:05:45 +00003348 if hasattr(v, '__call__'):
Georg Brandl33cece02008-05-20 06:58:21 +00003349 v = self._register(v)
Serhiy Storchaka04fa7042014-07-31 07:48:14 +03003350 elif k in ('data', 'maskdata'):
3351 v = self.tk._createbytearray(v)
Georg Brandl33cece02008-05-20 06:58:21 +00003352 res = res + ('-'+k, v)
3353 self.tk.call((self.name, 'config') + res)
3354 config = configure
3355 def height(self):
3356 """Return the height of the image."""
3357 return getint(
3358 self.tk.call('image', 'height', self.name))
3359 def type(self):
Vijay Kumarf31f2252017-05-23 11:46:27 +05303360 """Return the type of the image, e.g. "photo" or "bitmap"."""
Georg Brandl33cece02008-05-20 06:58:21 +00003361 return self.tk.call('image', 'type', self.name)
3362 def width(self):
3363 """Return the width of the image."""
3364 return getint(
3365 self.tk.call('image', 'width', self.name))
3366
3367class PhotoImage(Image):
Andrés Delfino7a45eb92018-04-20 03:15:01 -03003368 """Widget which can display images in PGM, PPM, GIF, PNG format."""
Georg Brandl33cece02008-05-20 06:58:21 +00003369 def __init__(self, name=None, cnf={}, master=None, **kw):
3370 """Create an image with NAME.
3371
3372 Valid resource names: data, format, file, gamma, height, palette,
3373 width."""
3374 Image.__init__(self, 'photo', name, cnf, master, **kw)
3375 def blank(self):
3376 """Display a transparent image."""
3377 self.tk.call(self.name, 'blank')
3378 def cget(self, option):
3379 """Return the value of OPTION."""
3380 return self.tk.call(self.name, 'cget', '-' + option)
3381 # XXX config
3382 def __getitem__(self, key):
3383 return self.tk.call(self.name, 'cget', '-' + key)
3384 # XXX copy -from, -to, ...?
3385 def copy(self):
3386 """Return a new PhotoImage with the same image as this widget."""
Serhiy Storchakad3ea0652014-08-24 09:07:09 +03003387 destImage = PhotoImage(master=self.tk)
Georg Brandl33cece02008-05-20 06:58:21 +00003388 self.tk.call(destImage, 'copy', self.name)
3389 return destImage
Terry Jan Reedyca761002016-03-11 15:30:27 -05003390 def zoom(self, x, y=''):
Georg Brandl33cece02008-05-20 06:58:21 +00003391 """Return a new PhotoImage with the same image as this widget
Terry Jan Reedyca761002016-03-11 15:30:27 -05003392 but zoom it with a factor of x in the X direction and y in the Y
3393 direction. If y is not given, the default value is the same as x.
3394 """
Serhiy Storchakad3ea0652014-08-24 09:07:09 +03003395 destImage = PhotoImage(master=self.tk)
Georg Brandl33cece02008-05-20 06:58:21 +00003396 if y=='': y=x
3397 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3398 return destImage
Terry Jan Reedyca761002016-03-11 15:30:27 -05003399 def subsample(self, x, y=''):
Georg Brandl33cece02008-05-20 06:58:21 +00003400 """Return a new PhotoImage based on the same image as this widget
Terry Jan Reedyca761002016-03-11 15:30:27 -05003401 but use only every Xth or Yth pixel. If y is not given, the
3402 default value is the same as x.
3403 """
Serhiy Storchakad3ea0652014-08-24 09:07:09 +03003404 destImage = PhotoImage(master=self.tk)
Georg Brandl33cece02008-05-20 06:58:21 +00003405 if y=='': y=x
3406 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3407 return destImage
3408 def get(self, x, y):
3409 """Return the color (red, green, blue) of the pixel at X,Y."""
3410 return self.tk.call(self.name, 'get', x, y)
3411 def put(self, data, to=None):
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00003412 """Put row formatted colors to image starting from
Georg Brandl33cece02008-05-20 06:58:21 +00003413 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3414 args = (self.name, 'put', data)
3415 if to:
3416 if to[0] == '-to':
3417 to = to[1:]
3418 args = args + ('-to',) + tuple(to)
3419 self.tk.call(args)
3420 # XXX read
3421 def write(self, filename, format=None, from_coords=None):
3422 """Write image to file FILENAME in FORMAT starting from
3423 position FROM_COORDS."""
3424 args = (self.name, 'write', filename)
3425 if format:
3426 args = args + ('-format', format)
3427 if from_coords:
3428 args = args + ('-from',) + tuple(from_coords)
3429 self.tk.call(args)
3430
3431class BitmapImage(Image):
Andrés Delfino7a45eb92018-04-20 03:15:01 -03003432 """Widget which can display images in XBM format."""
Georg Brandl33cece02008-05-20 06:58:21 +00003433 def __init__(self, name=None, cnf={}, master=None, **kw):
3434 """Create a bitmap with NAME.
3435
3436 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3437 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
3438
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02003439def image_names():
3440 return _default_root.tk.splitlist(_default_root.tk.call('image', 'names'))
3441
3442def image_types():
3443 return _default_root.tk.splitlist(_default_root.tk.call('image', 'types'))
Georg Brandl33cece02008-05-20 06:58:21 +00003444
3445
Guilherme Poloe45f0172009-08-14 14:36:45 +00003446class Spinbox(Widget, XView):
Georg Brandl33cece02008-05-20 06:58:21 +00003447 """spinbox widget."""
3448 def __init__(self, master=None, cnf={}, **kw):
3449 """Construct a spinbox widget with the parent MASTER.
3450
3451 STANDARD OPTIONS
3452
3453 activebackground, background, borderwidth,
3454 cursor, exportselection, font, foreground,
3455 highlightbackground, highlightcolor,
3456 highlightthickness, insertbackground,
3457 insertborderwidth, insertofftime,
3458 insertontime, insertwidth, justify, relief,
3459 repeatdelay, repeatinterval,
3460 selectbackground, selectborderwidth
3461 selectforeground, takefocus, textvariable
3462 xscrollcommand.
3463
3464 WIDGET-SPECIFIC OPTIONS
3465
3466 buttonbackground, buttoncursor,
3467 buttondownrelief, buttonuprelief,
3468 command, disabledbackground,
3469 disabledforeground, format, from,
3470 invalidcommand, increment,
3471 readonlybackground, state, to,
3472 validate, validatecommand values,
3473 width, wrap,
3474 """
3475 Widget.__init__(self, master, 'spinbox', cnf, kw)
3476
3477 def bbox(self, index):
3478 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3479 rectangle which encloses the character given by index.
3480
3481 The first two elements of the list give the x and y
3482 coordinates of the upper-left corner of the screen
3483 area covered by the character (in pixels relative
3484 to the widget) and the last two elements give the
3485 width and height of the character, in pixels. The
3486 bounding box may refer to a region outside the
3487 visible area of the window.
3488 """
Serhiy Storchaka8630f162013-11-03 14:13:08 +02003489 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
Georg Brandl33cece02008-05-20 06:58:21 +00003490
3491 def delete(self, first, last=None):
3492 """Delete one or more elements of the spinbox.
3493
3494 First is the index of the first character to delete,
3495 and last is the index of the character just after
3496 the last one to delete. If last isn't specified it
3497 defaults to first+1, i.e. a single character is
3498 deleted. This command returns an empty string.
3499 """
3500 return self.tk.call(self._w, 'delete', first, last)
3501
3502 def get(self):
3503 """Returns the spinbox's string"""
3504 return self.tk.call(self._w, 'get')
3505
3506 def icursor(self, index):
3507 """Alter the position of the insertion cursor.
3508
3509 The insertion cursor will be displayed just before
3510 the character given by index. Returns an empty string
3511 """
3512 return self.tk.call(self._w, 'icursor', index)
3513
3514 def identify(self, x, y):
3515 """Returns the name of the widget at position x, y
3516
3517 Return value is one of: none, buttondown, buttonup, entry
3518 """
3519 return self.tk.call(self._w, 'identify', x, y)
3520
3521 def index(self, index):
3522 """Returns the numerical index corresponding to index
3523 """
3524 return self.tk.call(self._w, 'index', index)
3525
3526 def insert(self, index, s):
3527 """Insert string s at index
3528
3529 Returns an empty string.
3530 """
3531 return self.tk.call(self._w, 'insert', index, s)
3532
3533 def invoke(self, element):
3534 """Causes the specified element to be invoked
3535
3536 The element could be buttondown or buttonup
3537 triggering the action associated with it.
3538 """
3539 return self.tk.call(self._w, 'invoke', element)
3540
3541 def scan(self, *args):
3542 """Internal function."""
3543 return self._getints(
3544 self.tk.call((self._w, 'scan') + args)) or ()
3545
3546 def scan_mark(self, x):
3547 """Records x and the current view in the spinbox window;
3548
3549 used in conjunction with later scan dragto commands.
3550 Typically this command is associated with a mouse button
3551 press in the widget. It returns an empty string.
3552 """
3553 return self.scan("mark", x)
3554
3555 def scan_dragto(self, x):
3556 """Compute the difference between the given x argument
3557 and the x argument to the last scan mark command
3558
3559 It then adjusts the view left or right by 10 times the
3560 difference in x-coordinates. This command is typically
3561 associated with mouse motion events in the widget, to
3562 produce the effect of dragging the spinbox at high speed
3563 through the window. The return value is an empty string.
3564 """
3565 return self.scan("dragto", x)
3566
3567 def selection(self, *args):
3568 """Internal function."""
3569 return self._getints(
3570 self.tk.call((self._w, 'selection') + args)) or ()
3571
3572 def selection_adjust(self, index):
3573 """Locate the end of the selection nearest to the character
3574 given by index,
3575
3576 Then adjust that end of the selection to be at index
3577 (i.e including but not going beyond index). The other
3578 end of the selection is made the anchor point for future
3579 select to commands. If the selection isn't currently in
3580 the spinbox, then a new selection is created to include
3581 the characters between index and the most recent selection
3582 anchor point, inclusive. Returns an empty string.
3583 """
3584 return self.selection("adjust", index)
3585
3586 def selection_clear(self):
3587 """Clear the selection
3588
3589 If the selection isn't in this widget then the
3590 command has no effect. Returns an empty string.
3591 """
3592 return self.selection("clear")
3593
3594 def selection_element(self, element=None):
3595 """Sets or gets the currently selected element.
3596
3597 If a spinbutton element is specified, it will be
3598 displayed depressed
3599 """
3600 return self.selection("element", element)
3601
3602###########################################################################
3603
3604class LabelFrame(Widget):
3605 """labelframe widget."""
3606 def __init__(self, master=None, cnf={}, **kw):
3607 """Construct a labelframe widget with the parent MASTER.
3608
3609 STANDARD OPTIONS
3610
3611 borderwidth, cursor, font, foreground,
3612 highlightbackground, highlightcolor,
3613 highlightthickness, padx, pady, relief,
3614 takefocus, text
3615
3616 WIDGET-SPECIFIC OPTIONS
3617
3618 background, class, colormap, container,
3619 height, labelanchor, labelwidget,
3620 visual, width
3621 """
3622 Widget.__init__(self, master, 'labelframe', cnf, kw)
3623
3624########################################################################
3625
3626class PanedWindow(Widget):
3627 """panedwindow widget."""
3628 def __init__(self, master=None, cnf={}, **kw):
3629 """Construct a panedwindow widget with the parent MASTER.
3630
3631 STANDARD OPTIONS
3632
3633 background, borderwidth, cursor, height,
3634 orient, relief, width
3635
3636 WIDGET-SPECIFIC OPTIONS
3637
3638 handlepad, handlesize, opaqueresize,
3639 sashcursor, sashpad, sashrelief,
3640 sashwidth, showhandle,
3641 """
3642 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3643
3644 def add(self, child, **kw):
3645 """Add a child widget to the panedwindow in a new pane.
3646
3647 The child argument is the name of the child widget
3648 followed by pairs of arguments that specify how to
Guilherme Polo1c6787f2009-05-31 21:31:21 +00003649 manage the windows. The possible options and values
3650 are the ones accepted by the paneconfigure method.
Georg Brandl33cece02008-05-20 06:58:21 +00003651 """
3652 self.tk.call((self._w, 'add', child) + self._options(kw))
3653
3654 def remove(self, child):
3655 """Remove the pane containing child from the panedwindow
3656
3657 All geometry management options for child will be forgotten.
3658 """
3659 self.tk.call(self._w, 'forget', child)
3660 forget=remove
3661
3662 def identify(self, x, y):
3663 """Identify the panedwindow component at point x, y
3664
3665 If the point is over a sash or a sash handle, the result
3666 is a two element list containing the index of the sash or
3667 handle, and a word indicating whether it is over a sash
3668 or a handle, such as {0 sash} or {2 handle}. If the point
3669 is over any other part of the panedwindow, the result is
3670 an empty list.
3671 """
3672 return self.tk.call(self._w, 'identify', x, y)
3673
3674 def proxy(self, *args):
3675 """Internal function."""
3676 return self._getints(
3677 self.tk.call((self._w, 'proxy') + args)) or ()
3678
3679 def proxy_coord(self):
3680 """Return the x and y pair of the most recent proxy location
3681 """
3682 return self.proxy("coord")
3683
3684 def proxy_forget(self):
3685 """Remove the proxy from the display.
3686 """
3687 return self.proxy("forget")
3688
3689 def proxy_place(self, x, y):
3690 """Place the proxy at the given x and y coordinates.
3691 """
3692 return self.proxy("place", x, y)
3693
3694 def sash(self, *args):
3695 """Internal function."""
3696 return self._getints(
3697 self.tk.call((self._w, 'sash') + args)) or ()
3698
3699 def sash_coord(self, index):
3700 """Return the current x and y pair for the sash given by index.
3701
3702 Index must be an integer between 0 and 1 less than the
3703 number of panes in the panedwindow. The coordinates given are
3704 those of the top left corner of the region containing the sash.
3705 pathName sash dragto index x y This command computes the
3706 difference between the given coordinates and the coordinates
3707 given to the last sash coord command for the given sash. It then
3708 moves that sash the computed difference. The return value is the
3709 empty string.
3710 """
3711 return self.sash("coord", index)
3712
3713 def sash_mark(self, index):
3714 """Records x and y for the sash given by index;
3715
3716 Used in conjunction with later dragto commands to move the sash.
3717 """
3718 return self.sash("mark", index)
3719
3720 def sash_place(self, index, x, y):
3721 """Place the sash given by index at the given coordinates
3722 """
3723 return self.sash("place", index, x, y)
3724
3725 def panecget(self, child, option):
3726 """Query a management option for window.
3727
3728 Option may be any value allowed by the paneconfigure subcommand
3729 """
3730 return self.tk.call(
3731 (self._w, 'panecget') + (child, '-'+option))
3732
3733 def paneconfigure(self, tagOrId, cnf=None, **kw):
3734 """Query or modify the management options for window.
3735
3736 If no option is specified, returns a list describing all
3737 of the available options for pathName. If option is
3738 specified with no value, then the command returns a list
3739 describing the one named option (this list will be identical
3740 to the corresponding sublist of the value returned if no
3741 option is specified). If one or more option-value pairs are
3742 specified, then the command modifies the given widget
3743 option(s) to have the given value(s); in this case the
3744 command returns an empty string. The following options
3745 are supported:
3746
3747 after window
3748 Insert the window after the window specified. window
3749 should be the name of a window already managed by pathName.
3750 before window
3751 Insert the window before the window specified. window
3752 should be the name of a window already managed by pathName.
3753 height size
3754 Specify a height for the window. The height will be the
3755 outer dimension of the window including its border, if
3756 any. If size is an empty string, or if -height is not
3757 specified, then the height requested internally by the
3758 window will be used initially; the height may later be
3759 adjusted by the movement of sashes in the panedwindow.
3760 Size may be any value accepted by Tk_GetPixels.
3761 minsize n
3762 Specifies that the size of the window cannot be made
3763 less than n. This constraint only affects the size of
3764 the widget in the paned dimension -- the x dimension
3765 for horizontal panedwindows, the y dimension for
3766 vertical panedwindows. May be any value accepted by
3767 Tk_GetPixels.
3768 padx n
3769 Specifies a non-negative value indicating how much
3770 extra space to leave on each side of the window in
3771 the X-direction. The value may have any of the forms
3772 accepted by Tk_GetPixels.
3773 pady n
3774 Specifies a non-negative value indicating how much
3775 extra space to leave on each side of the window in
3776 the Y-direction. The value may have any of the forms
3777 accepted by Tk_GetPixels.
3778 sticky style
3779 If a window's pane is larger than the requested
3780 dimensions of the window, this option may be used
3781 to position (or stretch) the window within its pane.
3782 Style is a string that contains zero or more of the
3783 characters n, s, e or w. The string can optionally
3784 contains spaces or commas, but they are ignored. Each
3785 letter refers to a side (north, south, east, or west)
3786 that the window will "stick" to. If both n and s
3787 (or e and w) are specified, the window will be
3788 stretched to fill the entire height (or width) of
3789 its cavity.
3790 width size
3791 Specify a width for the window. The width will be
3792 the outer dimension of the window including its
3793 border, if any. If size is an empty string, or
3794 if -width is not specified, then the width requested
3795 internally by the window will be used initially; the
3796 width may later be adjusted by the movement of sashes
3797 in the panedwindow. Size may be any value accepted by
3798 Tk_GetPixels.
3799
3800 """
3801 if cnf is None and not kw:
Serhiy Storchakaec773cc2013-12-25 16:35:20 +02003802 return self._getconfigure(self._w, 'paneconfigure', tagOrId)
Georg Brandl33cece02008-05-20 06:58:21 +00003803 if type(cnf) == StringType and not kw:
Serhiy Storchakaec773cc2013-12-25 16:35:20 +02003804 return self._getconfigure1(
3805 self._w, 'paneconfigure', tagOrId, '-'+cnf)
Georg Brandl33cece02008-05-20 06:58:21 +00003806 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3807 self._options(cnf, kw))
3808 paneconfig = paneconfigure
3809
3810 def panes(self):
3811 """Returns an ordered list of the child panes."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02003812 return self.tk.splitlist(self.tk.call(self._w, 'panes'))
Georg Brandl33cece02008-05-20 06:58:21 +00003813
3814######################################################################
3815# Extensions:
3816
3817class Studbutton(Button):
3818 def __init__(self, master=None, cnf={}, **kw):
3819 Widget.__init__(self, master, 'studbutton', cnf, kw)
3820 self.bind('<Any-Enter>', self.tkButtonEnter)
3821 self.bind('<Any-Leave>', self.tkButtonLeave)
3822 self.bind('<1>', self.tkButtonDown)
3823 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3824
3825class Tributton(Button):
3826 def __init__(self, master=None, cnf={}, **kw):
3827 Widget.__init__(self, master, 'tributton', cnf, kw)
3828 self.bind('<Any-Enter>', self.tkButtonEnter)
3829 self.bind('<Any-Leave>', self.tkButtonLeave)
3830 self.bind('<1>', self.tkButtonDown)
3831 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3832 self['fg'] = self['bg']
3833 self['activebackground'] = self['bg']
3834
3835######################################################################
3836# Test:
3837
3838def _test():
3839 root = Tk()
3840 text = "This is Tcl/Tk version %s" % TclVersion
3841 if TclVersion >= 8.1:
3842 try:
3843 text = text + unicode("\nThis should be a cedilla: \347",
3844 "iso-8859-1")
3845 except NameError:
3846 pass # no unicode support
3847 label = Label(root, text=text)
3848 label.pack()
3849 test = Button(root, text="Click me!",
3850 command=lambda root=root: root.test.configure(
3851 text="[%s]" % root.test['text']))
3852 test.pack()
3853 root.test = test
3854 quit = Button(root, text="QUIT", command=root.destroy)
3855 quit.pack()
3856 # The following three commands are needed so the window pops
3857 # up on top on Windows...
3858 root.iconify()
3859 root.update()
3860 root.deiconify()
3861 root.mainloop()
3862
3863if __name__ == '__main__':
3864 _test()