blob: 8fa8e6e4bb7d05fe6daf82bd76a81ebdd9a31a84 [file] [log] [blame]
Guido van Rossum5917ecb2000-06-29 16:30:50 +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,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00006Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
Raymond Hettingerff41c482003-04-06 09:01:11 +00007LabelFrame and PanedWindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00008
Raymond Hettingerff41c482003-04-06 09:01:11 +00009Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
Martin v. Löwis2ec36272002-10-13 10:22:08 +000011under Tk.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000012
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
Guido van Rossuma0adb922001-09-01 18:29:55 +000017Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000019
20Example (Hello, World):
21import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25frame.pack(fill=BOTH,expand=1)
26label = Tkinter.Label(frame, text="Hello, World")
27label.pack(fill=X, expand=1)
28button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
29button.pack(side=BOTTOM)
30tk.mainloop()
31"""
Guido van Rossum2dcf5291994-07-06 09:23:20 +000032
Guido van Rossum37dcab11996-05-16 16:00:19 +000033__version__ = "$Revision$"
34
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import sys
36if sys.platform == "win32":
Fredrik Lundh06d28152000-08-09 18:03:12 +000037 import FixTk # Attempt to configure Tcl/Tk without requiring PATH
Guido van Rossumf8d579c1999-01-04 18:06:45 +000038import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000039tkinter = _tkinter # b/w compat for export
40TclError = _tkinter.TclError
Guido van Rossum7e9394a1995-03-17 16:21:33 +000041from types import *
Guido van Rossuma5773dd1995-09-07 19:22:00 +000042from Tkconstants import *
Guido van Rossumf0c891a1998-04-29 21:43:36 +000043try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000044 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000045except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000046 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000047
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000048wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000049
Eric S. Raymondfc170b12001-02-09 11:51:27 +000050TkVersion = float(_tkinter.TK_VERSION)
51TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000052
Guido van Rossumd6615ab1997-08-05 02:35:01 +000053READABLE = _tkinter.READABLE
54WRITABLE = _tkinter.WRITABLE
55EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000056
57# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
58try: _tkinter.createfilehandler
59except AttributeError: _tkinter.createfilehandler = None
60try: _tkinter.deletefilehandler
61except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000062
63
Guido van Rossum2dcf5291994-07-06 09:23:20 +000064def _flatten(tuple):
Fredrik Lundh06d28152000-08-09 18:03:12 +000065 """Internal function."""
66 res = ()
67 for item in tuple:
68 if type(item) in (TupleType, ListType):
69 res = res + _flatten(item)
70 elif item is not None:
71 res = res + (item,)
72 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000073
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000074try: _flatten = _tkinter._flatten
75except AttributeError: pass
76
Guido van Rossum2dcf5291994-07-06 09:23:20 +000077def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000078 """Internal function."""
79 if type(cnfs) is DictionaryType:
80 return cnfs
81 elif type(cnfs) in (NoneType, StringType):
82 return cnfs
83 else:
84 cnf = {}
85 for c in _flatten(cnfs):
86 try:
87 cnf.update(c)
88 except (AttributeError, TypeError), msg:
89 print "_cnfmerge: fallback due to:", msg
90 for k, v in c.items():
91 cnf[k] = v
92 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000093
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000094try: _cnfmerge = _tkinter._cnfmerge
95except AttributeError: pass
96
Guido van Rossum2dcf5291994-07-06 09:23:20 +000097class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000099
Fredrik Lundh06d28152000-08-09 18:03:12 +0000100 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000101
Fredrik Lundh06d28152000-08-09 18:03:12 +0000102 KeyPress, KeyRelease - for keyboard events
103 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
104 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
105 Colormap, Gravity, Reparent, Property, Destroy, Activate,
106 Deactivate - for window events.
107
108 If a callback function for one of these events is registered
109 using bind, bind_all, bind_class, or tag_bind, the callback is
110 called with an Event as first argument. It will have the
111 following attributes (in braces are the event types for which
112 the attribute is valid):
113
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000114 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000115 num - mouse button pressed (ButtonPress, ButtonRelease)
116 focus - whether the window has the focus (Enter, Leave)
117 height - height of the exposed window (Configure, Expose)
118 width - width of the exposed window (Configure, Expose)
119 keycode - keycode of the pressed key (KeyPress, KeyRelease)
120 state - state of the event as a number (ButtonPress, ButtonRelease,
121 Enter, KeyPress, KeyRelease,
122 Leave, Motion)
123 state - state as a string (Visibility)
124 time - when the event occurred
125 x - x-position of the mouse
126 y - y-position of the mouse
127 x_root - x-position of the mouse on the screen
128 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
129 y_root - y-position of the mouse on the screen
130 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
131 char - pressed character (KeyPress, KeyRelease)
132 send_event - see X/Windows documentation
133 keysym - keysym of the the event as a string (KeyPress, KeyRelease)
134 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
135 type - type of the event as a number
136 widget - widget in which the event occurred
137 delta - delta of wheel movement (MouseWheel)
138 """
139 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000140
Guido van Rossumc4570481998-03-20 20:45:49 +0000141_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000142_default_root = None
143
Guido van Rossumc4570481998-03-20 20:45:49 +0000144def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000145 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000146
Fredrik Lundh06d28152000-08-09 18:03:12 +0000147 Call this function to inhibit that the first instance of
148 Tk is used for windows without an explicit parent window.
149 """
150 global _support_default_root
151 _support_default_root = 0
152 global _default_root
153 _default_root = None
154 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000155
Guido van Rossum45853db1994-06-20 12:19:19 +0000156def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000157 """Internal function."""
158 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000159
Guido van Rossum97aeca11994-07-07 13:12:12 +0000160def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000161 """Internal function. Calling it will throw the exception SystemExit."""
162 raise SystemExit, code
Guido van Rossum97aeca11994-07-07 13:12:12 +0000163
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000164_varnum = 0
165class Variable:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000166 """Internal class. Base class to define value holders for e.g. buttons."""
167 _default = ""
168 def __init__(self, master=None):
169 """Construct a variable with an optional MASTER as master widget.
170 The variable is named PY_VAR_number in Tcl.
171 """
172 global _varnum
173 if not master:
174 master = _default_root
175 self._master = master
176 self._tk = master.tk
177 self._name = 'PY_VAR' + `_varnum`
178 _varnum = _varnum + 1
179 self.set(self._default)
180 def __del__(self):
181 """Unset the variable in Tcl."""
182 self._tk.globalunsetvar(self._name)
183 def __str__(self):
184 """Return the name of the variable in Tcl."""
185 return self._name
186 def set(self, value):
187 """Set the variable to VALUE."""
188 return self._tk.globalsetvar(self._name, value)
189 def trace_variable(self, mode, callback):
190 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000191
Fredrik Lundh06d28152000-08-09 18:03:12 +0000192 MODE is one of "r", "w", "u" for read, write, undefine.
193 CALLBACK must be a function which is called when
194 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000195
Fredrik Lundh06d28152000-08-09 18:03:12 +0000196 Return the name of the callback.
197 """
198 cbname = self._master._register(callback)
199 self._tk.call("trace", "variable", self._name, mode, cbname)
200 return cbname
201 trace = trace_variable
202 def trace_vdelete(self, mode, cbname):
203 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000204
Fredrik Lundh06d28152000-08-09 18:03:12 +0000205 MODE is one of "r", "w", "u" for read, write, undefine.
206 CBNAME is the name of the callback returned from trace_variable or trace.
207 """
208 self._tk.call("trace", "vdelete", self._name, mode, cbname)
209 self._master.deletecommand(cbname)
210 def trace_vinfo(self):
211 """Return all trace callback information."""
212 return map(self._tk.split, self._tk.splitlist(
213 self._tk.call("trace", "vinfo", self._name)))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000214
215class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000216 """Value holder for strings variables."""
217 _default = ""
218 def __init__(self, master=None):
219 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000220
Fredrik Lundh06d28152000-08-09 18:03:12 +0000221 MASTER can be given as master widget."""
222 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000223
Fredrik Lundh06d28152000-08-09 18:03:12 +0000224 def get(self):
225 """Return value of variable as string."""
226 return self._tk.globalgetvar(self._name)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000227
228class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000229 """Value holder for integer variables."""
230 _default = 0
231 def __init__(self, master=None):
232 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000233
Fredrik Lundh06d28152000-08-09 18:03:12 +0000234 MASTER can be given as master widget."""
235 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000236
Martin v. Löwis70c3dda2003-01-22 09:17:38 +0000237 def set(self, value):
238 """Set the variable to value, converting booleans to integers."""
239 if isinstance(value, bool):
240 value = int(value)
241 return Variable.set(self, value)
242
Fredrik Lundh06d28152000-08-09 18:03:12 +0000243 def get(self):
244 """Return the value of the variable as an integer."""
245 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000246
247class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000248 """Value holder for float variables."""
249 _default = 0.0
250 def __init__(self, master=None):
251 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000252
Fredrik Lundh06d28152000-08-09 18:03:12 +0000253 MASTER can be given as a master widget."""
254 Variable.__init__(self, master)
255
256 def get(self):
257 """Return the value of the variable as a float."""
258 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000259
260class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000261 """Value holder for boolean variables."""
262 _default = "false"
263 def __init__(self, master=None):
264 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000265
Fredrik Lundh06d28152000-08-09 18:03:12 +0000266 MASTER can be given as a master widget."""
267 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000268
Fredrik Lundh06d28152000-08-09 18:03:12 +0000269 def get(self):
270 """Return the value of the variable as 0 or 1."""
271 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000272
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000273def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000274 """Run the main loop of Tcl."""
275 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000276
Guido van Rossum0132f691998-04-30 17:50:36 +0000277getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000278
Guido van Rossum0132f691998-04-30 17:50:36 +0000279getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000280
281def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000282 """Convert true and false to integer values 1 and 0."""
283 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000284
Guido van Rossum368e06b1997-11-07 20:38:49 +0000285# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000286class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000287 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000288
Fredrik Lundh06d28152000-08-09 18:03:12 +0000289 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000290
Fredrik Lundh06d28152000-08-09 18:03:12 +0000291 # XXX font command?
292 _tclCommands = None
293 def destroy(self):
294 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000295
Fredrik Lundh06d28152000-08-09 18:03:12 +0000296 Delete all Tcl commands created for
297 this widget in the Tcl interpreter."""
298 if self._tclCommands is not None:
299 for name in self._tclCommands:
300 #print '- Tkinter: deleted command', name
301 self.tk.deletecommand(name)
302 self._tclCommands = None
303 def deletecommand(self, name):
304 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000305
Fredrik Lundh06d28152000-08-09 18:03:12 +0000306 Delete the Tcl command provided in NAME."""
307 #print '- Tkinter: deleted command', name
308 self.tk.deletecommand(name)
309 try:
310 self._tclCommands.remove(name)
311 except ValueError:
312 pass
313 def tk_strictMotif(self, boolean=None):
314 """Set Tcl internal variable, whether the look and feel
315 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000316
Fredrik Lundh06d28152000-08-09 18:03:12 +0000317 A parameter of 1 means adhere to Motif (e.g. no color
318 change if mouse passes over slider).
319 Returns the set value."""
320 return self.tk.getboolean(self.tk.call(
321 'set', 'tk_strictMotif', boolean))
322 def tk_bisque(self):
323 """Change the color scheme to light brown as used in Tk 3.6 and before."""
324 self.tk.call('tk_bisque')
325 def tk_setPalette(self, *args, **kw):
326 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000327
Fredrik Lundh06d28152000-08-09 18:03:12 +0000328 A single color as argument will cause that all colors of Tk
329 widget elements are derived from this.
330 Alternatively several keyword parameters and its associated
331 colors can be given. The following keywords are valid:
332 activeBackground, foreground, selectColor,
333 activeForeground, highlightBackground, selectBackground,
334 background, highlightColor, selectForeground,
335 disabledForeground, insertBackground, troughColor."""
336 self.tk.call(('tk_setPalette',)
337 + _flatten(args) + _flatten(kw.items()))
338 def tk_menuBar(self, *args):
339 """Do not use. Needed in Tk 3.6 and earlier."""
340 pass # obsolete since Tk 4.0
341 def wait_variable(self, name='PY_VAR'):
342 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000343
Fredrik Lundh06d28152000-08-09 18:03:12 +0000344 A parameter of type IntVar, StringVar, DoubleVar or
345 BooleanVar must be given."""
346 self.tk.call('tkwait', 'variable', name)
347 waitvar = wait_variable # XXX b/w compat
348 def wait_window(self, window=None):
349 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000350
Fredrik Lundh06d28152000-08-09 18:03:12 +0000351 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000352 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000353 window = self
354 self.tk.call('tkwait', 'window', window._w)
355 def wait_visibility(self, window=None):
356 """Wait until the visibility of a WIDGET changes
357 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000358
Fredrik Lundh06d28152000-08-09 18:03:12 +0000359 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000360 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000361 window = self
362 self.tk.call('tkwait', 'visibility', window._w)
363 def setvar(self, name='PY_VAR', value='1'):
364 """Set Tcl variable NAME to VALUE."""
365 self.tk.setvar(name, value)
366 def getvar(self, name='PY_VAR'):
367 """Return value of Tcl variable NAME."""
368 return self.tk.getvar(name)
369 getint = int
370 getdouble = float
371 def getboolean(self, s):
372 """Return 0 or 1 for Tcl boolean values true and false given as parameter."""
373 return self.tk.getboolean(s)
374 def focus_set(self):
375 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000376
Fredrik Lundh06d28152000-08-09 18:03:12 +0000377 If the application currently does not have the focus
378 this widget will get the focus if the application gets
379 the focus through the window manager."""
380 self.tk.call('focus', self._w)
381 focus = focus_set # XXX b/w compat?
382 def focus_force(self):
383 """Direct input focus to this widget even if the
384 application does not have the focus. Use with
385 caution!"""
386 self.tk.call('focus', '-force', self._w)
387 def focus_get(self):
388 """Return the widget which has currently the focus in the
389 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000390
Fredrik Lundh06d28152000-08-09 18:03:12 +0000391 Use focus_displayof to allow working with several
392 displays. Return None if application does not have
393 the focus."""
394 name = self.tk.call('focus')
395 if name == 'none' or not name: return None
396 return self._nametowidget(name)
397 def focus_displayof(self):
398 """Return the widget which has currently the focus on the
399 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000400
Fredrik Lundh06d28152000-08-09 18:03:12 +0000401 Return None if the application does not have the focus."""
402 name = self.tk.call('focus', '-displayof', self._w)
403 if name == 'none' or not name: return None
404 return self._nametowidget(name)
405 def focus_lastfor(self):
406 """Return the widget which would have the focus if top level
407 for this widget gets the focus from the window manager."""
408 name = self.tk.call('focus', '-lastfor', self._w)
409 if name == 'none' or not name: return None
410 return self._nametowidget(name)
411 def tk_focusFollowsMouse(self):
412 """The widget under mouse will get automatically focus. Can not
413 be disabled easily."""
414 self.tk.call('tk_focusFollowsMouse')
415 def tk_focusNext(self):
416 """Return the next widget in the focus order which follows
417 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000418
Fredrik Lundh06d28152000-08-09 18:03:12 +0000419 The focus order first goes to the next child, then to
420 the children of the child recursively and then to the
421 next sibling which is higher in the stacking order. A
422 widget is omitted if it has the takefocus resource set
423 to 0."""
424 name = self.tk.call('tk_focusNext', self._w)
425 if not name: return None
426 return self._nametowidget(name)
427 def tk_focusPrev(self):
428 """Return previous widget in the focus order. See tk_focusNext for details."""
429 name = self.tk.call('tk_focusPrev', self._w)
430 if not name: return None
431 return self._nametowidget(name)
432 def after(self, ms, func=None, *args):
433 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000434
Fredrik Lundh06d28152000-08-09 18:03:12 +0000435 MS specifies the time in milliseconds. FUNC gives the
436 function which shall be called. Additional parameters
437 are given as parameters to the function call. Return
438 identifier to cancel scheduling with after_cancel."""
439 if not func:
440 # I'd rather use time.sleep(ms*0.001)
441 self.tk.call('after', ms)
442 else:
443 # XXX Disgusting hack to clean up after calling func
444 tmp = []
445 def callit(func=func, args=args, self=self, tmp=tmp):
446 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000447 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000448 finally:
449 try:
450 self.deletecommand(tmp[0])
451 except TclError:
452 pass
453 name = self._register(callit)
454 tmp.append(name)
455 return self.tk.call('after', ms, name)
456 def after_idle(self, func, *args):
457 """Call FUNC once if the Tcl main loop has no event to
458 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000459
Fredrik Lundh06d28152000-08-09 18:03:12 +0000460 Return an identifier to cancel the scheduling with
461 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000462 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000463 def after_cancel(self, id):
464 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000465
Fredrik Lundh06d28152000-08-09 18:03:12 +0000466 Identifier returned by after or after_idle must be
467 given as first parameter."""
468 self.tk.call('after', 'cancel', id)
469 def bell(self, displayof=0):
470 """Ring a display's bell."""
471 self.tk.call(('bell',) + self._displayof(displayof))
472 # Clipboard handling:
473 def clipboard_clear(self, **kw):
474 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000475
Fredrik Lundh06d28152000-08-09 18:03:12 +0000476 A widget specified for the optional displayof keyword
477 argument specifies the target display."""
478 if not kw.has_key('displayof'): kw['displayof'] = self._w
479 self.tk.call(('clipboard', 'clear') + self._options(kw))
480 def clipboard_append(self, string, **kw):
481 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000482
Fredrik Lundh06d28152000-08-09 18:03:12 +0000483 A widget specified at the optional displayof keyword
484 argument specifies the target display. The clipboard
485 can be retrieved with selection_get."""
486 if not kw.has_key('displayof'): kw['displayof'] = self._w
487 self.tk.call(('clipboard', 'append') + self._options(kw)
488 + ('--', string))
489 # XXX grab current w/o window argument
490 def grab_current(self):
491 """Return widget which has currently the grab in this application
492 or None."""
493 name = self.tk.call('grab', 'current', self._w)
494 if not name: return None
495 return self._nametowidget(name)
496 def grab_release(self):
497 """Release grab for this widget if currently set."""
498 self.tk.call('grab', 'release', self._w)
499 def grab_set(self):
500 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000501
Fredrik Lundh06d28152000-08-09 18:03:12 +0000502 A grab directs all events to this and descendant
503 widgets in the application."""
504 self.tk.call('grab', 'set', self._w)
505 def grab_set_global(self):
506 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000507
Fredrik Lundh06d28152000-08-09 18:03:12 +0000508 A global grab directs all events to this and
509 descendant widgets on the display. Use with caution -
510 other applications do not get events anymore."""
511 self.tk.call('grab', 'set', '-global', self._w)
512 def grab_status(self):
513 """Return None, "local" or "global" if this widget has
514 no, a local or a global grab."""
515 status = self.tk.call('grab', 'status', self._w)
516 if status == 'none': status = None
517 return status
518 def lower(self, belowThis=None):
519 """Lower this widget in the stacking order."""
520 self.tk.call('lower', self._w, belowThis)
521 def option_add(self, pattern, value, priority = None):
522 """Set a VALUE (second parameter) for an option
523 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000524
Fredrik Lundh06d28152000-08-09 18:03:12 +0000525 An optional third parameter gives the numeric priority
526 (defaults to 80)."""
527 self.tk.call('option', 'add', pattern, value, priority)
528 def option_clear(self):
529 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000530
Fredrik Lundh06d28152000-08-09 18:03:12 +0000531 It will be reloaded if option_add is called."""
532 self.tk.call('option', 'clear')
533 def option_get(self, name, className):
534 """Return the value for an option NAME for this widget
535 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000536
Fredrik Lundh06d28152000-08-09 18:03:12 +0000537 Values with higher priority override lower values."""
538 return self.tk.call('option', 'get', self._w, name, className)
539 def option_readfile(self, fileName, priority = None):
540 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000541
Fredrik Lundh06d28152000-08-09 18:03:12 +0000542 An optional second parameter gives the numeric
543 priority."""
544 self.tk.call('option', 'readfile', fileName, priority)
545 def selection_clear(self, **kw):
546 """Clear the current X selection."""
547 if not kw.has_key('displayof'): kw['displayof'] = self._w
548 self.tk.call(('selection', 'clear') + self._options(kw))
549 def selection_get(self, **kw):
550 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000551
Fredrik Lundh06d28152000-08-09 18:03:12 +0000552 A keyword parameter selection specifies the name of
553 the selection and defaults to PRIMARY. A keyword
554 parameter displayof specifies a widget on the display
555 to use."""
556 if not kw.has_key('displayof'): kw['displayof'] = self._w
557 return self.tk.call(('selection', 'get') + self._options(kw))
558 def selection_handle(self, command, **kw):
559 """Specify a function COMMAND to call if the X
560 selection owned by this widget is queried by another
561 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000562
Fredrik Lundh06d28152000-08-09 18:03:12 +0000563 This function must return the contents of the
564 selection. The function will be called with the
565 arguments OFFSET and LENGTH which allows the chunking
566 of very long selections. The following keyword
567 parameters can be provided:
568 selection - name of the selection (default PRIMARY),
569 type - type of the selection (e.g. STRING, FILE_NAME)."""
570 name = self._register(command)
571 self.tk.call(('selection', 'handle') + self._options(kw)
572 + (self._w, name))
573 def selection_own(self, **kw):
574 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000575
Fredrik Lundh06d28152000-08-09 18:03:12 +0000576 A keyword parameter selection specifies the name of
577 the selection (default PRIMARY)."""
578 self.tk.call(('selection', 'own') +
579 self._options(kw) + (self._w,))
580 def selection_own_get(self, **kw):
581 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000582
Fredrik Lundh06d28152000-08-09 18:03:12 +0000583 The following keyword parameter can
584 be provided:
585 selection - name of the selection (default PRIMARY),
586 type - type of the selection (e.g. STRING, FILE_NAME)."""
587 if not kw.has_key('displayof'): kw['displayof'] = self._w
588 name = self.tk.call(('selection', 'own') + self._options(kw))
589 if not name: return None
590 return self._nametowidget(name)
591 def send(self, interp, cmd, *args):
592 """Send Tcl command CMD to different interpreter INTERP to be executed."""
593 return self.tk.call(('send', interp, cmd) + args)
594 def lower(self, belowThis=None):
595 """Lower this widget in the stacking order."""
596 self.tk.call('lower', self._w, belowThis)
597 def tkraise(self, aboveThis=None):
598 """Raise this widget in the stacking order."""
599 self.tk.call('raise', self._w, aboveThis)
600 lift = tkraise
601 def colormodel(self, value=None):
602 """Useless. Not implemented in Tk."""
603 return self.tk.call('tk', 'colormodel', self._w, value)
604 def winfo_atom(self, name, displayof=0):
605 """Return integer which represents atom NAME."""
606 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
607 return getint(self.tk.call(args))
608 def winfo_atomname(self, id, displayof=0):
609 """Return name of atom with identifier ID."""
610 args = ('winfo', 'atomname') \
611 + self._displayof(displayof) + (id,)
612 return self.tk.call(args)
613 def winfo_cells(self):
614 """Return number of cells in the colormap for this widget."""
615 return getint(
616 self.tk.call('winfo', 'cells', self._w))
617 def winfo_children(self):
618 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000619 result = []
620 for child in self.tk.splitlist(
621 self.tk.call('winfo', 'children', self._w)):
622 try:
623 # Tcl sometimes returns extra windows, e.g. for
624 # menus; those need to be skipped
625 result.append(self._nametowidget(child))
626 except KeyError:
627 pass
628 return result
629
Fredrik Lundh06d28152000-08-09 18:03:12 +0000630 def winfo_class(self):
631 """Return window class name of this widget."""
632 return self.tk.call('winfo', 'class', self._w)
633 def winfo_colormapfull(self):
634 """Return true if at the last color request the colormap was full."""
635 return self.tk.getboolean(
636 self.tk.call('winfo', 'colormapfull', self._w))
637 def winfo_containing(self, rootX, rootY, displayof=0):
638 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
639 args = ('winfo', 'containing') \
640 + self._displayof(displayof) + (rootX, rootY)
641 name = self.tk.call(args)
642 if not name: return None
643 return self._nametowidget(name)
644 def winfo_depth(self):
645 """Return the number of bits per pixel."""
646 return getint(self.tk.call('winfo', 'depth', self._w))
647 def winfo_exists(self):
648 """Return true if this widget exists."""
649 return getint(
650 self.tk.call('winfo', 'exists', self._w))
651 def winfo_fpixels(self, number):
652 """Return the number of pixels for the given distance NUMBER
653 (e.g. "3c") as float."""
654 return getdouble(self.tk.call(
655 'winfo', 'fpixels', self._w, number))
656 def winfo_geometry(self):
657 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
658 return self.tk.call('winfo', 'geometry', self._w)
659 def winfo_height(self):
660 """Return height of this widget."""
661 return getint(
662 self.tk.call('winfo', 'height', self._w))
663 def winfo_id(self):
664 """Return identifier ID for this widget."""
665 return self.tk.getint(
666 self.tk.call('winfo', 'id', self._w))
667 def winfo_interps(self, displayof=0):
668 """Return the name of all Tcl interpreters for this display."""
669 args = ('winfo', 'interps') + self._displayof(displayof)
670 return self.tk.splitlist(self.tk.call(args))
671 def winfo_ismapped(self):
672 """Return true if this widget is mapped."""
673 return getint(
674 self.tk.call('winfo', 'ismapped', self._w))
675 def winfo_manager(self):
676 """Return the window mananger name for this widget."""
677 return self.tk.call('winfo', 'manager', self._w)
678 def winfo_name(self):
679 """Return the name of this widget."""
680 return self.tk.call('winfo', 'name', self._w)
681 def winfo_parent(self):
682 """Return the name of the parent of this widget."""
683 return self.tk.call('winfo', 'parent', self._w)
684 def winfo_pathname(self, id, displayof=0):
685 """Return the pathname of the widget given by ID."""
686 args = ('winfo', 'pathname') \
687 + self._displayof(displayof) + (id,)
688 return self.tk.call(args)
689 def winfo_pixels(self, number):
690 """Rounded integer value of winfo_fpixels."""
691 return getint(
692 self.tk.call('winfo', 'pixels', self._w, number))
693 def winfo_pointerx(self):
694 """Return the x coordinate of the pointer on the root window."""
695 return getint(
696 self.tk.call('winfo', 'pointerx', self._w))
697 def winfo_pointerxy(self):
698 """Return a tuple of x and y coordinates of the pointer on the root window."""
699 return self._getints(
700 self.tk.call('winfo', 'pointerxy', self._w))
701 def winfo_pointery(self):
702 """Return the y coordinate of the pointer on the root window."""
703 return getint(
704 self.tk.call('winfo', 'pointery', self._w))
705 def winfo_reqheight(self):
706 """Return requested height of this widget."""
707 return getint(
708 self.tk.call('winfo', 'reqheight', self._w))
709 def winfo_reqwidth(self):
710 """Return requested width of this widget."""
711 return getint(
712 self.tk.call('winfo', 'reqwidth', self._w))
713 def winfo_rgb(self, color):
714 """Return tuple of decimal values for red, green, blue for
715 COLOR in this widget."""
716 return self._getints(
717 self.tk.call('winfo', 'rgb', self._w, color))
718 def winfo_rootx(self):
719 """Return x coordinate of upper left corner of this widget on the
720 root window."""
721 return getint(
722 self.tk.call('winfo', 'rootx', self._w))
723 def winfo_rooty(self):
724 """Return y coordinate of upper left corner of this widget on the
725 root window."""
726 return getint(
727 self.tk.call('winfo', 'rooty', self._w))
728 def winfo_screen(self):
729 """Return the screen name of this widget."""
730 return self.tk.call('winfo', 'screen', self._w)
731 def winfo_screencells(self):
732 """Return the number of the cells in the colormap of the screen
733 of this widget."""
734 return getint(
735 self.tk.call('winfo', 'screencells', self._w))
736 def winfo_screendepth(self):
737 """Return the number of bits per pixel of the root window of the
738 screen of this widget."""
739 return getint(
740 self.tk.call('winfo', 'screendepth', self._w))
741 def winfo_screenheight(self):
742 """Return the number of pixels of the height of the screen of this widget
743 in pixel."""
744 return getint(
745 self.tk.call('winfo', 'screenheight', self._w))
746 def winfo_screenmmheight(self):
747 """Return the number of pixels of the height of the screen of
748 this widget in mm."""
749 return getint(
750 self.tk.call('winfo', 'screenmmheight', self._w))
751 def winfo_screenmmwidth(self):
752 """Return the number of pixels of the width of the screen of
753 this widget in mm."""
754 return getint(
755 self.tk.call('winfo', 'screenmmwidth', self._w))
756 def winfo_screenvisual(self):
757 """Return one of the strings directcolor, grayscale, pseudocolor,
758 staticcolor, staticgray, or truecolor for the default
759 colormodel of this screen."""
760 return self.tk.call('winfo', 'screenvisual', self._w)
761 def winfo_screenwidth(self):
762 """Return the number of pixels of the width of the screen of
763 this widget in pixel."""
764 return getint(
765 self.tk.call('winfo', 'screenwidth', self._w))
766 def winfo_server(self):
767 """Return information of the X-Server of the screen of this widget in
768 the form "XmajorRminor vendor vendorVersion"."""
769 return self.tk.call('winfo', 'server', self._w)
770 def winfo_toplevel(self):
771 """Return the toplevel widget of this widget."""
772 return self._nametowidget(self.tk.call(
773 'winfo', 'toplevel', self._w))
774 def winfo_viewable(self):
775 """Return true if the widget and all its higher ancestors are mapped."""
776 return getint(
777 self.tk.call('winfo', 'viewable', self._w))
778 def winfo_visual(self):
779 """Return one of the strings directcolor, grayscale, pseudocolor,
780 staticcolor, staticgray, or truecolor for the
781 colormodel of this widget."""
782 return self.tk.call('winfo', 'visual', self._w)
783 def winfo_visualid(self):
784 """Return the X identifier for the visual for this widget."""
785 return self.tk.call('winfo', 'visualid', self._w)
786 def winfo_visualsavailable(self, includeids=0):
787 """Return a list of all visuals available for the screen
788 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000789
Fredrik Lundh06d28152000-08-09 18:03:12 +0000790 Each item in the list consists of a visual name (see winfo_visual), a
791 depth and if INCLUDEIDS=1 is given also the X identifier."""
792 data = self.tk.split(
793 self.tk.call('winfo', 'visualsavailable', self._w,
794 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000795 if type(data) is StringType:
796 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000797 return map(self.__winfo_parseitem, data)
798 def __winfo_parseitem(self, t):
799 """Internal function."""
800 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
801 def __winfo_getint(self, x):
802 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000803 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000804 def winfo_vrootheight(self):
805 """Return the height of the virtual root window associated with this
806 widget in pixels. If there is no virtual root window return the
807 height of the screen."""
808 return getint(
809 self.tk.call('winfo', 'vrootheight', self._w))
810 def winfo_vrootwidth(self):
811 """Return the width of the virtual root window associated with this
812 widget in pixel. If there is no virtual root window return the
813 width of the screen."""
814 return getint(
815 self.tk.call('winfo', 'vrootwidth', self._w))
816 def winfo_vrootx(self):
817 """Return the x offset of the virtual root relative to the root
818 window of the screen of this widget."""
819 return getint(
820 self.tk.call('winfo', 'vrootx', self._w))
821 def winfo_vrooty(self):
822 """Return the y offset of the virtual root relative to the root
823 window of the screen of this widget."""
824 return getint(
825 self.tk.call('winfo', 'vrooty', self._w))
826 def winfo_width(self):
827 """Return the width of this widget."""
828 return getint(
829 self.tk.call('winfo', 'width', self._w))
830 def winfo_x(self):
831 """Return the x coordinate of the upper left corner of this widget
832 in the parent."""
833 return getint(
834 self.tk.call('winfo', 'x', self._w))
835 def winfo_y(self):
836 """Return the y coordinate of the upper left corner of this widget
837 in the parent."""
838 return getint(
839 self.tk.call('winfo', 'y', self._w))
840 def update(self):
841 """Enter event loop until all pending events have been processed by Tcl."""
842 self.tk.call('update')
843 def update_idletasks(self):
844 """Enter event loop until all idle callbacks have been called. This
845 will update the display of windows but not process events caused by
846 the user."""
847 self.tk.call('update', 'idletasks')
848 def bindtags(self, tagList=None):
849 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000850
Fredrik Lundh06d28152000-08-09 18:03:12 +0000851 With no argument return the list of all bindtags associated with
852 this widget. With a list of strings as argument the bindtags are
853 set to this list. The bindtags determine in which order events are
854 processed (see bind)."""
855 if tagList is None:
856 return self.tk.splitlist(
857 self.tk.call('bindtags', self._w))
858 else:
859 self.tk.call('bindtags', self._w, tagList)
860 def _bind(self, what, sequence, func, add, needcleanup=1):
861 """Internal function."""
862 if type(func) is StringType:
863 self.tk.call(what + (sequence, func))
864 elif func:
865 funcid = self._register(func, self._substitute,
866 needcleanup)
867 cmd = ('%sif {"[%s %s]" == "break"} break\n'
868 %
869 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000870 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000871 self.tk.call(what + (sequence, cmd))
872 return funcid
873 elif sequence:
874 return self.tk.call(what + (sequence,))
875 else:
876 return self.tk.splitlist(self.tk.call(what))
877 def bind(self, sequence=None, func=None, add=None):
878 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000879
Fredrik Lundh06d28152000-08-09 18:03:12 +0000880 SEQUENCE is a string of concatenated event
881 patterns. An event pattern is of the form
882 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
883 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
884 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
885 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
886 Mod1, M1. TYPE is one of Activate, Enter, Map,
887 ButtonPress, Button, Expose, Motion, ButtonRelease
888 FocusIn, MouseWheel, Circulate, FocusOut, Property,
889 Colormap, Gravity Reparent, Configure, KeyPress, Key,
890 Unmap, Deactivate, KeyRelease Visibility, Destroy,
891 Leave and DETAIL is the button number for ButtonPress,
892 ButtonRelease and DETAIL is the Keysym for KeyPress and
893 KeyRelease. Examples are
894 <Control-Button-1> for pressing Control and mouse button 1 or
895 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
896 An event pattern can also be a virtual event of the form
897 <<AString>> where AString can be arbitrary. This
898 event can be generated by event_generate.
899 If events are concatenated they must appear shortly
900 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000901
Fredrik Lundh06d28152000-08-09 18:03:12 +0000902 FUNC will be called if the event sequence occurs with an
903 instance of Event as argument. If the return value of FUNC is
904 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000905
Fredrik Lundh06d28152000-08-09 18:03:12 +0000906 An additional boolean parameter ADD specifies whether FUNC will
907 be called additionally to the other bound function or whether
908 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000909
Fredrik Lundh06d28152000-08-09 18:03:12 +0000910 Bind will return an identifier to allow deletion of the bound function with
911 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000912
Fredrik Lundh06d28152000-08-09 18:03:12 +0000913 If FUNC or SEQUENCE is omitted the bound function or list
914 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000915
Fredrik Lundh06d28152000-08-09 18:03:12 +0000916 return self._bind(('bind', self._w), sequence, func, add)
917 def unbind(self, sequence, funcid=None):
918 """Unbind for this widget for event SEQUENCE the
919 function identified with FUNCID."""
920 self.tk.call('bind', self._w, sequence, '')
921 if funcid:
922 self.deletecommand(funcid)
923 def bind_all(self, sequence=None, func=None, add=None):
924 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
925 An additional boolean parameter ADD specifies whether FUNC will
926 be called additionally to the other bound function or whether
927 it will replace the previous function. See bind for the return value."""
928 return self._bind(('bind', 'all'), sequence, func, add, 0)
929 def unbind_all(self, sequence):
930 """Unbind for all widgets for event SEQUENCE all functions."""
931 self.tk.call('bind', 'all' , sequence, '')
932 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000933
Fredrik Lundh06d28152000-08-09 18:03:12 +0000934 """Bind to widgets with bindtag CLASSNAME at event
935 SEQUENCE a call of function FUNC. An additional
936 boolean parameter ADD specifies whether FUNC will be
937 called additionally to the other bound function or
938 whether it will replace the previous function. See bind for
939 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000940
Fredrik Lundh06d28152000-08-09 18:03:12 +0000941 return self._bind(('bind', className), sequence, func, add, 0)
942 def unbind_class(self, className, sequence):
943 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
944 all functions."""
945 self.tk.call('bind', className , sequence, '')
946 def mainloop(self, n=0):
947 """Call the mainloop of Tk."""
948 self.tk.mainloop(n)
949 def quit(self):
950 """Quit the Tcl interpreter. All widgets will be destroyed."""
951 self.tk.quit()
952 def _getints(self, string):
953 """Internal function."""
954 if string:
955 return tuple(map(getint, self.tk.splitlist(string)))
956 def _getdoubles(self, string):
957 """Internal function."""
958 if string:
959 return tuple(map(getdouble, self.tk.splitlist(string)))
960 def _getboolean(self, string):
961 """Internal function."""
962 if string:
963 return self.tk.getboolean(string)
964 def _displayof(self, displayof):
965 """Internal function."""
966 if displayof:
967 return ('-displayof', displayof)
968 if displayof is None:
969 return ('-displayof', self._w)
970 return ()
971 def _options(self, cnf, kw = None):
972 """Internal function."""
973 if kw:
974 cnf = _cnfmerge((cnf, kw))
975 else:
976 cnf = _cnfmerge(cnf)
977 res = ()
978 for k, v in cnf.items():
979 if v is not None:
980 if k[-1] == '_': k = k[:-1]
981 if callable(v):
982 v = self._register(v)
983 res = res + ('-'+k, v)
984 return res
985 def nametowidget(self, name):
986 """Return the Tkinter instance of a widget identified by
987 its Tcl name NAME."""
988 w = self
989 if name[0] == '.':
990 w = w._root()
991 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000992 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000993 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +0000994 if i >= 0:
995 name, tail = name[:i], name[i+1:]
996 else:
997 tail = ''
998 w = w.children[name]
999 name = tail
1000 return w
1001 _nametowidget = nametowidget
1002 def _register(self, func, subst=None, needcleanup=1):
1003 """Return a newly created Tcl function. If this
1004 function is called, the Python function FUNC will
1005 be executed. An optional function SUBST can
1006 be given which will be executed before FUNC."""
1007 f = CallWrapper(func, subst, self).__call__
1008 name = `id(f)`
1009 try:
1010 func = func.im_func
1011 except AttributeError:
1012 pass
1013 try:
1014 name = name + func.__name__
1015 except AttributeError:
1016 pass
1017 self.tk.createcommand(name, f)
1018 if needcleanup:
1019 if self._tclCommands is None:
1020 self._tclCommands = []
1021 self._tclCommands.append(name)
1022 #print '+ Tkinter created command', name
1023 return name
1024 register = _register
1025 def _root(self):
1026 """Internal function."""
1027 w = self
1028 while w.master: w = w.master
1029 return w
1030 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1031 '%s', '%t', '%w', '%x', '%y',
1032 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001033 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001034 def _substitute(self, *args):
1035 """Internal function."""
1036 if len(args) != len(self._subst_format): return args
1037 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001038
Fredrik Lundh06d28152000-08-09 18:03:12 +00001039 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001040 def getint_event(s):
1041 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1042 try:
1043 return int(s)
1044 except ValueError:
1045 return s
1046
Fredrik Lundh06d28152000-08-09 18:03:12 +00001047 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1048 # Missing: (a, c, d, m, o, v, B, R)
1049 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001050 # serial field: valid vor all events
1051 # number of button: ButtonPress and ButtonRelease events only
1052 # height field: Configure, ConfigureRequest, Create,
1053 # ResizeRequest, and Expose events only
1054 # keycode field: KeyPress and KeyRelease events only
1055 # time field: "valid for events that contain a time field"
1056 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1057 # and Expose events only
1058 # x field: "valid for events that contain a x field"
1059 # y field: "valid for events that contain a y field"
1060 # keysym as decimal: KeyPress and KeyRelease events only
1061 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1062 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001063 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001064 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001065 try: e.focus = getboolean(f)
1066 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001067 e.height = getint_event(h)
1068 e.keycode = getint_event(k)
1069 e.state = getint_event(s)
1070 e.time = getint_event(t)
1071 e.width = getint_event(w)
1072 e.x = getint_event(x)
1073 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001074 e.char = A
1075 try: e.send_event = getboolean(E)
1076 except TclError: pass
1077 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001078 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001079 e.type = T
1080 try:
1081 e.widget = self._nametowidget(W)
1082 except KeyError:
1083 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001084 e.x_root = getint_event(X)
1085 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001086 try:
1087 e.delta = getint(D)
1088 except ValueError:
1089 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001090 return (e,)
1091 def _report_exception(self):
1092 """Internal function."""
1093 import sys
1094 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1095 root = self._root()
1096 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001097 def _configure(self, cmd, cnf, kw):
1098 """Internal function."""
1099 if kw:
1100 cnf = _cnfmerge((cnf, kw))
1101 elif cnf:
1102 cnf = _cnfmerge(cnf)
1103 if cnf is None:
1104 cnf = {}
1105 for x in self.tk.split(
1106 self.tk.call(_flatten((self._w, cmd)))):
1107 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1108 return cnf
1109 if type(cnf) is StringType:
1110 x = self.tk.split(
1111 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1112 return (x[0][1:],) + x[1:]
1113 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001114 # These used to be defined in Widget:
1115 def configure(self, cnf=None, **kw):
1116 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001117
Fredrik Lundh06d28152000-08-09 18:03:12 +00001118 The values for resources are specified as keyword
1119 arguments. To get an overview about
1120 the allowed keyword arguments call the method keys.
1121 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001122 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001123 config = configure
1124 def cget(self, key):
1125 """Return the resource value for a KEY given as string."""
1126 return self.tk.call(self._w, 'cget', '-' + key)
1127 __getitem__ = cget
1128 def __setitem__(self, key, value):
1129 self.configure({key: value})
1130 def keys(self):
1131 """Return a list of all resource names of this widget."""
1132 return map(lambda x: x[0][1:],
1133 self.tk.split(self.tk.call(self._w, 'configure')))
1134 def __str__(self):
1135 """Return the window path name of this widget."""
1136 return self._w
1137 # Pack methods that apply to the master
1138 _noarg_ = ['_noarg_']
1139 def pack_propagate(self, flag=_noarg_):
1140 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001141
Fredrik Lundh06d28152000-08-09 18:03:12 +00001142 A boolean argument specifies whether the geometry information
1143 of the slaves will determine the size of this widget. If no argument
1144 is given the current setting will be returned.
1145 """
1146 if flag is Misc._noarg_:
1147 return self._getboolean(self.tk.call(
1148 'pack', 'propagate', self._w))
1149 else:
1150 self.tk.call('pack', 'propagate', self._w, flag)
1151 propagate = pack_propagate
1152 def pack_slaves(self):
1153 """Return a list of all slaves of this widget
1154 in its packing order."""
1155 return map(self._nametowidget,
1156 self.tk.splitlist(
1157 self.tk.call('pack', 'slaves', self._w)))
1158 slaves = pack_slaves
1159 # Place method that applies to the master
1160 def place_slaves(self):
1161 """Return a list of all slaves of this widget
1162 in its packing order."""
1163 return map(self._nametowidget,
1164 self.tk.splitlist(
1165 self.tk.call(
1166 'place', 'slaves', self._w)))
1167 # Grid methods that apply to the master
1168 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1169 """Return a tuple of integer coordinates for the bounding
1170 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001171
Fredrik Lundh06d28152000-08-09 18:03:12 +00001172 If COLUMN, ROW is given the bounding box applies from
1173 the cell with row and column 0 to the specified
1174 cell. If COL2 and ROW2 are given the bounding box
1175 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001176
Fredrik Lundh06d28152000-08-09 18:03:12 +00001177 The returned integers specify the offset of the upper left
1178 corner in the master widget and the width and height.
1179 """
1180 args = ('grid', 'bbox', self._w)
1181 if column is not None and row is not None:
1182 args = args + (column, row)
1183 if col2 is not None and row2 is not None:
1184 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001185 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001186
Fredrik Lundh06d28152000-08-09 18:03:12 +00001187 bbox = grid_bbox
1188 def _grid_configure(self, command, index, cnf, kw):
1189 """Internal function."""
1190 if type(cnf) is StringType and not kw:
1191 if cnf[-1:] == '_':
1192 cnf = cnf[:-1]
1193 if cnf[:1] != '-':
1194 cnf = '-'+cnf
1195 options = (cnf,)
1196 else:
1197 options = self._options(cnf, kw)
1198 if not options:
1199 res = self.tk.call('grid',
1200 command, self._w, index)
1201 words = self.tk.splitlist(res)
1202 dict = {}
1203 for i in range(0, len(words), 2):
1204 key = words[i][1:]
1205 value = words[i+1]
1206 if not value:
1207 value = None
1208 elif '.' in value:
1209 value = getdouble(value)
1210 else:
1211 value = getint(value)
1212 dict[key] = value
1213 return dict
1214 res = self.tk.call(
1215 ('grid', command, self._w, index)
1216 + options)
1217 if len(options) == 1:
1218 if not res: return None
1219 # In Tk 7.5, -width can be a float
1220 if '.' in res: return getdouble(res)
1221 return getint(res)
1222 def grid_columnconfigure(self, index, cnf={}, **kw):
1223 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001224
Fredrik Lundh06d28152000-08-09 18:03:12 +00001225 Valid resources are minsize (minimum size of the column),
1226 weight (how much does additional space propagate to this column)
1227 and pad (how much space to let additionally)."""
1228 return self._grid_configure('columnconfigure', index, cnf, kw)
1229 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001230 def grid_location(self, x, y):
1231 """Return a tuple of column and row which identify the cell
1232 at which the pixel at position X and Y inside the master
1233 widget is located."""
1234 return self._getints(
1235 self.tk.call(
1236 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001237 def grid_propagate(self, flag=_noarg_):
1238 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001239
Fredrik Lundh06d28152000-08-09 18:03:12 +00001240 A boolean argument specifies whether the geometry information
1241 of the slaves will determine the size of this widget. If no argument
1242 is given, the current setting will be returned.
1243 """
1244 if flag is Misc._noarg_:
1245 return self._getboolean(self.tk.call(
1246 'grid', 'propagate', self._w))
1247 else:
1248 self.tk.call('grid', 'propagate', self._w, flag)
1249 def grid_rowconfigure(self, index, cnf={}, **kw):
1250 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001251
Fredrik Lundh06d28152000-08-09 18:03:12 +00001252 Valid resources are minsize (minimum size of the row),
1253 weight (how much does additional space propagate to this row)
1254 and pad (how much space to let additionally)."""
1255 return self._grid_configure('rowconfigure', index, cnf, kw)
1256 rowconfigure = grid_rowconfigure
1257 def grid_size(self):
1258 """Return a tuple of the number of column and rows in the grid."""
1259 return self._getints(
1260 self.tk.call('grid', 'size', self._w)) or None
1261 size = grid_size
1262 def grid_slaves(self, row=None, column=None):
1263 """Return a list of all slaves of this widget
1264 in its packing order."""
1265 args = ()
1266 if row is not None:
1267 args = args + ('-row', row)
1268 if column is not None:
1269 args = args + ('-column', column)
1270 return map(self._nametowidget,
1271 self.tk.splitlist(self.tk.call(
1272 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001273
Fredrik Lundh06d28152000-08-09 18:03:12 +00001274 # Support for the "event" command, new in Tk 4.2.
1275 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001276
Fredrik Lundh06d28152000-08-09 18:03:12 +00001277 def event_add(self, virtual, *sequences):
1278 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1279 to an event SEQUENCE such that the virtual event is triggered
1280 whenever SEQUENCE occurs."""
1281 args = ('event', 'add', virtual) + sequences
1282 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001283
Fredrik Lundh06d28152000-08-09 18:03:12 +00001284 def event_delete(self, virtual, *sequences):
1285 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1286 args = ('event', 'delete', virtual) + sequences
1287 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001288
Fredrik Lundh06d28152000-08-09 18:03:12 +00001289 def event_generate(self, sequence, **kw):
1290 """Generate an event SEQUENCE. Additional
1291 keyword arguments specify parameter of the event
1292 (e.g. x, y, rootx, rooty)."""
1293 args = ('event', 'generate', self._w, sequence)
1294 for k, v in kw.items():
1295 args = args + ('-%s' % k, str(v))
1296 self.tk.call(args)
1297
1298 def event_info(self, virtual=None):
1299 """Return a list of all virtual events or the information
1300 about the SEQUENCE bound to the virtual event VIRTUAL."""
1301 return self.tk.splitlist(
1302 self.tk.call('event', 'info', virtual))
1303
1304 # Image related commands
1305
1306 def image_names(self):
1307 """Return a list of all existing image names."""
1308 return self.tk.call('image', 'names')
1309
1310 def image_types(self):
1311 """Return a list of all available image types (e.g. phote bitmap)."""
1312 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001313
Guido van Rossum80f8be81997-12-02 19:51:39 +00001314
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001315class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001316 """Internal class. Stores function to call when some user
1317 defined Tcl function is called e.g. after an event occurred."""
1318 def __init__(self, func, subst, widget):
1319 """Store FUNC, SUBST and WIDGET as members."""
1320 self.func = func
1321 self.subst = subst
1322 self.widget = widget
1323 def __call__(self, *args):
1324 """Apply first function SUBST to arguments, than FUNC."""
1325 try:
1326 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001327 args = self.subst(*args)
1328 return self.func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001329 except SystemExit, msg:
1330 raise SystemExit, msg
1331 except:
1332 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001333
Guido van Rossume365a591998-05-01 19:48:20 +00001334
Guido van Rossum18468821994-06-20 07:49:28 +00001335class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001336 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001337
Fredrik Lundh06d28152000-08-09 18:03:12 +00001338 def wm_aspect(self,
1339 minNumer=None, minDenom=None,
1340 maxNumer=None, maxDenom=None):
1341 """Instruct the window manager to set the aspect ratio (width/height)
1342 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1343 of the actual values if no argument is given."""
1344 return self._getints(
1345 self.tk.call('wm', 'aspect', self._w,
1346 minNumer, minDenom,
1347 maxNumer, maxDenom))
1348 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001349
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001350 def wm_attributes(self, *args):
1351 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001352
1353 The first form returns a list of the platform specific flags and
1354 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001355 option. The third form sets one or more of the values. The values
1356 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001357
1358 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001359 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001360 to toolwindow (as defined in the MSDN). -topmost gets or sets
1361 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001362 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001363
1364 On Macintosh, XXXXX
1365
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001366 On Unix, there are currently no special attribute values.
1367 """
1368 args = ('wm', 'attributes', self._w) + args
1369 return self.tk.call(args)
1370 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001371
Fredrik Lundh06d28152000-08-09 18:03:12 +00001372 def wm_client(self, name=None):
1373 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1374 current value."""
1375 return self.tk.call('wm', 'client', self._w, name)
1376 client = wm_client
1377 def wm_colormapwindows(self, *wlist):
1378 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1379 of this widget. This list contains windows whose colormaps differ from their
1380 parents. Return current list of widgets if WLIST is empty."""
1381 if len(wlist) > 1:
1382 wlist = (wlist,) # Tk needs a list of windows here
1383 args = ('wm', 'colormapwindows', self._w) + wlist
1384 return map(self._nametowidget, self.tk.call(args))
1385 colormapwindows = wm_colormapwindows
1386 def wm_command(self, value=None):
1387 """Store VALUE in WM_COMMAND property. It is the command
1388 which shall be used to invoke the application. Return current
1389 command if VALUE is None."""
1390 return self.tk.call('wm', 'command', self._w, value)
1391 command = wm_command
1392 def wm_deiconify(self):
1393 """Deiconify this widget. If it was never mapped it will not be mapped.
1394 On Windows it will raise this widget and give it the focus."""
1395 return self.tk.call('wm', 'deiconify', self._w)
1396 deiconify = wm_deiconify
1397 def wm_focusmodel(self, model=None):
1398 """Set focus model to MODEL. "active" means that this widget will claim
1399 the focus itself, "passive" means that the window manager shall give
1400 the focus. Return current focus model if MODEL is None."""
1401 return self.tk.call('wm', 'focusmodel', self._w, model)
1402 focusmodel = wm_focusmodel
1403 def wm_frame(self):
1404 """Return identifier for decorative frame of this widget if present."""
1405 return self.tk.call('wm', 'frame', self._w)
1406 frame = wm_frame
1407 def wm_geometry(self, newGeometry=None):
1408 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1409 current value if None is given."""
1410 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1411 geometry = wm_geometry
1412 def wm_grid(self,
1413 baseWidth=None, baseHeight=None,
1414 widthInc=None, heightInc=None):
1415 """Instruct the window manager that this widget shall only be
1416 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1417 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1418 number of grid units requested in Tk_GeometryRequest."""
1419 return self._getints(self.tk.call(
1420 'wm', 'grid', self._w,
1421 baseWidth, baseHeight, widthInc, heightInc))
1422 grid = wm_grid
1423 def wm_group(self, pathName=None):
1424 """Set the group leader widgets for related widgets to PATHNAME. Return
1425 the group leader of this widget if None is given."""
1426 return self.tk.call('wm', 'group', self._w, pathName)
1427 group = wm_group
1428 def wm_iconbitmap(self, bitmap=None):
1429 """Set bitmap for the iconified widget to BITMAP. Return
1430 the bitmap if None is given."""
1431 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1432 iconbitmap = wm_iconbitmap
1433 def wm_iconify(self):
1434 """Display widget as icon."""
1435 return self.tk.call('wm', 'iconify', self._w)
1436 iconify = wm_iconify
1437 def wm_iconmask(self, bitmap=None):
1438 """Set mask for the icon bitmap of this widget. Return the
1439 mask if None is given."""
1440 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1441 iconmask = wm_iconmask
1442 def wm_iconname(self, newName=None):
1443 """Set the name of the icon for this widget. Return the name if
1444 None is given."""
1445 return self.tk.call('wm', 'iconname', self._w, newName)
1446 iconname = wm_iconname
1447 def wm_iconposition(self, x=None, y=None):
1448 """Set the position of the icon of this widget to X and Y. Return
1449 a tuple of the current values of X and X if None is given."""
1450 return self._getints(self.tk.call(
1451 'wm', 'iconposition', self._w, x, y))
1452 iconposition = wm_iconposition
1453 def wm_iconwindow(self, pathName=None):
1454 """Set widget PATHNAME to be displayed instead of icon. Return the current
1455 value if None is given."""
1456 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1457 iconwindow = wm_iconwindow
1458 def wm_maxsize(self, width=None, height=None):
1459 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1460 the values are given in grid units. Return the current values if None
1461 is given."""
1462 return self._getints(self.tk.call(
1463 'wm', 'maxsize', self._w, width, height))
1464 maxsize = wm_maxsize
1465 def wm_minsize(self, width=None, height=None):
1466 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1467 the values are given in grid units. Return the current values if None
1468 is given."""
1469 return self._getints(self.tk.call(
1470 'wm', 'minsize', self._w, width, height))
1471 minsize = wm_minsize
1472 def wm_overrideredirect(self, boolean=None):
1473 """Instruct the window manager to ignore this widget
1474 if BOOLEAN is given with 1. Return the current value if None
1475 is given."""
1476 return self._getboolean(self.tk.call(
1477 'wm', 'overrideredirect', self._w, boolean))
1478 overrideredirect = wm_overrideredirect
1479 def wm_positionfrom(self, who=None):
1480 """Instruct the window manager that the position of this widget shall
1481 be defined by the user if WHO is "user", and by its own policy if WHO is
1482 "program"."""
1483 return self.tk.call('wm', 'positionfrom', self._w, who)
1484 positionfrom = wm_positionfrom
1485 def wm_protocol(self, name=None, func=None):
1486 """Bind function FUNC to command NAME for this widget.
1487 Return the function bound to NAME if None is given. NAME could be
1488 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1489 if callable(func):
1490 command = self._register(func)
1491 else:
1492 command = func
1493 return self.tk.call(
1494 'wm', 'protocol', self._w, name, command)
1495 protocol = wm_protocol
1496 def wm_resizable(self, width=None, height=None):
1497 """Instruct the window manager whether this width can be resized
1498 in WIDTH or HEIGHT. Both values are boolean values."""
1499 return self.tk.call('wm', 'resizable', self._w, width, height)
1500 resizable = wm_resizable
1501 def wm_sizefrom(self, who=None):
1502 """Instruct the window manager that the size of this widget shall
1503 be defined by the user if WHO is "user", and by its own policy if WHO is
1504 "program"."""
1505 return self.tk.call('wm', 'sizefrom', self._w, who)
1506 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001507 def wm_state(self, newstate=None):
1508 """Query or set the state of this widget as one of normal, icon,
1509 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1510 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001511 state = wm_state
1512 def wm_title(self, string=None):
1513 """Set the title of this widget."""
1514 return self.tk.call('wm', 'title', self._w, string)
1515 title = wm_title
1516 def wm_transient(self, master=None):
1517 """Instruct the window manager that this widget is transient
1518 with regard to widget MASTER."""
1519 return self.tk.call('wm', 'transient', self._w, master)
1520 transient = wm_transient
1521 def wm_withdraw(self):
1522 """Withdraw this widget from the screen such that it is unmapped
1523 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1524 return self.tk.call('wm', 'withdraw', self._w)
1525 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001526
Guido van Rossum18468821994-06-20 07:49:28 +00001527
1528class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001529 """Toplevel widget of Tk which represents mostly the main window
1530 of an appliation. It has an associated Tcl interpreter."""
1531 _w = '.'
1532 def __init__(self, screenName=None, baseName=None, className='Tk'):
1533 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1534 be created. BASENAME will be used for the identification of the profile file (see
1535 readprofile).
1536 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1537 is the name of the widget class."""
1538 global _default_root
1539 self.master = None
1540 self.children = {}
1541 if baseName is None:
1542 import sys, os
1543 baseName = os.path.basename(sys.argv[0])
1544 baseName, ext = os.path.splitext(baseName)
1545 if ext not in ('.py', '.pyc', '.pyo'):
1546 baseName = baseName + ext
1547 self.tk = _tkinter.create(screenName, baseName, className)
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001548 self.tk.wantobjects(wantobjects)
Jack Jansenbe92af02001-08-23 13:25:59 +00001549 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001550 # Disable event scanning except for Command-Period
1551 _MacOS.SchedParams(1, 0)
1552 # Work around nasty MacTk bug
1553 # XXX Is this one still needed?
1554 self.update()
1555 # Version sanity checks
1556 tk_version = self.tk.getvar('tk_version')
1557 if tk_version != _tkinter.TK_VERSION:
1558 raise RuntimeError, \
1559 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1560 % (_tkinter.TK_VERSION, tk_version)
1561 tcl_version = self.tk.getvar('tcl_version')
1562 if tcl_version != _tkinter.TCL_VERSION:
1563 raise RuntimeError, \
1564 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1565 % (_tkinter.TCL_VERSION, tcl_version)
1566 if TkVersion < 4.0:
1567 raise RuntimeError, \
1568 "Tk 4.0 or higher is required; found Tk %s" \
1569 % str(TkVersion)
1570 self.tk.createcommand('tkerror', _tkerror)
1571 self.tk.createcommand('exit', _exit)
1572 self.readprofile(baseName, className)
1573 if _support_default_root and not _default_root:
1574 _default_root = self
1575 self.protocol("WM_DELETE_WINDOW", self.destroy)
1576 def destroy(self):
1577 """Destroy this and all descendants widgets. This will
1578 end the application of this Tcl interpreter."""
1579 for c in self.children.values(): c.destroy()
1580 self.tk.call('destroy', self._w)
1581 Misc.destroy(self)
1582 global _default_root
1583 if _support_default_root and _default_root is self:
1584 _default_root = None
1585 def readprofile(self, baseName, className):
1586 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1587 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1588 such a file exists in the home directory."""
1589 import os
1590 if os.environ.has_key('HOME'): home = os.environ['HOME']
1591 else: home = os.curdir
1592 class_tcl = os.path.join(home, '.%s.tcl' % className)
1593 class_py = os.path.join(home, '.%s.py' % className)
1594 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1595 base_py = os.path.join(home, '.%s.py' % baseName)
1596 dir = {'self': self}
1597 exec 'from Tkinter import *' in dir
1598 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001599 self.tk.call('source', class_tcl)
1600 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001601 execfile(class_py, dir)
1602 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001603 self.tk.call('source', base_tcl)
1604 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001605 execfile(base_py, dir)
1606 def report_callback_exception(self, exc, val, tb):
1607 """Internal function. It reports exception on sys.stderr."""
1608 import traceback, sys
1609 sys.stderr.write("Exception in Tkinter callback\n")
1610 sys.last_type = exc
1611 sys.last_value = val
1612 sys.last_traceback = tb
1613 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001614
Guido van Rossum368e06b1997-11-07 20:38:49 +00001615# Ideally, the classes Pack, Place and Grid disappear, the
1616# pack/place/grid methods are defined on the Widget class, and
1617# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1618# ...), with pack(), place() and grid() being short for
1619# pack_configure(), place_configure() and grid_columnconfigure(), and
1620# forget() being short for pack_forget(). As a practical matter, I'm
1621# afraid that there is too much code out there that may be using the
1622# Pack, Place or Grid class, so I leave them intact -- but only as
1623# backwards compatibility features. Also note that those methods that
1624# take a master as argument (e.g. pack_propagate) have been moved to
1625# the Misc class (which now incorporates all methods common between
1626# toplevel and interior widgets). Again, for compatibility, these are
1627# copied into the Pack, Place or Grid class.
1628
Guido van Rossum18468821994-06-20 07:49:28 +00001629class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001630 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001631
Fredrik Lundh06d28152000-08-09 18:03:12 +00001632 Base class to use the methods pack_* in every widget."""
1633 def pack_configure(self, cnf={}, **kw):
1634 """Pack a widget in the parent widget. Use as options:
1635 after=widget - pack it after you have packed widget
1636 anchor=NSEW (or subset) - position widget according to
1637 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001638 before=widget - pack it before you will pack widget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001639 expand=1 or 0 - expand widget if parent size grows
1640 fill=NONE or X or Y or BOTH - fill widget if widget grows
1641 in=master - use master to contain this widget
1642 ipadx=amount - add internal padding in x direction
1643 ipady=amount - add internal padding in y direction
1644 padx=amount - add padding in x direction
1645 pady=amount - add padding in y direction
1646 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1647 """
1648 self.tk.call(
1649 ('pack', 'configure', self._w)
1650 + self._options(cnf, kw))
1651 pack = configure = config = pack_configure
1652 def pack_forget(self):
1653 """Unmap this widget and do not use it for the packing order."""
1654 self.tk.call('pack', 'forget', self._w)
1655 forget = pack_forget
1656 def pack_info(self):
1657 """Return information about the packing options
1658 for this widget."""
1659 words = self.tk.splitlist(
1660 self.tk.call('pack', 'info', self._w))
1661 dict = {}
1662 for i in range(0, len(words), 2):
1663 key = words[i][1:]
1664 value = words[i+1]
1665 if value[:1] == '.':
1666 value = self._nametowidget(value)
1667 dict[key] = value
1668 return dict
1669 info = pack_info
1670 propagate = pack_propagate = Misc.pack_propagate
1671 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001672
1673class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001674 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001675
Fredrik Lundh06d28152000-08-09 18:03:12 +00001676 Base class to use the methods place_* in every widget."""
1677 def place_configure(self, cnf={}, **kw):
1678 """Place a widget in the parent widget. Use as options:
1679 in=master - master relative to which the widget is placed.
1680 x=amount - locate anchor of this widget at position x of master
1681 y=amount - locate anchor of this widget at position y of master
1682 relx=amount - locate anchor of this widget between 0.0 and 1.0
1683 relative to width of master (1.0 is right edge)
1684 rely=amount - locate anchor of this widget between 0.0 and 1.0
1685 relative to height of master (1.0 is bottom edge)
1686 anchor=NSEW (or subset) - position anchor according to given direction
1687 width=amount - width of this widget in pixel
1688 height=amount - height of this widget in pixel
1689 relwidth=amount - width of this widget between 0.0 and 1.0
1690 relative to width of master (1.0 is the same width
1691 as the master)
1692 relheight=amount - height of this widget between 0.0 and 1.0
1693 relative to height of master (1.0 is the same
1694 height as the master)
1695 bordermode="inside" or "outside" - whether to take border width of master widget
1696 into account
1697 """
1698 for k in ['in_']:
1699 if kw.has_key(k):
1700 kw[k[:-1]] = kw[k]
1701 del kw[k]
1702 self.tk.call(
1703 ('place', 'configure', self._w)
1704 + self._options(cnf, kw))
1705 place = configure = config = place_configure
1706 def place_forget(self):
1707 """Unmap this widget."""
1708 self.tk.call('place', 'forget', self._w)
1709 forget = place_forget
1710 def place_info(self):
1711 """Return information about the placing options
1712 for this widget."""
1713 words = self.tk.splitlist(
1714 self.tk.call('place', 'info', self._w))
1715 dict = {}
1716 for i in range(0, len(words), 2):
1717 key = words[i][1:]
1718 value = words[i+1]
1719 if value[:1] == '.':
1720 value = self._nametowidget(value)
1721 dict[key] = value
1722 return dict
1723 info = place_info
1724 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001725
Guido van Rossum37dcab11996-05-16 16:00:19 +00001726class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001727 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001728
Fredrik Lundh06d28152000-08-09 18:03:12 +00001729 Base class to use the methods grid_* in every widget."""
1730 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1731 def grid_configure(self, cnf={}, **kw):
1732 """Position a widget in the parent widget in a grid. Use as options:
1733 column=number - use cell identified with given column (starting with 0)
1734 columnspan=number - this widget will span several columns
1735 in=master - use master to contain this widget
1736 ipadx=amount - add internal padding in x direction
1737 ipady=amount - add internal padding in y direction
1738 padx=amount - add padding in x direction
1739 pady=amount - add padding in y direction
1740 row=number - use cell identified with given row (starting with 0)
1741 rowspan=number - this widget will span several rows
1742 sticky=NSEW - if cell is larger on which sides will this
1743 widget stick to the cell boundary
1744 """
1745 self.tk.call(
1746 ('grid', 'configure', self._w)
1747 + self._options(cnf, kw))
1748 grid = configure = config = grid_configure
1749 bbox = grid_bbox = Misc.grid_bbox
1750 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1751 def grid_forget(self):
1752 """Unmap this widget."""
1753 self.tk.call('grid', 'forget', self._w)
1754 forget = grid_forget
1755 def grid_remove(self):
1756 """Unmap this widget but remember the grid options."""
1757 self.tk.call('grid', 'remove', self._w)
1758 def grid_info(self):
1759 """Return information about the options
1760 for positioning this widget in a grid."""
1761 words = self.tk.splitlist(
1762 self.tk.call('grid', 'info', self._w))
1763 dict = {}
1764 for i in range(0, len(words), 2):
1765 key = words[i][1:]
1766 value = words[i+1]
1767 if value[:1] == '.':
1768 value = self._nametowidget(value)
1769 dict[key] = value
1770 return dict
1771 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001772 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001773 propagate = grid_propagate = Misc.grid_propagate
1774 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1775 size = grid_size = Misc.grid_size
1776 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001777
Guido van Rossum368e06b1997-11-07 20:38:49 +00001778class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001779 """Internal class."""
1780 def _setup(self, master, cnf):
1781 """Internal function. Sets up information about children."""
1782 if _support_default_root:
1783 global _default_root
1784 if not master:
1785 if not _default_root:
1786 _default_root = Tk()
1787 master = _default_root
1788 self.master = master
1789 self.tk = master.tk
1790 name = None
1791 if cnf.has_key('name'):
1792 name = cnf['name']
1793 del cnf['name']
1794 if not name:
1795 name = `id(self)`
1796 self._name = name
1797 if master._w=='.':
1798 self._w = '.' + name
1799 else:
1800 self._w = master._w + '.' + name
1801 self.children = {}
1802 if self.master.children.has_key(self._name):
1803 self.master.children[self._name].destroy()
1804 self.master.children[self._name] = self
1805 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1806 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1807 and appropriate options."""
1808 if kw:
1809 cnf = _cnfmerge((cnf, kw))
1810 self.widgetName = widgetName
1811 BaseWidget._setup(self, master, cnf)
1812 classes = []
1813 for k in cnf.keys():
1814 if type(k) is ClassType:
1815 classes.append((k, cnf[k]))
1816 del cnf[k]
1817 self.tk.call(
1818 (widgetName, self._w) + extra + self._options(cnf))
1819 for k, v in classes:
1820 k.configure(self, v)
1821 def destroy(self):
1822 """Destroy this and all descendants widgets."""
1823 for c in self.children.values(): c.destroy()
1824 if self.master.children.has_key(self._name):
1825 del self.master.children[self._name]
1826 self.tk.call('destroy', self._w)
1827 Misc.destroy(self)
1828 def _do(self, name, args=()):
1829 # XXX Obsolete -- better use self.tk.call directly!
1830 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001831
Guido van Rossum368e06b1997-11-07 20:38:49 +00001832class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001833 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001834
Fredrik Lundh06d28152000-08-09 18:03:12 +00001835 Base class for a widget which can be positioned with the geometry managers
1836 Pack, Place or Grid."""
1837 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001838
1839class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001840 """Toplevel widget, e.g. for dialogs."""
1841 def __init__(self, master=None, cnf={}, **kw):
1842 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001843
Fredrik Lundh06d28152000-08-09 18:03:12 +00001844 Valid resource names: background, bd, bg, borderwidth, class,
1845 colormap, container, cursor, height, highlightbackground,
1846 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1847 use, visual, width."""
1848 if kw:
1849 cnf = _cnfmerge((cnf, kw))
1850 extra = ()
1851 for wmkey in ['screen', 'class_', 'class', 'visual',
1852 'colormap']:
1853 if cnf.has_key(wmkey):
1854 val = cnf[wmkey]
1855 # TBD: a hack needed because some keys
1856 # are not valid as keyword arguments
1857 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1858 else: opt = '-'+wmkey
1859 extra = extra + (opt, val)
1860 del cnf[wmkey]
1861 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1862 root = self._root()
1863 self.iconname(root.iconname())
1864 self.title(root.title())
1865 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001866
1867class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001868 """Button widget."""
1869 def __init__(self, master=None, cnf={}, **kw):
1870 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001871
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001872 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001873
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001874 activebackground, activeforeground, anchor,
1875 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001876 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001877 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001878 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001879 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001880 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001881 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001882
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001883 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001884
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001885 command, compound, default, height,
1886 overrelief, state, width
1887 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001888 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001889
Fredrik Lundh06d28152000-08-09 18:03:12 +00001890 def tkButtonEnter(self, *dummy):
1891 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001892
Fredrik Lundh06d28152000-08-09 18:03:12 +00001893 def tkButtonLeave(self, *dummy):
1894 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001895
Fredrik Lundh06d28152000-08-09 18:03:12 +00001896 def tkButtonDown(self, *dummy):
1897 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001898
Fredrik Lundh06d28152000-08-09 18:03:12 +00001899 def tkButtonUp(self, *dummy):
1900 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001901
Fredrik Lundh06d28152000-08-09 18:03:12 +00001902 def tkButtonInvoke(self, *dummy):
1903 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001904
Fredrik Lundh06d28152000-08-09 18:03:12 +00001905 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001906 """Flash the button.
1907
1908 This is accomplished by redisplaying
1909 the button several times, alternating between active and
1910 normal colors. At the end of the flash the button is left
1911 in the same normal/active state as when the command was
1912 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001913 disabled.
1914 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001915 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00001916
Fredrik Lundh06d28152000-08-09 18:03:12 +00001917 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001918 """Invoke the command associated with the button.
1919
1920 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001921 or an empty string if there is no command associated with
1922 the button. This command is ignored if the button's state
1923 is disabled.
1924 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001925 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001926
1927# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001928# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001929def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001930 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001931def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001932 s = 'insert'
1933 for a in args:
1934 if a: s = s + (' ' + a)
1935 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001936def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001937 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001938def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001939 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001940def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001941 if y is None:
1942 return '@' + `x`
1943 else:
1944 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001945
1946class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001947 """Canvas widget to display graphical elements like lines or text."""
1948 def __init__(self, master=None, cnf={}, **kw):
1949 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001950
Fredrik Lundh06d28152000-08-09 18:03:12 +00001951 Valid resource names: background, bd, bg, borderwidth, closeenough,
1952 confine, cursor, height, highlightbackground, highlightcolor,
1953 highlightthickness, insertbackground, insertborderwidth,
1954 insertofftime, insertontime, insertwidth, offset, relief,
1955 scrollregion, selectbackground, selectborderwidth, selectforeground,
1956 state, takefocus, width, xscrollcommand, xscrollincrement,
1957 yscrollcommand, yscrollincrement."""
1958 Widget.__init__(self, master, 'canvas', cnf, kw)
1959 def addtag(self, *args):
1960 """Internal function."""
1961 self.tk.call((self._w, 'addtag') + args)
1962 def addtag_above(self, newtag, tagOrId):
1963 """Add tag NEWTAG to all items above TAGORID."""
1964 self.addtag(newtag, 'above', tagOrId)
1965 def addtag_all(self, newtag):
1966 """Add tag NEWTAG to all items."""
1967 self.addtag(newtag, 'all')
1968 def addtag_below(self, newtag, tagOrId):
1969 """Add tag NEWTAG to all items below TAGORID."""
1970 self.addtag(newtag, 'below', tagOrId)
1971 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1972 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1973 If several match take the top-most.
1974 All items closer than HALO are considered overlapping (all are
1975 closests). If START is specified the next below this tag is taken."""
1976 self.addtag(newtag, 'closest', x, y, halo, start)
1977 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1978 """Add tag NEWTAG to all items in the rectangle defined
1979 by X1,Y1,X2,Y2."""
1980 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1981 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1982 """Add tag NEWTAG to all items which overlap the rectangle
1983 defined by X1,Y1,X2,Y2."""
1984 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1985 def addtag_withtag(self, newtag, tagOrId):
1986 """Add tag NEWTAG to all items with TAGORID."""
1987 self.addtag(newtag, 'withtag', tagOrId)
1988 def bbox(self, *args):
1989 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1990 which encloses all items with tags specified as arguments."""
1991 return self._getints(
1992 self.tk.call((self._w, 'bbox') + args)) or None
1993 def tag_unbind(self, tagOrId, sequence, funcid=None):
1994 """Unbind for all items with TAGORID for event SEQUENCE the
1995 function identified with FUNCID."""
1996 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
1997 if funcid:
1998 self.deletecommand(funcid)
1999 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2000 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002001
Fredrik Lundh06d28152000-08-09 18:03:12 +00002002 An additional boolean parameter ADD specifies whether FUNC will be
2003 called additionally to the other bound function or whether it will
2004 replace the previous function. See bind for the return value."""
2005 return self._bind((self._w, 'bind', tagOrId),
2006 sequence, func, add)
2007 def canvasx(self, screenx, gridspacing=None):
2008 """Return the canvas x coordinate of pixel position SCREENX rounded
2009 to nearest multiple of GRIDSPACING units."""
2010 return getdouble(self.tk.call(
2011 self._w, 'canvasx', screenx, gridspacing))
2012 def canvasy(self, screeny, gridspacing=None):
2013 """Return the canvas y coordinate of pixel position SCREENY rounded
2014 to nearest multiple of GRIDSPACING units."""
2015 return getdouble(self.tk.call(
2016 self._w, 'canvasy', screeny, gridspacing))
2017 def coords(self, *args):
2018 """Return a list of coordinates for the item given in ARGS."""
2019 # XXX Should use _flatten on args
2020 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002021 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002022 self.tk.call((self._w, 'coords') + args)))
2023 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2024 """Internal function."""
2025 args = _flatten(args)
2026 cnf = args[-1]
2027 if type(cnf) in (DictionaryType, TupleType):
2028 args = args[:-1]
2029 else:
2030 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002031 return getint(self.tk.call(
2032 self._w, 'create', itemType,
2033 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002034 def create_arc(self, *args, **kw):
2035 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2036 return self._create('arc', args, kw)
2037 def create_bitmap(self, *args, **kw):
2038 """Create bitmap with coordinates x1,y1."""
2039 return self._create('bitmap', args, kw)
2040 def create_image(self, *args, **kw):
2041 """Create image item with coordinates x1,y1."""
2042 return self._create('image', args, kw)
2043 def create_line(self, *args, **kw):
2044 """Create line with coordinates x1,y1,...,xn,yn."""
2045 return self._create('line', args, kw)
2046 def create_oval(self, *args, **kw):
2047 """Create oval with coordinates x1,y1,x2,y2."""
2048 return self._create('oval', args, kw)
2049 def create_polygon(self, *args, **kw):
2050 """Create polygon with coordinates x1,y1,...,xn,yn."""
2051 return self._create('polygon', args, kw)
2052 def create_rectangle(self, *args, **kw):
2053 """Create rectangle with coordinates x1,y1,x2,y2."""
2054 return self._create('rectangle', args, kw)
2055 def create_text(self, *args, **kw):
2056 """Create text with coordinates x1,y1."""
2057 return self._create('text', args, kw)
2058 def create_window(self, *args, **kw):
2059 """Create window with coordinates x1,y1,x2,y2."""
2060 return self._create('window', args, kw)
2061 def dchars(self, *args):
2062 """Delete characters of text items identified by tag or id in ARGS (possibly
2063 several times) from FIRST to LAST character (including)."""
2064 self.tk.call((self._w, 'dchars') + args)
2065 def delete(self, *args):
2066 """Delete items identified by all tag or ids contained in ARGS."""
2067 self.tk.call((self._w, 'delete') + args)
2068 def dtag(self, *args):
2069 """Delete tag or id given as last arguments in ARGS from items
2070 identified by first argument in ARGS."""
2071 self.tk.call((self._w, 'dtag') + args)
2072 def find(self, *args):
2073 """Internal function."""
2074 return self._getints(
2075 self.tk.call((self._w, 'find') + args)) or ()
2076 def find_above(self, tagOrId):
2077 """Return items above TAGORID."""
2078 return self.find('above', tagOrId)
2079 def find_all(self):
2080 """Return all items."""
2081 return self.find('all')
2082 def find_below(self, tagOrId):
2083 """Return all items below TAGORID."""
2084 return self.find('below', tagOrId)
2085 def find_closest(self, x, y, halo=None, start=None):
2086 """Return item which is closest to pixel at X, Y.
2087 If several match take the top-most.
2088 All items closer than HALO are considered overlapping (all are
2089 closests). If START is specified the next below this tag is taken."""
2090 return self.find('closest', x, y, halo, start)
2091 def find_enclosed(self, x1, y1, x2, y2):
2092 """Return all items in rectangle defined
2093 by X1,Y1,X2,Y2."""
2094 return self.find('enclosed', x1, y1, x2, y2)
2095 def find_overlapping(self, x1, y1, x2, y2):
2096 """Return all items which overlap the rectangle
2097 defined by X1,Y1,X2,Y2."""
2098 return self.find('overlapping', x1, y1, x2, y2)
2099 def find_withtag(self, tagOrId):
2100 """Return all items with TAGORID."""
2101 return self.find('withtag', tagOrId)
2102 def focus(self, *args):
2103 """Set focus to the first item specified in ARGS."""
2104 return self.tk.call((self._w, 'focus') + args)
2105 def gettags(self, *args):
2106 """Return tags associated with the first item specified in ARGS."""
2107 return self.tk.splitlist(
2108 self.tk.call((self._w, 'gettags') + args))
2109 def icursor(self, *args):
2110 """Set cursor at position POS in the item identified by TAGORID.
2111 In ARGS TAGORID must be first."""
2112 self.tk.call((self._w, 'icursor') + args)
2113 def index(self, *args):
2114 """Return position of cursor as integer in item specified in ARGS."""
2115 return getint(self.tk.call((self._w, 'index') + args))
2116 def insert(self, *args):
2117 """Insert TEXT in item TAGORID at position POS. ARGS must
2118 be TAGORID POS TEXT."""
2119 self.tk.call((self._w, 'insert') + args)
2120 def itemcget(self, tagOrId, option):
2121 """Return the resource value for an OPTION for item TAGORID."""
2122 return self.tk.call(
2123 (self._w, 'itemcget') + (tagOrId, '-'+option))
2124 def itemconfigure(self, tagOrId, cnf=None, **kw):
2125 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002126
Fredrik Lundh06d28152000-08-09 18:03:12 +00002127 The values for resources are specified as keyword
2128 arguments. To get an overview about
2129 the allowed keyword arguments call the method without arguments.
2130 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002131 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002132 itemconfig = itemconfigure
2133 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2134 # so the preferred name for them is tag_lower, tag_raise
2135 # (similar to tag_bind, and similar to the Text widget);
2136 # unfortunately can't delete the old ones yet (maybe in 1.6)
2137 def tag_lower(self, *args):
2138 """Lower an item TAGORID given in ARGS
2139 (optional below another item)."""
2140 self.tk.call((self._w, 'lower') + args)
2141 lower = tag_lower
2142 def move(self, *args):
2143 """Move an item TAGORID given in ARGS."""
2144 self.tk.call((self._w, 'move') + args)
2145 def postscript(self, cnf={}, **kw):
2146 """Print the contents of the canvas to a postscript
2147 file. Valid options: colormap, colormode, file, fontmap,
2148 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2149 rotate, witdh, x, y."""
2150 return self.tk.call((self._w, 'postscript') +
2151 self._options(cnf, kw))
2152 def tag_raise(self, *args):
2153 """Raise an item TAGORID given in ARGS
2154 (optional above another item)."""
2155 self.tk.call((self._w, 'raise') + args)
2156 lift = tkraise = tag_raise
2157 def scale(self, *args):
2158 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2159 self.tk.call((self._w, 'scale') + args)
2160 def scan_mark(self, x, y):
2161 """Remember the current X, Y coordinates."""
2162 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002163 def scan_dragto(self, x, y, gain=10):
2164 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002165 difference between X and Y and the coordinates given in
2166 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002167 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002168 def select_adjust(self, tagOrId, index):
2169 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2170 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2171 def select_clear(self):
2172 """Clear the selection if it is in this widget."""
2173 self.tk.call(self._w, 'select', 'clear')
2174 def select_from(self, tagOrId, index):
2175 """Set the fixed end of a selection in item TAGORID to INDEX."""
2176 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2177 def select_item(self):
2178 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002179 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002180 def select_to(self, tagOrId, index):
2181 """Set the variable end of a selection in item TAGORID to INDEX."""
2182 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2183 def type(self, tagOrId):
2184 """Return the type of the item TAGORID."""
2185 return self.tk.call(self._w, 'type', tagOrId) or None
2186 def xview(self, *args):
2187 """Query and change horizontal position of the view."""
2188 if not args:
2189 return self._getdoubles(self.tk.call(self._w, 'xview'))
2190 self.tk.call((self._w, 'xview') + args)
2191 def xview_moveto(self, fraction):
2192 """Adjusts the view in the window so that FRACTION of the
2193 total width of the canvas is off-screen to the left."""
2194 self.tk.call(self._w, 'xview', 'moveto', fraction)
2195 def xview_scroll(self, number, what):
2196 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2197 self.tk.call(self._w, 'xview', 'scroll', number, what)
2198 def yview(self, *args):
2199 """Query and change vertical position of the view."""
2200 if not args:
2201 return self._getdoubles(self.tk.call(self._w, 'yview'))
2202 self.tk.call((self._w, 'yview') + args)
2203 def yview_moveto(self, fraction):
2204 """Adjusts the view in the window so that FRACTION of the
2205 total height of the canvas is off-screen to the top."""
2206 self.tk.call(self._w, 'yview', 'moveto', fraction)
2207 def yview_scroll(self, number, what):
2208 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2209 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002210
2211class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002212 """Checkbutton widget which is either in on- or off-state."""
2213 def __init__(self, master=None, cnf={}, **kw):
2214 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002215
Fredrik Lundh06d28152000-08-09 18:03:12 +00002216 Valid resource names: activebackground, activeforeground, anchor,
2217 background, bd, bg, bitmap, borderwidth, command, cursor,
2218 disabledforeground, fg, font, foreground, height,
2219 highlightbackground, highlightcolor, highlightthickness, image,
2220 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2221 selectcolor, selectimage, state, takefocus, text, textvariable,
2222 underline, variable, width, wraplength."""
2223 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2224 def deselect(self):
2225 """Put the button in off-state."""
2226 self.tk.call(self._w, 'deselect')
2227 def flash(self):
2228 """Flash the button."""
2229 self.tk.call(self._w, 'flash')
2230 def invoke(self):
2231 """Toggle the button and invoke a command if given as resource."""
2232 return self.tk.call(self._w, 'invoke')
2233 def select(self):
2234 """Put the button in on-state."""
2235 self.tk.call(self._w, 'select')
2236 def toggle(self):
2237 """Toggle the button."""
2238 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002239
2240class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002241 """Entry widget which allows to display simple text."""
2242 def __init__(self, master=None, cnf={}, **kw):
2243 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002244
Fredrik Lundh06d28152000-08-09 18:03:12 +00002245 Valid resource names: background, bd, bg, borderwidth, cursor,
2246 exportselection, fg, font, foreground, highlightbackground,
2247 highlightcolor, highlightthickness, insertbackground,
2248 insertborderwidth, insertofftime, insertontime, insertwidth,
2249 invalidcommand, invcmd, justify, relief, selectbackground,
2250 selectborderwidth, selectforeground, show, state, takefocus,
2251 textvariable, validate, validatecommand, vcmd, width,
2252 xscrollcommand."""
2253 Widget.__init__(self, master, 'entry', cnf, kw)
2254 def delete(self, first, last=None):
2255 """Delete text from FIRST to LAST (not included)."""
2256 self.tk.call(self._w, 'delete', first, last)
2257 def get(self):
2258 """Return the text."""
2259 return self.tk.call(self._w, 'get')
2260 def icursor(self, index):
2261 """Insert cursor at INDEX."""
2262 self.tk.call(self._w, 'icursor', index)
2263 def index(self, index):
2264 """Return position of cursor."""
2265 return getint(self.tk.call(
2266 self._w, 'index', index))
2267 def insert(self, index, string):
2268 """Insert STRING at INDEX."""
2269 self.tk.call(self._w, 'insert', index, string)
2270 def scan_mark(self, x):
2271 """Remember the current X, Y coordinates."""
2272 self.tk.call(self._w, 'scan', 'mark', x)
2273 def scan_dragto(self, x):
2274 """Adjust the view of the canvas to 10 times the
2275 difference between X and Y and the coordinates given in
2276 scan_mark."""
2277 self.tk.call(self._w, 'scan', 'dragto', x)
2278 def selection_adjust(self, index):
2279 """Adjust the end of the selection near the cursor to INDEX."""
2280 self.tk.call(self._w, 'selection', 'adjust', index)
2281 select_adjust = selection_adjust
2282 def selection_clear(self):
2283 """Clear the selection if it is in this widget."""
2284 self.tk.call(self._w, 'selection', 'clear')
2285 select_clear = selection_clear
2286 def selection_from(self, index):
2287 """Set the fixed end of a selection to INDEX."""
2288 self.tk.call(self._w, 'selection', 'from', index)
2289 select_from = selection_from
2290 def selection_present(self):
2291 """Return whether the widget has the selection."""
2292 return self.tk.getboolean(
2293 self.tk.call(self._w, 'selection', 'present'))
2294 select_present = selection_present
2295 def selection_range(self, start, end):
2296 """Set the selection from START to END (not included)."""
2297 self.tk.call(self._w, 'selection', 'range', start, end)
2298 select_range = selection_range
2299 def selection_to(self, index):
2300 """Set the variable end of a selection to INDEX."""
2301 self.tk.call(self._w, 'selection', 'to', index)
2302 select_to = selection_to
2303 def xview(self, index):
2304 """Query and change horizontal position of the view."""
2305 self.tk.call(self._w, 'xview', index)
2306 def xview_moveto(self, fraction):
2307 """Adjust the view in the window so that FRACTION of the
2308 total width of the entry is off-screen to the left."""
2309 self.tk.call(self._w, 'xview', 'moveto', fraction)
2310 def xview_scroll(self, number, what):
2311 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2312 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002313
2314class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002315 """Frame widget which may contain other widgets and can have a 3D border."""
2316 def __init__(self, master=None, cnf={}, **kw):
2317 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002318
Fredrik Lundh06d28152000-08-09 18:03:12 +00002319 Valid resource names: background, bd, bg, borderwidth, class,
2320 colormap, container, cursor, height, highlightbackground,
2321 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2322 cnf = _cnfmerge((cnf, kw))
2323 extra = ()
2324 if cnf.has_key('class_'):
2325 extra = ('-class', cnf['class_'])
2326 del cnf['class_']
2327 elif cnf.has_key('class'):
2328 extra = ('-class', cnf['class'])
2329 del cnf['class']
2330 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002331
2332class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002333 """Label widget which can display text and bitmaps."""
2334 def __init__(self, master=None, cnf={}, **kw):
2335 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002336
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002337 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002338
2339 activebackground, activeforeground, anchor,
2340 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002341 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002342 highlightbackground, highlightcolor,
2343 highlightthickness, image, justify,
2344 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002345 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002346
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002347 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002348
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002349 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002350
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002351 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002352 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002353
Guido van Rossum18468821994-06-20 07:49:28 +00002354class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002355 """Listbox widget which can display a list of strings."""
2356 def __init__(self, master=None, cnf={}, **kw):
2357 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002358
Fredrik Lundh06d28152000-08-09 18:03:12 +00002359 Valid resource names: background, bd, bg, borderwidth, cursor,
2360 exportselection, fg, font, foreground, height, highlightbackground,
2361 highlightcolor, highlightthickness, relief, selectbackground,
2362 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2363 width, xscrollcommand, yscrollcommand, listvariable."""
2364 Widget.__init__(self, master, 'listbox', cnf, kw)
2365 def activate(self, index):
2366 """Activate item identified by INDEX."""
2367 self.tk.call(self._w, 'activate', index)
2368 def bbox(self, *args):
2369 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2370 which encloses the item identified by index in ARGS."""
2371 return self._getints(
2372 self.tk.call((self._w, 'bbox') + args)) or None
2373 def curselection(self):
2374 """Return list of indices of currently selected item."""
2375 # XXX Ought to apply self._getints()...
2376 return self.tk.splitlist(self.tk.call(
2377 self._w, 'curselection'))
2378 def delete(self, first, last=None):
2379 """Delete items from FIRST to LAST (not included)."""
2380 self.tk.call(self._w, 'delete', first, last)
2381 def get(self, first, last=None):
2382 """Get list of items from FIRST to LAST (not included)."""
2383 if last:
2384 return self.tk.splitlist(self.tk.call(
2385 self._w, 'get', first, last))
2386 else:
2387 return self.tk.call(self._w, 'get', first)
2388 def index(self, index):
2389 """Return index of item identified with INDEX."""
2390 i = self.tk.call(self._w, 'index', index)
2391 if i == 'none': return None
2392 return getint(i)
2393 def insert(self, index, *elements):
2394 """Insert ELEMENTS at INDEX."""
2395 self.tk.call((self._w, 'insert', index) + elements)
2396 def nearest(self, y):
2397 """Get index of item which is nearest to y coordinate Y."""
2398 return getint(self.tk.call(
2399 self._w, 'nearest', y))
2400 def scan_mark(self, x, y):
2401 """Remember the current X, Y coordinates."""
2402 self.tk.call(self._w, 'scan', 'mark', x, y)
2403 def scan_dragto(self, x, y):
2404 """Adjust the view of the listbox to 10 times the
2405 difference between X and Y and the coordinates given in
2406 scan_mark."""
2407 self.tk.call(self._w, 'scan', 'dragto', x, y)
2408 def see(self, index):
2409 """Scroll such that INDEX is visible."""
2410 self.tk.call(self._w, 'see', index)
2411 def selection_anchor(self, index):
2412 """Set the fixed end oft the selection to INDEX."""
2413 self.tk.call(self._w, 'selection', 'anchor', index)
2414 select_anchor = selection_anchor
2415 def selection_clear(self, first, last=None):
2416 """Clear the selection from FIRST to LAST (not included)."""
2417 self.tk.call(self._w,
2418 'selection', 'clear', first, last)
2419 select_clear = selection_clear
2420 def selection_includes(self, index):
2421 """Return 1 if INDEX is part of the selection."""
2422 return self.tk.getboolean(self.tk.call(
2423 self._w, 'selection', 'includes', index))
2424 select_includes = selection_includes
2425 def selection_set(self, first, last=None):
2426 """Set the selection from FIRST to LAST (not included) without
2427 changing the currently selected elements."""
2428 self.tk.call(self._w, 'selection', 'set', first, last)
2429 select_set = selection_set
2430 def size(self):
2431 """Return the number of elements in the listbox."""
2432 return getint(self.tk.call(self._w, 'size'))
2433 def xview(self, *what):
2434 """Query and change horizontal position of the view."""
2435 if not what:
2436 return self._getdoubles(self.tk.call(self._w, 'xview'))
2437 self.tk.call((self._w, 'xview') + what)
2438 def xview_moveto(self, fraction):
2439 """Adjust the view in the window so that FRACTION of the
2440 total width of the entry is off-screen to the left."""
2441 self.tk.call(self._w, 'xview', 'moveto', fraction)
2442 def xview_scroll(self, number, what):
2443 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2444 self.tk.call(self._w, 'xview', 'scroll', number, what)
2445 def yview(self, *what):
2446 """Query and change vertical position of the view."""
2447 if not what:
2448 return self._getdoubles(self.tk.call(self._w, 'yview'))
2449 self.tk.call((self._w, 'yview') + what)
2450 def yview_moveto(self, fraction):
2451 """Adjust the view in the window so that FRACTION of the
2452 total width of the entry is off-screen to the top."""
2453 self.tk.call(self._w, 'yview', 'moveto', fraction)
2454 def yview_scroll(self, number, what):
2455 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2456 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002457 def itemcget(self, index, option):
2458 """Return the resource value for an ITEM and an OPTION."""
2459 return self.tk.call(
2460 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002461 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002462 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002463
2464 The values for resources are specified as keyword arguments.
2465 To get an overview about the allowed keyword arguments
2466 call the method without arguments.
2467 Valid resource names: background, bg, foreground, fg,
2468 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002469 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002470 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002471
2472class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002473 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2474 def __init__(self, master=None, cnf={}, **kw):
2475 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002476
Fredrik Lundh06d28152000-08-09 18:03:12 +00002477 Valid resource names: activebackground, activeborderwidth,
2478 activeforeground, background, bd, bg, borderwidth, cursor,
2479 disabledforeground, fg, font, foreground, postcommand, relief,
2480 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2481 Widget.__init__(self, master, 'menu', cnf, kw)
2482 def tk_bindForTraversal(self):
2483 pass # obsolete since Tk 4.0
2484 def tk_mbPost(self):
2485 self.tk.call('tk_mbPost', self._w)
2486 def tk_mbUnpost(self):
2487 self.tk.call('tk_mbUnpost')
2488 def tk_traverseToMenu(self, char):
2489 self.tk.call('tk_traverseToMenu', self._w, char)
2490 def tk_traverseWithinMenu(self, char):
2491 self.tk.call('tk_traverseWithinMenu', self._w, char)
2492 def tk_getMenuButtons(self):
2493 return self.tk.call('tk_getMenuButtons', self._w)
2494 def tk_nextMenu(self, count):
2495 self.tk.call('tk_nextMenu', count)
2496 def tk_nextMenuEntry(self, count):
2497 self.tk.call('tk_nextMenuEntry', count)
2498 def tk_invokeMenu(self):
2499 self.tk.call('tk_invokeMenu', self._w)
2500 def tk_firstMenu(self):
2501 self.tk.call('tk_firstMenu', self._w)
2502 def tk_mbButtonDown(self):
2503 self.tk.call('tk_mbButtonDown', self._w)
2504 def tk_popup(self, x, y, entry=""):
2505 """Post the menu at position X,Y with entry ENTRY."""
2506 self.tk.call('tk_popup', self._w, x, y, entry)
2507 def activate(self, index):
2508 """Activate entry at INDEX."""
2509 self.tk.call(self._w, 'activate', index)
2510 def add(self, itemType, cnf={}, **kw):
2511 """Internal function."""
2512 self.tk.call((self._w, 'add', itemType) +
2513 self._options(cnf, kw))
2514 def add_cascade(self, cnf={}, **kw):
2515 """Add hierarchical menu item."""
2516 self.add('cascade', cnf or kw)
2517 def add_checkbutton(self, cnf={}, **kw):
2518 """Add checkbutton menu item."""
2519 self.add('checkbutton', cnf or kw)
2520 def add_command(self, cnf={}, **kw):
2521 """Add command menu item."""
2522 self.add('command', cnf or kw)
2523 def add_radiobutton(self, cnf={}, **kw):
2524 """Addd radio menu item."""
2525 self.add('radiobutton', cnf or kw)
2526 def add_separator(self, cnf={}, **kw):
2527 """Add separator."""
2528 self.add('separator', cnf or kw)
2529 def insert(self, index, itemType, cnf={}, **kw):
2530 """Internal function."""
2531 self.tk.call((self._w, 'insert', index, itemType) +
2532 self._options(cnf, kw))
2533 def insert_cascade(self, index, cnf={}, **kw):
2534 """Add hierarchical menu item at INDEX."""
2535 self.insert(index, 'cascade', cnf or kw)
2536 def insert_checkbutton(self, index, cnf={}, **kw):
2537 """Add checkbutton menu item at INDEX."""
2538 self.insert(index, 'checkbutton', cnf or kw)
2539 def insert_command(self, index, cnf={}, **kw):
2540 """Add command menu item at INDEX."""
2541 self.insert(index, 'command', cnf or kw)
2542 def insert_radiobutton(self, index, cnf={}, **kw):
2543 """Addd radio menu item at INDEX."""
2544 self.insert(index, 'radiobutton', cnf or kw)
2545 def insert_separator(self, index, cnf={}, **kw):
2546 """Add separator at INDEX."""
2547 self.insert(index, 'separator', cnf or kw)
2548 def delete(self, index1, index2=None):
2549 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2550 self.tk.call(self._w, 'delete', index1, index2)
2551 def entrycget(self, index, option):
2552 """Return the resource value of an menu item for OPTION at INDEX."""
2553 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2554 def entryconfigure(self, index, cnf=None, **kw):
2555 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002556 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002557 entryconfig = entryconfigure
2558 def index(self, index):
2559 """Return the index of a menu item identified by INDEX."""
2560 i = self.tk.call(self._w, 'index', index)
2561 if i == 'none': return None
2562 return getint(i)
2563 def invoke(self, index):
2564 """Invoke a menu item identified by INDEX and execute
2565 the associated command."""
2566 return self.tk.call(self._w, 'invoke', index)
2567 def post(self, x, y):
2568 """Display a menu at position X,Y."""
2569 self.tk.call(self._w, 'post', x, y)
2570 def type(self, index):
2571 """Return the type of the menu item at INDEX."""
2572 return self.tk.call(self._w, 'type', index)
2573 def unpost(self):
2574 """Unmap a menu."""
2575 self.tk.call(self._w, 'unpost')
2576 def yposition(self, index):
2577 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2578 return getint(self.tk.call(
2579 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002580
2581class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002582 """Menubutton widget, obsolete since Tk8.0."""
2583 def __init__(self, master=None, cnf={}, **kw):
2584 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002585
2586class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002587 """Message widget to display multiline text. Obsolete since Label does it too."""
2588 def __init__(self, master=None, cnf={}, **kw):
2589 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002590
2591class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002592 """Radiobutton widget which shows only one of several buttons in on-state."""
2593 def __init__(self, master=None, cnf={}, **kw):
2594 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002595
Fredrik Lundh06d28152000-08-09 18:03:12 +00002596 Valid resource names: activebackground, activeforeground, anchor,
2597 background, bd, bg, bitmap, borderwidth, command, cursor,
2598 disabledforeground, fg, font, foreground, height,
2599 highlightbackground, highlightcolor, highlightthickness, image,
2600 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2601 state, takefocus, text, textvariable, underline, value, variable,
2602 width, wraplength."""
2603 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2604 def deselect(self):
2605 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002606
Fredrik Lundh06d28152000-08-09 18:03:12 +00002607 self.tk.call(self._w, 'deselect')
2608 def flash(self):
2609 """Flash the button."""
2610 self.tk.call(self._w, 'flash')
2611 def invoke(self):
2612 """Toggle the button and invoke a command if given as resource."""
2613 return self.tk.call(self._w, 'invoke')
2614 def select(self):
2615 """Put the button in on-state."""
2616 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002617
2618class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002619 """Scale widget which can display a numerical scale."""
2620 def __init__(self, master=None, cnf={}, **kw):
2621 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002622
Fredrik Lundh06d28152000-08-09 18:03:12 +00002623 Valid resource names: activebackground, background, bigincrement, bd,
2624 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2625 highlightbackground, highlightcolor, highlightthickness, label,
2626 length, orient, relief, repeatdelay, repeatinterval, resolution,
2627 showvalue, sliderlength, sliderrelief, state, takefocus,
2628 tickinterval, to, troughcolor, variable, width."""
2629 Widget.__init__(self, master, 'scale', cnf, kw)
2630 def get(self):
2631 """Get the current value as integer or float."""
2632 value = self.tk.call(self._w, 'get')
2633 try:
2634 return getint(value)
2635 except ValueError:
2636 return getdouble(value)
2637 def set(self, value):
2638 """Set the value to VALUE."""
2639 self.tk.call(self._w, 'set', value)
2640 def coords(self, value=None):
2641 """Return a tuple (X,Y) of the point along the centerline of the
2642 trough that corresponds to VALUE or the current value if None is
2643 given."""
2644
2645 return self._getints(self.tk.call(self._w, 'coords', value))
2646 def identify(self, x, y):
2647 """Return where the point X,Y lies. Valid return values are "slider",
2648 "though1" and "though2"."""
2649 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002650
2651class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002652 """Scrollbar widget which displays a slider at a certain position."""
2653 def __init__(self, master=None, cnf={}, **kw):
2654 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002655
Fredrik Lundh06d28152000-08-09 18:03:12 +00002656 Valid resource names: activebackground, activerelief,
2657 background, bd, bg, borderwidth, command, cursor,
2658 elementborderwidth, highlightbackground,
2659 highlightcolor, highlightthickness, jump, orient,
2660 relief, repeatdelay, repeatinterval, takefocus,
2661 troughcolor, width."""
2662 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2663 def activate(self, index):
2664 """Display the element at INDEX with activebackground and activerelief.
2665 INDEX can be "arrow1","slider" or "arrow2"."""
2666 self.tk.call(self._w, 'activate', index)
2667 def delta(self, deltax, deltay):
2668 """Return the fractional change of the scrollbar setting if it
2669 would be moved by DELTAX or DELTAY pixels."""
2670 return getdouble(
2671 self.tk.call(self._w, 'delta', deltax, deltay))
2672 def fraction(self, x, y):
2673 """Return the fractional value which corresponds to a slider
2674 position of X,Y."""
2675 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2676 def identify(self, x, y):
2677 """Return the element under position X,Y as one of
2678 "arrow1","slider","arrow2" or ""."""
2679 return self.tk.call(self._w, 'identify', x, y)
2680 def get(self):
2681 """Return the current fractional values (upper and lower end)
2682 of the slider position."""
2683 return self._getdoubles(self.tk.call(self._w, 'get'))
2684 def set(self, *args):
2685 """Set the fractional values of the slider position (upper and
2686 lower ends as value between 0 and 1)."""
2687 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002688
2689
2690
Guido van Rossum18468821994-06-20 07:49:28 +00002691class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002692 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002693 def __init__(self, master=None, cnf={}, **kw):
2694 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002695
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002696 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002697
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002698 background, borderwidth, cursor,
2699 exportselection, font, foreground,
2700 highlightbackground, highlightcolor,
2701 highlightthickness, insertbackground,
2702 insertborderwidth, insertofftime,
2703 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002704 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002705 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002706 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002707 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002708
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002709 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002710
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002711 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002712 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002713 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002714
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002715 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002716 Widget.__init__(self, master, 'text', cnf, kw)
2717 def bbox(self, *args):
2718 """Return a tuple of (x,y,width,height) which gives the bounding
2719 box of the visible part of the character at the index in ARGS."""
2720 return self._getints(
2721 self.tk.call((self._w, 'bbox') + args)) or None
2722 def tk_textSelectTo(self, index):
2723 self.tk.call('tk_textSelectTo', self._w, index)
2724 def tk_textBackspace(self):
2725 self.tk.call('tk_textBackspace', self._w)
2726 def tk_textIndexCloser(self, a, b, c):
2727 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2728 def tk_textResetAnchor(self, index):
2729 self.tk.call('tk_textResetAnchor', self._w, index)
2730 def compare(self, index1, op, index2):
2731 """Return whether between index INDEX1 and index INDEX2 the
2732 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2733 return self.tk.getboolean(self.tk.call(
2734 self._w, 'compare', index1, op, index2))
2735 def debug(self, boolean=None):
2736 """Turn on the internal consistency checks of the B-Tree inside the text
2737 widget according to BOOLEAN."""
2738 return self.tk.getboolean(self.tk.call(
2739 self._w, 'debug', boolean))
2740 def delete(self, index1, index2=None):
2741 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2742 self.tk.call(self._w, 'delete', index1, index2)
2743 def dlineinfo(self, index):
2744 """Return tuple (x,y,width,height,baseline) giving the bounding box
2745 and baseline position of the visible part of the line containing
2746 the character at INDEX."""
2747 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002748 def dump(self, index1, index2=None, command=None, **kw):
2749 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002750
Guido van Rossum256705b2002-04-23 13:29:43 +00002751 The type of contents returned in filtered based on the keyword
2752 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2753 given and true, then the corresponding items are returned. The result
2754 is a list of triples of the form (key, value, index). If none of the
2755 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002756
Guido van Rossum256705b2002-04-23 13:29:43 +00002757 If the 'command' argument is given, it is called once for each element
2758 of the list of triples, with the values of each triple serving as the
2759 arguments to the function. In this case the list is not returned."""
2760 args = []
2761 func_name = None
2762 result = None
2763 if not command:
2764 # Never call the dump command without the -command flag, since the
2765 # output could involve Tcl quoting and would be a pain to parse
2766 # right. Instead just set the command to build a list of triples
2767 # as if we had done the parsing.
2768 result = []
2769 def append_triple(key, value, index, result=result):
2770 result.append((key, value, index))
2771 command = append_triple
2772 try:
2773 if not isinstance(command, str):
2774 func_name = command = self._register(command)
2775 args += ["-command", command]
2776 for key in kw:
2777 if kw[key]: args.append("-" + key)
2778 args.append(index1)
2779 if index2:
2780 args.append(index2)
2781 self.tk.call(self._w, "dump", *args)
2782 return result
2783 finally:
2784 if func_name:
2785 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002786
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002787 ## new in tk8.4
2788 def edit(self, *args):
2789 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002790
2791 This method controls the undo mechanism and
2792 the modified flag. The exact behavior of the
2793 command depends on the option argument that
2794 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002795 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002796
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002797 edit_modified, edit_redo, edit_reset, edit_separator
2798 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002799
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002800 """
2801 return self._getints(
2802 self.tk.call((self._w, 'edit') + args)) or ()
2803
2804 def edit_modified(self, arg=None):
2805 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002806
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002807 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002808 flag of the widget. The insert, delete, edit undo and
2809 edit redo commands or the user can set or clear the
2810 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002811 modified flag of the widget to arg.
2812 """
2813 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002814
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002815 def edit_redo(self):
2816 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002817
2818 When the undo option is true, reapplies the last
2819 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002820 then. Generates an error when the redo stack is empty.
2821 Does nothing when the undo option is false.
2822 """
2823 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002824
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002825 def edit_reset(self):
2826 """Clears the undo and redo stacks
2827 """
2828 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002829
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002830 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002831 """Inserts a separator (boundary) on the undo stack.
2832
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002833 Does nothing when the undo option is false
2834 """
2835 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002836
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002837 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002838 """Undoes the last edit action
2839
2840 If the undo option is true. An edit action is defined
2841 as all the insert and delete commands that are recorded
2842 on the undo stack in between two separators. Generates
2843 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002844 when the undo option is false
2845 """
2846 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002847
Fredrik Lundh06d28152000-08-09 18:03:12 +00002848 def get(self, index1, index2=None):
2849 """Return the text from INDEX1 to INDEX2 (not included)."""
2850 return self.tk.call(self._w, 'get', index1, index2)
2851 # (Image commands are new in 8.0)
2852 def image_cget(self, index, option):
2853 """Return the value of OPTION of an embedded image at INDEX."""
2854 if option[:1] != "-":
2855 option = "-" + option
2856 if option[-1:] == "_":
2857 option = option[:-1]
2858 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002859 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002860 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002861 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002862 def image_create(self, index, cnf={}, **kw):
2863 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002864 return self.tk.call(
2865 self._w, "image", "create", index,
2866 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002867 def image_names(self):
2868 """Return all names of embedded images in this widget."""
2869 return self.tk.call(self._w, "image", "names")
2870 def index(self, index):
2871 """Return the index in the form line.char for INDEX."""
2872 return self.tk.call(self._w, 'index', index)
2873 def insert(self, index, chars, *args):
2874 """Insert CHARS before the characters at INDEX. An additional
2875 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2876 self.tk.call((self._w, 'insert', index, chars) + args)
2877 def mark_gravity(self, markName, direction=None):
2878 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2879 Return the current value if None is given for DIRECTION."""
2880 return self.tk.call(
2881 (self._w, 'mark', 'gravity', markName, direction))
2882 def mark_names(self):
2883 """Return all mark names."""
2884 return self.tk.splitlist(self.tk.call(
2885 self._w, 'mark', 'names'))
2886 def mark_set(self, markName, index):
2887 """Set mark MARKNAME before the character at INDEX."""
2888 self.tk.call(self._w, 'mark', 'set', markName, index)
2889 def mark_unset(self, *markNames):
2890 """Delete all marks in MARKNAMES."""
2891 self.tk.call((self._w, 'mark', 'unset') + markNames)
2892 def mark_next(self, index):
2893 """Return the name of the next mark after INDEX."""
2894 return self.tk.call(self._w, 'mark', 'next', index) or None
2895 def mark_previous(self, index):
2896 """Return the name of the previous mark before INDEX."""
2897 return self.tk.call(self._w, 'mark', 'previous', index) or None
2898 def scan_mark(self, x, y):
2899 """Remember the current X, Y coordinates."""
2900 self.tk.call(self._w, 'scan', 'mark', x, y)
2901 def scan_dragto(self, x, y):
2902 """Adjust the view of the text to 10 times the
2903 difference between X and Y and the coordinates given in
2904 scan_mark."""
2905 self.tk.call(self._w, 'scan', 'dragto', x, y)
2906 def search(self, pattern, index, stopindex=None,
2907 forwards=None, backwards=None, exact=None,
2908 regexp=None, nocase=None, count=None):
2909 """Search PATTERN beginning from INDEX until STOPINDEX.
2910 Return the index of the first character of a match or an empty string."""
2911 args = [self._w, 'search']
2912 if forwards: args.append('-forwards')
2913 if backwards: args.append('-backwards')
2914 if exact: args.append('-exact')
2915 if regexp: args.append('-regexp')
2916 if nocase: args.append('-nocase')
2917 if count: args.append('-count'); args.append(count)
2918 if pattern[0] == '-': args.append('--')
2919 args.append(pattern)
2920 args.append(index)
2921 if stopindex: args.append(stopindex)
2922 return self.tk.call(tuple(args))
2923 def see(self, index):
2924 """Scroll such that the character at INDEX is visible."""
2925 self.tk.call(self._w, 'see', index)
2926 def tag_add(self, tagName, index1, *args):
2927 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2928 Additional pairs of indices may follow in ARGS."""
2929 self.tk.call(
2930 (self._w, 'tag', 'add', tagName, index1) + args)
2931 def tag_unbind(self, tagName, sequence, funcid=None):
2932 """Unbind for all characters with TAGNAME for event SEQUENCE the
2933 function identified with FUNCID."""
2934 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2935 if funcid:
2936 self.deletecommand(funcid)
2937 def tag_bind(self, tagName, sequence, func, add=None):
2938 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002939
Fredrik Lundh06d28152000-08-09 18:03:12 +00002940 An additional boolean parameter ADD specifies whether FUNC will be
2941 called additionally to the other bound function or whether it will
2942 replace the previous function. See bind for the return value."""
2943 return self._bind((self._w, 'tag', 'bind', tagName),
2944 sequence, func, add)
2945 def tag_cget(self, tagName, option):
2946 """Return the value of OPTION for tag TAGNAME."""
2947 if option[:1] != '-':
2948 option = '-' + option
2949 if option[-1:] == '_':
2950 option = option[:-1]
2951 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002952 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002953 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002954 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002955 tag_config = tag_configure
2956 def tag_delete(self, *tagNames):
2957 """Delete all tags in TAGNAMES."""
2958 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2959 def tag_lower(self, tagName, belowThis=None):
2960 """Change the priority of tag TAGNAME such that it is lower
2961 than the priority of BELOWTHIS."""
2962 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2963 def tag_names(self, index=None):
2964 """Return a list of all tag names."""
2965 return self.tk.splitlist(
2966 self.tk.call(self._w, 'tag', 'names', index))
2967 def tag_nextrange(self, tagName, index1, index2=None):
2968 """Return a list of start and end index for the first sequence of
2969 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2970 The text is searched forward from INDEX1."""
2971 return self.tk.splitlist(self.tk.call(
2972 self._w, 'tag', 'nextrange', tagName, index1, index2))
2973 def tag_prevrange(self, tagName, index1, index2=None):
2974 """Return a list of start and end index for the first sequence of
2975 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2976 The text is searched backwards from INDEX1."""
2977 return self.tk.splitlist(self.tk.call(
2978 self._w, 'tag', 'prevrange', tagName, index1, index2))
2979 def tag_raise(self, tagName, aboveThis=None):
2980 """Change the priority of tag TAGNAME such that it is higher
2981 than the priority of ABOVETHIS."""
2982 self.tk.call(
2983 self._w, 'tag', 'raise', tagName, aboveThis)
2984 def tag_ranges(self, tagName):
2985 """Return a list of ranges of text which have tag TAGNAME."""
2986 return self.tk.splitlist(self.tk.call(
2987 self._w, 'tag', 'ranges', tagName))
2988 def tag_remove(self, tagName, index1, index2=None):
2989 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2990 self.tk.call(
2991 self._w, 'tag', 'remove', tagName, index1, index2)
2992 def window_cget(self, index, option):
2993 """Return the value of OPTION of an embedded window at INDEX."""
2994 if option[:1] != '-':
2995 option = '-' + option
2996 if option[-1:] == '_':
2997 option = option[:-1]
2998 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002999 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003000 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003001 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003002 window_config = window_configure
3003 def window_create(self, index, cnf={}, **kw):
3004 """Create a window at INDEX."""
3005 self.tk.call(
3006 (self._w, 'window', 'create', index)
3007 + self._options(cnf, kw))
3008 def window_names(self):
3009 """Return all names of embedded windows in this widget."""
3010 return self.tk.splitlist(
3011 self.tk.call(self._w, 'window', 'names'))
3012 def xview(self, *what):
3013 """Query and change horizontal position of the view."""
3014 if not what:
3015 return self._getdoubles(self.tk.call(self._w, 'xview'))
3016 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003017 def xview_moveto(self, fraction):
3018 """Adjusts the view in the window so that FRACTION of the
3019 total width of the canvas is off-screen to the left."""
3020 self.tk.call(self._w, 'xview', 'moveto', fraction)
3021 def xview_scroll(self, number, what):
3022 """Shift the x-view according to NUMBER which is measured
3023 in "units" or "pages" (WHAT)."""
3024 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003025 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003026 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003027 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003028 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003029 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003030 def yview_moveto(self, fraction):
3031 """Adjusts the view in the window so that FRACTION of the
3032 total height of the canvas is off-screen to the top."""
3033 self.tk.call(self._w, 'yview', 'moveto', fraction)
3034 def yview_scroll(self, number, what):
3035 """Shift the y-view according to NUMBER which is measured
3036 in "units" or "pages" (WHAT)."""
3037 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003038 def yview_pickplace(self, *what):
3039 """Obsolete function, use see."""
3040 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003041
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003042
Guido van Rossum28574b51996-10-21 15:16:51 +00003043class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003044 """Internal class. It wraps the command in the widget OptionMenu."""
3045 def __init__(self, var, value, callback=None):
3046 self.__value = value
3047 self.__var = var
3048 self.__callback = callback
3049 def __call__(self, *args):
3050 self.__var.set(self.__value)
3051 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003052 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003053
3054class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003055 """OptionMenu which allows the user to select a value from a menu."""
3056 def __init__(self, master, variable, value, *values, **kwargs):
3057 """Construct an optionmenu widget with the parent MASTER, with
3058 the resource textvariable set to VARIABLE, the initially selected
3059 value VALUE, the other menu values VALUES and an additional
3060 keyword argument command."""
3061 kw = {"borderwidth": 2, "textvariable": variable,
3062 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3063 "highlightthickness": 2}
3064 Widget.__init__(self, master, "menubutton", kw)
3065 self.widgetName = 'tk_optionMenu'
3066 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3067 self.menuname = menu._w
3068 # 'command' is the only supported keyword
3069 callback = kwargs.get('command')
3070 if kwargs.has_key('command'):
3071 del kwargs['command']
3072 if kwargs:
3073 raise TclError, 'unknown option -'+kwargs.keys()[0]
3074 menu.add_command(label=value,
3075 command=_setit(variable, value, callback))
3076 for v in values:
3077 menu.add_command(label=v,
3078 command=_setit(variable, v, callback))
3079 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003080
Fredrik Lundh06d28152000-08-09 18:03:12 +00003081 def __getitem__(self, name):
3082 if name == 'menu':
3083 return self.__menu
3084 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003085
Fredrik Lundh06d28152000-08-09 18:03:12 +00003086 def destroy(self):
3087 """Destroy this widget and the associated menu."""
3088 Menubutton.destroy(self)
3089 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003090
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003091class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003092 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003093 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003094 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3095 self.name = None
3096 if not master:
3097 master = _default_root
3098 if not master:
3099 raise RuntimeError, 'Too early to create image'
3100 self.tk = master.tk
3101 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003102 Image._last_id += 1
3103 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003104 # The following is needed for systems where id(x)
3105 # can return a negative number, such as Linux/m68k:
3106 if name[0] == '-': name = '_' + name[1:]
3107 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3108 elif kw: cnf = kw
3109 options = ()
3110 for k, v in cnf.items():
3111 if callable(v):
3112 v = self._register(v)
3113 options = options + ('-'+k, v)
3114 self.tk.call(('image', 'create', imgtype, name,) + options)
3115 self.name = name
3116 def __str__(self): return self.name
3117 def __del__(self):
3118 if self.name:
3119 try:
3120 self.tk.call('image', 'delete', self.name)
3121 except TclError:
3122 # May happen if the root was destroyed
3123 pass
3124 def __setitem__(self, key, value):
3125 self.tk.call(self.name, 'configure', '-'+key, value)
3126 def __getitem__(self, key):
3127 return self.tk.call(self.name, 'configure', '-'+key)
3128 def configure(self, **kw):
3129 """Configure the image."""
3130 res = ()
3131 for k, v in _cnfmerge(kw).items():
3132 if v is not None:
3133 if k[-1] == '_': k = k[:-1]
3134 if callable(v):
3135 v = self._register(v)
3136 res = res + ('-'+k, v)
3137 self.tk.call((self.name, 'config') + res)
3138 config = configure
3139 def height(self):
3140 """Return the height of the image."""
3141 return getint(
3142 self.tk.call('image', 'height', self.name))
3143 def type(self):
3144 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3145 return self.tk.call('image', 'type', self.name)
3146 def width(self):
3147 """Return the width of the image."""
3148 return getint(
3149 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003150
3151class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003152 """Widget which can display colored images in GIF, PPM/PGM format."""
3153 def __init__(self, name=None, cnf={}, master=None, **kw):
3154 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003155
Fredrik Lundh06d28152000-08-09 18:03:12 +00003156 Valid resource names: data, format, file, gamma, height, palette,
3157 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003158 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003159 def blank(self):
3160 """Display a transparent image."""
3161 self.tk.call(self.name, 'blank')
3162 def cget(self, option):
3163 """Return the value of OPTION."""
3164 return self.tk.call(self.name, 'cget', '-' + option)
3165 # XXX config
3166 def __getitem__(self, key):
3167 return self.tk.call(self.name, 'cget', '-' + key)
3168 # XXX copy -from, -to, ...?
3169 def copy(self):
3170 """Return a new PhotoImage with the same image as this widget."""
3171 destImage = PhotoImage()
3172 self.tk.call(destImage, 'copy', self.name)
3173 return destImage
3174 def zoom(self,x,y=''):
3175 """Return a new PhotoImage with the same image as this widget
3176 but zoom it with X and Y."""
3177 destImage = PhotoImage()
3178 if y=='': y=x
3179 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3180 return destImage
3181 def subsample(self,x,y=''):
3182 """Return a new PhotoImage based on the same image as this widget
3183 but use only every Xth or Yth pixel."""
3184 destImage = PhotoImage()
3185 if y=='': y=x
3186 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3187 return destImage
3188 def get(self, x, y):
3189 """Return the color (red, green, blue) of the pixel at X,Y."""
3190 return self.tk.call(self.name, 'get', x, y)
3191 def put(self, data, to=None):
3192 """Put row formated colors to image starting from
3193 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3194 args = (self.name, 'put', data)
3195 if to:
3196 if to[0] == '-to':
3197 to = to[1:]
3198 args = args + ('-to',) + tuple(to)
3199 self.tk.call(args)
3200 # XXX read
3201 def write(self, filename, format=None, from_coords=None):
3202 """Write image to file FILENAME in FORMAT starting from
3203 position FROM_COORDS."""
3204 args = (self.name, 'write', filename)
3205 if format:
3206 args = args + ('-format', format)
3207 if from_coords:
3208 args = args + ('-from',) + tuple(from_coords)
3209 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003210
3211class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003212 """Widget which can display a bitmap."""
3213 def __init__(self, name=None, cnf={}, master=None, **kw):
3214 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003215
Fredrik Lundh06d28152000-08-09 18:03:12 +00003216 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003217 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003218
3219def image_names(): return _default_root.tk.call('image', 'names')
3220def image_types(): return _default_root.tk.call('image', 'types')
3221
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003222
3223class Spinbox(Widget):
3224 """spinbox widget."""
3225 def __init__(self, master=None, cnf={}, **kw):
3226 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003227
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003228 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003229
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003230 activebackground, background, borderwidth,
3231 cursor, exportselection, font, foreground,
3232 highlightbackground, highlightcolor,
3233 highlightthickness, insertbackground,
3234 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003235 insertontime, insertwidth, justify, relief,
3236 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003237 selectbackground, selectborderwidth
3238 selectforeground, takefocus, textvariable
3239 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003240
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003241 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003242
3243 buttonbackground, buttoncursor,
3244 buttondownrelief, buttonuprelief,
3245 command, disabledbackground,
3246 disabledforeground, format, from,
3247 invalidcommand, increment,
3248 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003249 validate, validatecommand values,
3250 width, wrap,
3251 """
3252 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003253
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003254 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003255 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3256 rectangle which encloses the character given by index.
3257
3258 The first two elements of the list give the x and y
3259 coordinates of the upper-left corner of the screen
3260 area covered by the character (in pixels relative
3261 to the widget) and the last two elements give the
3262 width and height of the character, in pixels. The
3263 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003264 visible area of the window.
3265 """
3266 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003267
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003268 def delete(self, first, last=None):
3269 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003270
3271 First is the index of the first character to delete,
3272 and last is the index of the character just after
3273 the last one to delete. If last isn't specified it
3274 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003275 deleted. This command returns an empty string.
3276 """
3277 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003278
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003279 def get(self):
3280 """Returns the spinbox's string"""
3281 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003282
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003283 def icursor(self, index):
3284 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003285
3286 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003287 the character given by index. Returns an empty string
3288 """
3289 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003290
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003291 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003292 """Returns the name of the widget at position x, y
3293
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003294 Return value is one of: none, buttondown, buttonup, entry
3295 """
3296 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003297
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003298 def index(self, index):
3299 """Returns the numerical index corresponding to index
3300 """
3301 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003302
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003303 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003304 """Insert string s at index
3305
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003306 Returns an empty string.
3307 """
3308 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003309
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003310 def invoke(self, element):
3311 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003312
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003313 The element could be buttondown or buttonup
3314 triggering the action associated with it.
3315 """
3316 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003317
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003318 def scan(self, *args):
3319 """Internal function."""
3320 return self._getints(
3321 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003322
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003323 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003324 """Records x and the current view in the spinbox window;
3325
3326 used in conjunction with later scan dragto commands.
3327 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003328 press in the widget. It returns an empty string.
3329 """
3330 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003331
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003332 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003333 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003334 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003335
3336 It then adjusts the view left or right by 10 times the
3337 difference in x-coordinates. This command is typically
3338 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003339 produce the effect of dragging the spinbox at high speed
3340 through the window. The return value is an empty string.
3341 """
3342 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003343
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003344 def selection(self, *args):
3345 """Internal function."""
3346 return self._getints(
3347 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003348
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003349 def selection_adjust(self, index):
3350 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003351 given by index,
3352
3353 Then adjust that end of the selection to be at index
3354 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003355 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003356 select to commands. If the selection isn't currently in
3357 the spinbox, then a new selection is created to include
3358 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003359 anchor point, inclusive. Returns an empty string.
3360 """
3361 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003362
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003363 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003364 """Clear the selection
3365
3366 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003367 command has no effect. Returns an empty string.
3368 """
3369 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003370
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003371 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003372 """Sets or gets the currently selected element.
3373
3374 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003375 displayed depressed
3376 """
3377 return self.selection("element", element)
3378
3379###########################################################################
3380
3381class LabelFrame(Widget):
3382 """labelframe widget."""
3383 def __init__(self, master=None, cnf={}, **kw):
3384 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003385
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003386 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003387
3388 borderwidth, cursor, font, foreground,
3389 highlightbackground, highlightcolor,
3390 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003391 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003392
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003393 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003394
3395 background, class, colormap, container,
3396 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003397 visual, width
3398 """
3399 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003400
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003401########################################################################
3402
3403class PanedWindow(Widget):
3404 """panedwindow widget."""
3405 def __init__(self, master=None, cnf={}, **kw):
3406 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003407
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003408 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003409
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003410 background, borderwidth, cursor, height,
3411 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003412
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003413 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003414
3415 handlepad, handlesize, opaqueresize,
3416 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003417 sashwidth, showhandle,
3418 """
3419 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3420
3421 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003422 """Add a child widget to the panedwindow in a new pane.
3423
3424 The child argument is the name of the child widget
3425 followed by pairs of arguments that specify how to
3426 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003427 accepted by the configure subcommand.
3428 """
3429 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003430
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003431 def remove(self, child):
3432 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003433
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003434 All geometry management options for child will be forgotten.
3435 """
3436 self.tk.call(self._w, 'forget', child)
3437 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003438
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003439 def identify(self, x, y):
3440 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003441
3442 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003443 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003444 handle, and a word indicating whether it is over a sash
3445 or a handle, such as {0 sash} or {2 handle}. If the point
3446 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003447 an empty list.
3448 """
3449 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003450
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003451 def proxy(self, *args):
3452 """Internal function."""
3453 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003454 self.tk.call((self._w, 'proxy') + args)) or ()
3455
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003456 def proxy_coord(self):
3457 """Return the x and y pair of the most recent proxy location
3458 """
3459 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003460
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003461 def proxy_forget(self):
3462 """Remove the proxy from the display.
3463 """
3464 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003465
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003466 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003467 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003468 """
3469 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003470
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003471 def sash(self, *args):
3472 """Internal function."""
3473 return self._getints(
3474 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003475
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003476 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003477 """Return the current x and y pair for the sash given by index.
3478
3479 Index must be an integer between 0 and 1 less than the
3480 number of panes in the panedwindow. The coordinates given are
3481 those of the top left corner of the region containing the sash.
3482 pathName sash dragto index x y This command computes the
3483 difference between the given coordinates and the coordinates
3484 given to the last sash coord command for the given sash. It then
3485 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003486 empty string.
3487 """
3488 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003489
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003490 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003491 """Records x and y for the sash given by index;
3492
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003493 Used in conjunction with later dragto commands to move the sash.
3494 """
3495 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003496
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003497 def sash_place(self, index, x, y):
3498 """Place the sash given by index at the given coordinates
3499 """
3500 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003501
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003502 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003503 """Query a management option for window.
3504
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003505 Option may be any value allowed by the paneconfigure subcommand
3506 """
3507 return self.tk.call(
3508 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003509
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003510 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003511 """Query or modify the management options for window.
3512
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003513 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003514 of the available options for pathName. If option is
3515 specified with no value, then the command returns a list
3516 describing the one named option (this list will be identical
3517 to the corresponding sublist of the value returned if no
3518 option is specified). If one or more option-value pairs are
3519 specified, then the command modifies the given widget
3520 option(s) to have the given value(s); in this case the
3521 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003522 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003523
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003524 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003525 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003526 should be the name of a window already managed by pathName.
3527 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003528 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003529 should be the name of a window already managed by pathName.
3530 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003531 Specify a height for the window. The height will be the
3532 outer dimension of the window including its border, if
3533 any. If size is an empty string, or if -height is not
3534 specified, then the height requested internally by the
3535 window will be used initially; the height may later be
3536 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003537 Size may be any value accepted by Tk_GetPixels.
3538 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003539 Specifies that the size of the window cannot be made
3540 less than n. This constraint only affects the size of
3541 the widget in the paned dimension -- the x dimension
3542 for horizontal panedwindows, the y dimension for
3543 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003544 Tk_GetPixels.
3545 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003546 Specifies a non-negative value indicating how much
3547 extra space to leave on each side of the window in
3548 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003549 accepted by Tk_GetPixels.
3550 pady n
3551 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003552 extra space to leave on each side of the window in
3553 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003554 accepted by Tk_GetPixels.
3555 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003556 If a window's pane is larger than the requested
3557 dimensions of the window, this option may be used
3558 to position (or stretch) the window within its pane.
3559 Style is a string that contains zero or more of the
3560 characters n, s, e or w. The string can optionally
3561 contains spaces or commas, but they are ignored. Each
3562 letter refers to a side (north, south, east, or west)
3563 that the window will "stick" to. If both n and s
3564 (or e and w) are specified, the window will be
3565 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003566 its cavity.
3567 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003568 Specify a width for the window. The width will be
3569 the outer dimension of the window including its
3570 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003571 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003572 internally by the window will be used initially; the
3573 width may later be adjusted by the movement of sashes
3574 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003575 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003576
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003577 """
3578 if cnf is None and not kw:
3579 cnf = {}
3580 for x in self.tk.split(
3581 self.tk.call(self._w,
3582 'paneconfigure', tagOrId)):
3583 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3584 return cnf
3585 if type(cnf) == StringType and not kw:
3586 x = self.tk.split(self.tk.call(
3587 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3588 return (x[0][1:],) + x[1:]
3589 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3590 self._options(cnf, kw))
3591 paneconfig = paneconfigure
3592
3593 def panes(self):
3594 """Returns an ordered list of the child panes."""
3595 return self.tk.call(self._w, 'panes')
3596
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003597######################################################################
3598# Extensions:
3599
3600class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003601 def __init__(self, master=None, cnf={}, **kw):
3602 Widget.__init__(self, master, 'studbutton', cnf, kw)
3603 self.bind('<Any-Enter>', self.tkButtonEnter)
3604 self.bind('<Any-Leave>', self.tkButtonLeave)
3605 self.bind('<1>', self.tkButtonDown)
3606 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003607
3608class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003609 def __init__(self, master=None, cnf={}, **kw):
3610 Widget.__init__(self, master, 'tributton', cnf, kw)
3611 self.bind('<Any-Enter>', self.tkButtonEnter)
3612 self.bind('<Any-Leave>', self.tkButtonLeave)
3613 self.bind('<1>', self.tkButtonDown)
3614 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3615 self['fg'] = self['bg']
3616 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003617
Guido van Rossumc417ef81996-08-21 23:38:59 +00003618######################################################################
3619# Test:
3620
3621def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003622 root = Tk()
3623 text = "This is Tcl/Tk version %s" % TclVersion
3624 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003625 try:
3626 text = text + unicode("\nThis should be a cedilla: \347",
3627 "iso-8859-1")
3628 except NameError:
3629 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003630 label = Label(root, text=text)
3631 label.pack()
3632 test = Button(root, text="Click me!",
3633 command=lambda root=root: root.test.configure(
3634 text="[%s]" % root.test['text']))
3635 test.pack()
3636 root.test = test
3637 quit = Button(root, text="QUIT", command=root.destroy)
3638 quit.pack()
3639 # The following three commands are needed so the window pops
3640 # up on top on Windows...
3641 root.iconify()
3642 root.update()
3643 root.deiconify()
3644 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003645
3646if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003647 _test()