blob: 833aad551af90a9d90c1269970146ffff3c8261b [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
7LabelFrame and PanedWindow.
8
9Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
11under Tk.
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
Fredrik Lundh06d28152000-08-09 18:03:12 +0000237 def get(self):
238 """Return the value of the variable as an integer."""
239 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000240
241class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000242 """Value holder for float variables."""
243 _default = 0.0
244 def __init__(self, master=None):
245 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000246
Fredrik Lundh06d28152000-08-09 18:03:12 +0000247 MASTER can be given as a master widget."""
248 Variable.__init__(self, master)
249
250 def get(self):
251 """Return the value of the variable as a float."""
252 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000253
254class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000255 """Value holder for boolean variables."""
256 _default = "false"
257 def __init__(self, master=None):
258 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000259
Fredrik Lundh06d28152000-08-09 18:03:12 +0000260 MASTER can be given as a master widget."""
261 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000262
Fredrik Lundh06d28152000-08-09 18:03:12 +0000263 def get(self):
264 """Return the value of the variable as 0 or 1."""
265 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000266
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000267def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000268 """Run the main loop of Tcl."""
269 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000270
Guido van Rossum0132f691998-04-30 17:50:36 +0000271getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000272
Guido van Rossum0132f691998-04-30 17:50:36 +0000273getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000274
275def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000276 """Convert true and false to integer values 1 and 0."""
277 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000278
Guido van Rossum368e06b1997-11-07 20:38:49 +0000279# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000280class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000281 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000282
Fredrik Lundh06d28152000-08-09 18:03:12 +0000283 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000284
Fredrik Lundh06d28152000-08-09 18:03:12 +0000285 # XXX font command?
286 _tclCommands = None
287 def destroy(self):
288 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000289
Fredrik Lundh06d28152000-08-09 18:03:12 +0000290 Delete all Tcl commands created for
291 this widget in the Tcl interpreter."""
292 if self._tclCommands is not None:
293 for name in self._tclCommands:
294 #print '- Tkinter: deleted command', name
295 self.tk.deletecommand(name)
296 self._tclCommands = None
297 def deletecommand(self, name):
298 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000299
Fredrik Lundh06d28152000-08-09 18:03:12 +0000300 Delete the Tcl command provided in NAME."""
301 #print '- Tkinter: deleted command', name
302 self.tk.deletecommand(name)
303 try:
304 self._tclCommands.remove(name)
305 except ValueError:
306 pass
307 def tk_strictMotif(self, boolean=None):
308 """Set Tcl internal variable, whether the look and feel
309 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000310
Fredrik Lundh06d28152000-08-09 18:03:12 +0000311 A parameter of 1 means adhere to Motif (e.g. no color
312 change if mouse passes over slider).
313 Returns the set value."""
314 return self.tk.getboolean(self.tk.call(
315 'set', 'tk_strictMotif', boolean))
316 def tk_bisque(self):
317 """Change the color scheme to light brown as used in Tk 3.6 and before."""
318 self.tk.call('tk_bisque')
319 def tk_setPalette(self, *args, **kw):
320 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000321
Fredrik Lundh06d28152000-08-09 18:03:12 +0000322 A single color as argument will cause that all colors of Tk
323 widget elements are derived from this.
324 Alternatively several keyword parameters and its associated
325 colors can be given. The following keywords are valid:
326 activeBackground, foreground, selectColor,
327 activeForeground, highlightBackground, selectBackground,
328 background, highlightColor, selectForeground,
329 disabledForeground, insertBackground, troughColor."""
330 self.tk.call(('tk_setPalette',)
331 + _flatten(args) + _flatten(kw.items()))
332 def tk_menuBar(self, *args):
333 """Do not use. Needed in Tk 3.6 and earlier."""
334 pass # obsolete since Tk 4.0
335 def wait_variable(self, name='PY_VAR'):
336 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000337
Fredrik Lundh06d28152000-08-09 18:03:12 +0000338 A parameter of type IntVar, StringVar, DoubleVar or
339 BooleanVar must be given."""
340 self.tk.call('tkwait', 'variable', name)
341 waitvar = wait_variable # XXX b/w compat
342 def wait_window(self, window=None):
343 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000344
Fredrik Lundh06d28152000-08-09 18:03:12 +0000345 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000346 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000347 window = self
348 self.tk.call('tkwait', 'window', window._w)
349 def wait_visibility(self, window=None):
350 """Wait until the visibility of a WIDGET changes
351 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000352
Fredrik Lundh06d28152000-08-09 18:03:12 +0000353 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000354 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000355 window = self
356 self.tk.call('tkwait', 'visibility', window._w)
357 def setvar(self, name='PY_VAR', value='1'):
358 """Set Tcl variable NAME to VALUE."""
359 self.tk.setvar(name, value)
360 def getvar(self, name='PY_VAR'):
361 """Return value of Tcl variable NAME."""
362 return self.tk.getvar(name)
363 getint = int
364 getdouble = float
365 def getboolean(self, s):
366 """Return 0 or 1 for Tcl boolean values true and false given as parameter."""
367 return self.tk.getboolean(s)
368 def focus_set(self):
369 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000370
Fredrik Lundh06d28152000-08-09 18:03:12 +0000371 If the application currently does not have the focus
372 this widget will get the focus if the application gets
373 the focus through the window manager."""
374 self.tk.call('focus', self._w)
375 focus = focus_set # XXX b/w compat?
376 def focus_force(self):
377 """Direct input focus to this widget even if the
378 application does not have the focus. Use with
379 caution!"""
380 self.tk.call('focus', '-force', self._w)
381 def focus_get(self):
382 """Return the widget which has currently the focus in the
383 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000384
Fredrik Lundh06d28152000-08-09 18:03:12 +0000385 Use focus_displayof to allow working with several
386 displays. Return None if application does not have
387 the focus."""
388 name = self.tk.call('focus')
389 if name == 'none' or not name: return None
390 return self._nametowidget(name)
391 def focus_displayof(self):
392 """Return the widget which has currently the focus on the
393 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000394
Fredrik Lundh06d28152000-08-09 18:03:12 +0000395 Return None if the application does not have the focus."""
396 name = self.tk.call('focus', '-displayof', self._w)
397 if name == 'none' or not name: return None
398 return self._nametowidget(name)
399 def focus_lastfor(self):
400 """Return the widget which would have the focus if top level
401 for this widget gets the focus from the window manager."""
402 name = self.tk.call('focus', '-lastfor', self._w)
403 if name == 'none' or not name: return None
404 return self._nametowidget(name)
405 def tk_focusFollowsMouse(self):
406 """The widget under mouse will get automatically focus. Can not
407 be disabled easily."""
408 self.tk.call('tk_focusFollowsMouse')
409 def tk_focusNext(self):
410 """Return the next widget in the focus order which follows
411 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000412
Fredrik Lundh06d28152000-08-09 18:03:12 +0000413 The focus order first goes to the next child, then to
414 the children of the child recursively and then to the
415 next sibling which is higher in the stacking order. A
416 widget is omitted if it has the takefocus resource set
417 to 0."""
418 name = self.tk.call('tk_focusNext', self._w)
419 if not name: return None
420 return self._nametowidget(name)
421 def tk_focusPrev(self):
422 """Return previous widget in the focus order. See tk_focusNext for details."""
423 name = self.tk.call('tk_focusPrev', self._w)
424 if not name: return None
425 return self._nametowidget(name)
426 def after(self, ms, func=None, *args):
427 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000428
Fredrik Lundh06d28152000-08-09 18:03:12 +0000429 MS specifies the time in milliseconds. FUNC gives the
430 function which shall be called. Additional parameters
431 are given as parameters to the function call. Return
432 identifier to cancel scheduling with after_cancel."""
433 if not func:
434 # I'd rather use time.sleep(ms*0.001)
435 self.tk.call('after', ms)
436 else:
437 # XXX Disgusting hack to clean up after calling func
438 tmp = []
439 def callit(func=func, args=args, self=self, tmp=tmp):
440 try:
441 apply(func, args)
442 finally:
443 try:
444 self.deletecommand(tmp[0])
445 except TclError:
446 pass
447 name = self._register(callit)
448 tmp.append(name)
449 return self.tk.call('after', ms, name)
450 def after_idle(self, func, *args):
451 """Call FUNC once if the Tcl main loop has no event to
452 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000453
Fredrik Lundh06d28152000-08-09 18:03:12 +0000454 Return an identifier to cancel the scheduling with
455 after_cancel."""
456 return apply(self.after, ('idle', func) + args)
457 def after_cancel(self, id):
458 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000459
Fredrik Lundh06d28152000-08-09 18:03:12 +0000460 Identifier returned by after or after_idle must be
461 given as first parameter."""
462 self.tk.call('after', 'cancel', id)
463 def bell(self, displayof=0):
464 """Ring a display's bell."""
465 self.tk.call(('bell',) + self._displayof(displayof))
466 # Clipboard handling:
467 def clipboard_clear(self, **kw):
468 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000469
Fredrik Lundh06d28152000-08-09 18:03:12 +0000470 A widget specified for the optional displayof keyword
471 argument specifies the target display."""
472 if not kw.has_key('displayof'): kw['displayof'] = self._w
473 self.tk.call(('clipboard', 'clear') + self._options(kw))
474 def clipboard_append(self, string, **kw):
475 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000476
Fredrik Lundh06d28152000-08-09 18:03:12 +0000477 A widget specified at the optional displayof keyword
478 argument specifies the target display. The clipboard
479 can be retrieved with selection_get."""
480 if not kw.has_key('displayof'): kw['displayof'] = self._w
481 self.tk.call(('clipboard', 'append') + self._options(kw)
482 + ('--', string))
483 # XXX grab current w/o window argument
484 def grab_current(self):
485 """Return widget which has currently the grab in this application
486 or None."""
487 name = self.tk.call('grab', 'current', self._w)
488 if not name: return None
489 return self._nametowidget(name)
490 def grab_release(self):
491 """Release grab for this widget if currently set."""
492 self.tk.call('grab', 'release', self._w)
493 def grab_set(self):
494 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000495
Fredrik Lundh06d28152000-08-09 18:03:12 +0000496 A grab directs all events to this and descendant
497 widgets in the application."""
498 self.tk.call('grab', 'set', self._w)
499 def grab_set_global(self):
500 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000501
Fredrik Lundh06d28152000-08-09 18:03:12 +0000502 A global grab directs all events to this and
503 descendant widgets on the display. Use with caution -
504 other applications do not get events anymore."""
505 self.tk.call('grab', 'set', '-global', self._w)
506 def grab_status(self):
507 """Return None, "local" or "global" if this widget has
508 no, a local or a global grab."""
509 status = self.tk.call('grab', 'status', self._w)
510 if status == 'none': status = None
511 return status
512 def lower(self, belowThis=None):
513 """Lower this widget in the stacking order."""
514 self.tk.call('lower', self._w, belowThis)
515 def option_add(self, pattern, value, priority = None):
516 """Set a VALUE (second parameter) for an option
517 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000518
Fredrik Lundh06d28152000-08-09 18:03:12 +0000519 An optional third parameter gives the numeric priority
520 (defaults to 80)."""
521 self.tk.call('option', 'add', pattern, value, priority)
522 def option_clear(self):
523 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000524
Fredrik Lundh06d28152000-08-09 18:03:12 +0000525 It will be reloaded if option_add is called."""
526 self.tk.call('option', 'clear')
527 def option_get(self, name, className):
528 """Return the value for an option NAME for this widget
529 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000530
Fredrik Lundh06d28152000-08-09 18:03:12 +0000531 Values with higher priority override lower values."""
532 return self.tk.call('option', 'get', self._w, name, className)
533 def option_readfile(self, fileName, priority = None):
534 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000535
Fredrik Lundh06d28152000-08-09 18:03:12 +0000536 An optional second parameter gives the numeric
537 priority."""
538 self.tk.call('option', 'readfile', fileName, priority)
539 def selection_clear(self, **kw):
540 """Clear the current X selection."""
541 if not kw.has_key('displayof'): kw['displayof'] = self._w
542 self.tk.call(('selection', 'clear') + self._options(kw))
543 def selection_get(self, **kw):
544 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000545
Fredrik Lundh06d28152000-08-09 18:03:12 +0000546 A keyword parameter selection specifies the name of
547 the selection and defaults to PRIMARY. A keyword
548 parameter displayof specifies a widget on the display
549 to use."""
550 if not kw.has_key('displayof'): kw['displayof'] = self._w
551 return self.tk.call(('selection', 'get') + self._options(kw))
552 def selection_handle(self, command, **kw):
553 """Specify a function COMMAND to call if the X
554 selection owned by this widget is queried by another
555 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000556
Fredrik Lundh06d28152000-08-09 18:03:12 +0000557 This function must return the contents of the
558 selection. The function will be called with the
559 arguments OFFSET and LENGTH which allows the chunking
560 of very long selections. The following keyword
561 parameters can be provided:
562 selection - name of the selection (default PRIMARY),
563 type - type of the selection (e.g. STRING, FILE_NAME)."""
564 name = self._register(command)
565 self.tk.call(('selection', 'handle') + self._options(kw)
566 + (self._w, name))
567 def selection_own(self, **kw):
568 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000569
Fredrik Lundh06d28152000-08-09 18:03:12 +0000570 A keyword parameter selection specifies the name of
571 the selection (default PRIMARY)."""
572 self.tk.call(('selection', 'own') +
573 self._options(kw) + (self._w,))
574 def selection_own_get(self, **kw):
575 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000576
Fredrik Lundh06d28152000-08-09 18:03:12 +0000577 The following keyword parameter can
578 be provided:
579 selection - name of the selection (default PRIMARY),
580 type - type of the selection (e.g. STRING, FILE_NAME)."""
581 if not kw.has_key('displayof'): kw['displayof'] = self._w
582 name = self.tk.call(('selection', 'own') + self._options(kw))
583 if not name: return None
584 return self._nametowidget(name)
585 def send(self, interp, cmd, *args):
586 """Send Tcl command CMD to different interpreter INTERP to be executed."""
587 return self.tk.call(('send', interp, cmd) + args)
588 def lower(self, belowThis=None):
589 """Lower this widget in the stacking order."""
590 self.tk.call('lower', self._w, belowThis)
591 def tkraise(self, aboveThis=None):
592 """Raise this widget in the stacking order."""
593 self.tk.call('raise', self._w, aboveThis)
594 lift = tkraise
595 def colormodel(self, value=None):
596 """Useless. Not implemented in Tk."""
597 return self.tk.call('tk', 'colormodel', self._w, value)
598 def winfo_atom(self, name, displayof=0):
599 """Return integer which represents atom NAME."""
600 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
601 return getint(self.tk.call(args))
602 def winfo_atomname(self, id, displayof=0):
603 """Return name of atom with identifier ID."""
604 args = ('winfo', 'atomname') \
605 + self._displayof(displayof) + (id,)
606 return self.tk.call(args)
607 def winfo_cells(self):
608 """Return number of cells in the colormap for this widget."""
609 return getint(
610 self.tk.call('winfo', 'cells', self._w))
611 def winfo_children(self):
612 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000613 result = []
614 for child in self.tk.splitlist(
615 self.tk.call('winfo', 'children', self._w)):
616 try:
617 # Tcl sometimes returns extra windows, e.g. for
618 # menus; those need to be skipped
619 result.append(self._nametowidget(child))
620 except KeyError:
621 pass
622 return result
623
Fredrik Lundh06d28152000-08-09 18:03:12 +0000624 def winfo_class(self):
625 """Return window class name of this widget."""
626 return self.tk.call('winfo', 'class', self._w)
627 def winfo_colormapfull(self):
628 """Return true if at the last color request the colormap was full."""
629 return self.tk.getboolean(
630 self.tk.call('winfo', 'colormapfull', self._w))
631 def winfo_containing(self, rootX, rootY, displayof=0):
632 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
633 args = ('winfo', 'containing') \
634 + self._displayof(displayof) + (rootX, rootY)
635 name = self.tk.call(args)
636 if not name: return None
637 return self._nametowidget(name)
638 def winfo_depth(self):
639 """Return the number of bits per pixel."""
640 return getint(self.tk.call('winfo', 'depth', self._w))
641 def winfo_exists(self):
642 """Return true if this widget exists."""
643 return getint(
644 self.tk.call('winfo', 'exists', self._w))
645 def winfo_fpixels(self, number):
646 """Return the number of pixels for the given distance NUMBER
647 (e.g. "3c") as float."""
648 return getdouble(self.tk.call(
649 'winfo', 'fpixels', self._w, number))
650 def winfo_geometry(self):
651 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
652 return self.tk.call('winfo', 'geometry', self._w)
653 def winfo_height(self):
654 """Return height of this widget."""
655 return getint(
656 self.tk.call('winfo', 'height', self._w))
657 def winfo_id(self):
658 """Return identifier ID for this widget."""
659 return self.tk.getint(
660 self.tk.call('winfo', 'id', self._w))
661 def winfo_interps(self, displayof=0):
662 """Return the name of all Tcl interpreters for this display."""
663 args = ('winfo', 'interps') + self._displayof(displayof)
664 return self.tk.splitlist(self.tk.call(args))
665 def winfo_ismapped(self):
666 """Return true if this widget is mapped."""
667 return getint(
668 self.tk.call('winfo', 'ismapped', self._w))
669 def winfo_manager(self):
670 """Return the window mananger name for this widget."""
671 return self.tk.call('winfo', 'manager', self._w)
672 def winfo_name(self):
673 """Return the name of this widget."""
674 return self.tk.call('winfo', 'name', self._w)
675 def winfo_parent(self):
676 """Return the name of the parent of this widget."""
677 return self.tk.call('winfo', 'parent', self._w)
678 def winfo_pathname(self, id, displayof=0):
679 """Return the pathname of the widget given by ID."""
680 args = ('winfo', 'pathname') \
681 + self._displayof(displayof) + (id,)
682 return self.tk.call(args)
683 def winfo_pixels(self, number):
684 """Rounded integer value of winfo_fpixels."""
685 return getint(
686 self.tk.call('winfo', 'pixels', self._w, number))
687 def winfo_pointerx(self):
688 """Return the x coordinate of the pointer on the root window."""
689 return getint(
690 self.tk.call('winfo', 'pointerx', self._w))
691 def winfo_pointerxy(self):
692 """Return a tuple of x and y coordinates of the pointer on the root window."""
693 return self._getints(
694 self.tk.call('winfo', 'pointerxy', self._w))
695 def winfo_pointery(self):
696 """Return the y coordinate of the pointer on the root window."""
697 return getint(
698 self.tk.call('winfo', 'pointery', self._w))
699 def winfo_reqheight(self):
700 """Return requested height of this widget."""
701 return getint(
702 self.tk.call('winfo', 'reqheight', self._w))
703 def winfo_reqwidth(self):
704 """Return requested width of this widget."""
705 return getint(
706 self.tk.call('winfo', 'reqwidth', self._w))
707 def winfo_rgb(self, color):
708 """Return tuple of decimal values for red, green, blue for
709 COLOR in this widget."""
710 return self._getints(
711 self.tk.call('winfo', 'rgb', self._w, color))
712 def winfo_rootx(self):
713 """Return x coordinate of upper left corner of this widget on the
714 root window."""
715 return getint(
716 self.tk.call('winfo', 'rootx', self._w))
717 def winfo_rooty(self):
718 """Return y coordinate of upper left corner of this widget on the
719 root window."""
720 return getint(
721 self.tk.call('winfo', 'rooty', self._w))
722 def winfo_screen(self):
723 """Return the screen name of this widget."""
724 return self.tk.call('winfo', 'screen', self._w)
725 def winfo_screencells(self):
726 """Return the number of the cells in the colormap of the screen
727 of this widget."""
728 return getint(
729 self.tk.call('winfo', 'screencells', self._w))
730 def winfo_screendepth(self):
731 """Return the number of bits per pixel of the root window of the
732 screen of this widget."""
733 return getint(
734 self.tk.call('winfo', 'screendepth', self._w))
735 def winfo_screenheight(self):
736 """Return the number of pixels of the height of the screen of this widget
737 in pixel."""
738 return getint(
739 self.tk.call('winfo', 'screenheight', self._w))
740 def winfo_screenmmheight(self):
741 """Return the number of pixels of the height of the screen of
742 this widget in mm."""
743 return getint(
744 self.tk.call('winfo', 'screenmmheight', self._w))
745 def winfo_screenmmwidth(self):
746 """Return the number of pixels of the width of the screen of
747 this widget in mm."""
748 return getint(
749 self.tk.call('winfo', 'screenmmwidth', self._w))
750 def winfo_screenvisual(self):
751 """Return one of the strings directcolor, grayscale, pseudocolor,
752 staticcolor, staticgray, or truecolor for the default
753 colormodel of this screen."""
754 return self.tk.call('winfo', 'screenvisual', self._w)
755 def winfo_screenwidth(self):
756 """Return the number of pixels of the width of the screen of
757 this widget in pixel."""
758 return getint(
759 self.tk.call('winfo', 'screenwidth', self._w))
760 def winfo_server(self):
761 """Return information of the X-Server of the screen of this widget in
762 the form "XmajorRminor vendor vendorVersion"."""
763 return self.tk.call('winfo', 'server', self._w)
764 def winfo_toplevel(self):
765 """Return the toplevel widget of this widget."""
766 return self._nametowidget(self.tk.call(
767 'winfo', 'toplevel', self._w))
768 def winfo_viewable(self):
769 """Return true if the widget and all its higher ancestors are mapped."""
770 return getint(
771 self.tk.call('winfo', 'viewable', self._w))
772 def winfo_visual(self):
773 """Return one of the strings directcolor, grayscale, pseudocolor,
774 staticcolor, staticgray, or truecolor for the
775 colormodel of this widget."""
776 return self.tk.call('winfo', 'visual', self._w)
777 def winfo_visualid(self):
778 """Return the X identifier for the visual for this widget."""
779 return self.tk.call('winfo', 'visualid', self._w)
780 def winfo_visualsavailable(self, includeids=0):
781 """Return a list of all visuals available for the screen
782 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000783
Fredrik Lundh06d28152000-08-09 18:03:12 +0000784 Each item in the list consists of a visual name (see winfo_visual), a
785 depth and if INCLUDEIDS=1 is given also the X identifier."""
786 data = self.tk.split(
787 self.tk.call('winfo', 'visualsavailable', self._w,
788 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000789 if type(data) is StringType:
790 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000791 return map(self.__winfo_parseitem, data)
792 def __winfo_parseitem(self, t):
793 """Internal function."""
794 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
795 def __winfo_getint(self, x):
796 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000797 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000798 def winfo_vrootheight(self):
799 """Return the height of the virtual root window associated with this
800 widget in pixels. If there is no virtual root window return the
801 height of the screen."""
802 return getint(
803 self.tk.call('winfo', 'vrootheight', self._w))
804 def winfo_vrootwidth(self):
805 """Return the width of the virtual root window associated with this
806 widget in pixel. If there is no virtual root window return the
807 width of the screen."""
808 return getint(
809 self.tk.call('winfo', 'vrootwidth', self._w))
810 def winfo_vrootx(self):
811 """Return the x offset of the virtual root relative to the root
812 window of the screen of this widget."""
813 return getint(
814 self.tk.call('winfo', 'vrootx', self._w))
815 def winfo_vrooty(self):
816 """Return the y offset of the virtual root relative to the root
817 window of the screen of this widget."""
818 return getint(
819 self.tk.call('winfo', 'vrooty', self._w))
820 def winfo_width(self):
821 """Return the width of this widget."""
822 return getint(
823 self.tk.call('winfo', 'width', self._w))
824 def winfo_x(self):
825 """Return the x coordinate of the upper left corner of this widget
826 in the parent."""
827 return getint(
828 self.tk.call('winfo', 'x', self._w))
829 def winfo_y(self):
830 """Return the y coordinate of the upper left corner of this widget
831 in the parent."""
832 return getint(
833 self.tk.call('winfo', 'y', self._w))
834 def update(self):
835 """Enter event loop until all pending events have been processed by Tcl."""
836 self.tk.call('update')
837 def update_idletasks(self):
838 """Enter event loop until all idle callbacks have been called. This
839 will update the display of windows but not process events caused by
840 the user."""
841 self.tk.call('update', 'idletasks')
842 def bindtags(self, tagList=None):
843 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000844
Fredrik Lundh06d28152000-08-09 18:03:12 +0000845 With no argument return the list of all bindtags associated with
846 this widget. With a list of strings as argument the bindtags are
847 set to this list. The bindtags determine in which order events are
848 processed (see bind)."""
849 if tagList is None:
850 return self.tk.splitlist(
851 self.tk.call('bindtags', self._w))
852 else:
853 self.tk.call('bindtags', self._w, tagList)
854 def _bind(self, what, sequence, func, add, needcleanup=1):
855 """Internal function."""
856 if type(func) is StringType:
857 self.tk.call(what + (sequence, func))
858 elif func:
859 funcid = self._register(func, self._substitute,
860 needcleanup)
861 cmd = ('%sif {"[%s %s]" == "break"} break\n'
862 %
863 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000864 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000865 self.tk.call(what + (sequence, cmd))
866 return funcid
867 elif sequence:
868 return self.tk.call(what + (sequence,))
869 else:
870 return self.tk.splitlist(self.tk.call(what))
871 def bind(self, sequence=None, func=None, add=None):
872 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000873
Fredrik Lundh06d28152000-08-09 18:03:12 +0000874 SEQUENCE is a string of concatenated event
875 patterns. An event pattern is of the form
876 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
877 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
878 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
879 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
880 Mod1, M1. TYPE is one of Activate, Enter, Map,
881 ButtonPress, Button, Expose, Motion, ButtonRelease
882 FocusIn, MouseWheel, Circulate, FocusOut, Property,
883 Colormap, Gravity Reparent, Configure, KeyPress, Key,
884 Unmap, Deactivate, KeyRelease Visibility, Destroy,
885 Leave and DETAIL is the button number for ButtonPress,
886 ButtonRelease and DETAIL is the Keysym for KeyPress and
887 KeyRelease. Examples are
888 <Control-Button-1> for pressing Control and mouse button 1 or
889 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
890 An event pattern can also be a virtual event of the form
891 <<AString>> where AString can be arbitrary. This
892 event can be generated by event_generate.
893 If events are concatenated they must appear shortly
894 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000895
Fredrik Lundh06d28152000-08-09 18:03:12 +0000896 FUNC will be called if the event sequence occurs with an
897 instance of Event as argument. If the return value of FUNC is
898 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000899
Fredrik Lundh06d28152000-08-09 18:03:12 +0000900 An additional boolean parameter ADD specifies whether FUNC will
901 be called additionally to the other bound function or whether
902 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000903
Fredrik Lundh06d28152000-08-09 18:03:12 +0000904 Bind will return an identifier to allow deletion of the bound function with
905 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000906
Fredrik Lundh06d28152000-08-09 18:03:12 +0000907 If FUNC or SEQUENCE is omitted the bound function or list
908 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000909
Fredrik Lundh06d28152000-08-09 18:03:12 +0000910 return self._bind(('bind', self._w), sequence, func, add)
911 def unbind(self, sequence, funcid=None):
912 """Unbind for this widget for event SEQUENCE the
913 function identified with FUNCID."""
914 self.tk.call('bind', self._w, sequence, '')
915 if funcid:
916 self.deletecommand(funcid)
917 def bind_all(self, sequence=None, func=None, add=None):
918 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
919 An additional boolean parameter ADD specifies whether FUNC will
920 be called additionally to the other bound function or whether
921 it will replace the previous function. See bind for the return value."""
922 return self._bind(('bind', 'all'), sequence, func, add, 0)
923 def unbind_all(self, sequence):
924 """Unbind for all widgets for event SEQUENCE all functions."""
925 self.tk.call('bind', 'all' , sequence, '')
926 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000927
Fredrik Lundh06d28152000-08-09 18:03:12 +0000928 """Bind to widgets with bindtag CLASSNAME at event
929 SEQUENCE a call of function FUNC. An additional
930 boolean parameter ADD specifies whether FUNC will be
931 called additionally to the other bound function or
932 whether it will replace the previous function. See bind for
933 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000934
Fredrik Lundh06d28152000-08-09 18:03:12 +0000935 return self._bind(('bind', className), sequence, func, add, 0)
936 def unbind_class(self, className, sequence):
937 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
938 all functions."""
939 self.tk.call('bind', className , sequence, '')
940 def mainloop(self, n=0):
941 """Call the mainloop of Tk."""
942 self.tk.mainloop(n)
943 def quit(self):
944 """Quit the Tcl interpreter. All widgets will be destroyed."""
945 self.tk.quit()
946 def _getints(self, string):
947 """Internal function."""
948 if string:
949 return tuple(map(getint, self.tk.splitlist(string)))
950 def _getdoubles(self, string):
951 """Internal function."""
952 if string:
953 return tuple(map(getdouble, self.tk.splitlist(string)))
954 def _getboolean(self, string):
955 """Internal function."""
956 if string:
957 return self.tk.getboolean(string)
958 def _displayof(self, displayof):
959 """Internal function."""
960 if displayof:
961 return ('-displayof', displayof)
962 if displayof is None:
963 return ('-displayof', self._w)
964 return ()
965 def _options(self, cnf, kw = None):
966 """Internal function."""
967 if kw:
968 cnf = _cnfmerge((cnf, kw))
969 else:
970 cnf = _cnfmerge(cnf)
971 res = ()
972 for k, v in cnf.items():
973 if v is not None:
974 if k[-1] == '_': k = k[:-1]
975 if callable(v):
976 v = self._register(v)
977 res = res + ('-'+k, v)
978 return res
979 def nametowidget(self, name):
980 """Return the Tkinter instance of a widget identified by
981 its Tcl name NAME."""
982 w = self
983 if name[0] == '.':
984 w = w._root()
985 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000986 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000987 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +0000988 if i >= 0:
989 name, tail = name[:i], name[i+1:]
990 else:
991 tail = ''
992 w = w.children[name]
993 name = tail
994 return w
995 _nametowidget = nametowidget
996 def _register(self, func, subst=None, needcleanup=1):
997 """Return a newly created Tcl function. If this
998 function is called, the Python function FUNC will
999 be executed. An optional function SUBST can
1000 be given which will be executed before FUNC."""
1001 f = CallWrapper(func, subst, self).__call__
1002 name = `id(f)`
1003 try:
1004 func = func.im_func
1005 except AttributeError:
1006 pass
1007 try:
1008 name = name + func.__name__
1009 except AttributeError:
1010 pass
1011 self.tk.createcommand(name, f)
1012 if needcleanup:
1013 if self._tclCommands is None:
1014 self._tclCommands = []
1015 self._tclCommands.append(name)
1016 #print '+ Tkinter created command', name
1017 return name
1018 register = _register
1019 def _root(self):
1020 """Internal function."""
1021 w = self
1022 while w.master: w = w.master
1023 return w
1024 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1025 '%s', '%t', '%w', '%x', '%y',
1026 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001027 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001028 def _substitute(self, *args):
1029 """Internal function."""
1030 if len(args) != len(self._subst_format): return args
1031 getboolean = self.tk.getboolean
1032 getint = int
1033 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1034 # Missing: (a, c, d, m, o, v, B, R)
1035 e = Event()
1036 e.serial = getint(nsign)
1037 e.num = getint(b)
1038 try: e.focus = getboolean(f)
1039 except TclError: pass
1040 e.height = getint(h)
1041 e.keycode = getint(k)
1042 # For Visibility events, event state is a string and
1043 # not an integer:
1044 try:
1045 e.state = getint(s)
1046 except ValueError:
1047 e.state = s
1048 e.time = getint(t)
1049 e.width = getint(w)
1050 e.x = getint(x)
1051 e.y = getint(y)
1052 e.char = A
1053 try: e.send_event = getboolean(E)
1054 except TclError: pass
1055 e.keysym = K
1056 e.keysym_num = getint(N)
1057 e.type = T
1058 try:
1059 e.widget = self._nametowidget(W)
1060 except KeyError:
1061 e.widget = W
1062 e.x_root = getint(X)
1063 e.y_root = getint(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001064 try:
1065 e.delta = getint(D)
1066 except ValueError:
1067 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001068 return (e,)
1069 def _report_exception(self):
1070 """Internal function."""
1071 import sys
1072 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1073 root = self._root()
1074 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001075 def _configure(self, cmd, cnf, kw):
1076 """Internal function."""
1077 if kw:
1078 cnf = _cnfmerge((cnf, kw))
1079 elif cnf:
1080 cnf = _cnfmerge(cnf)
1081 if cnf is None:
1082 cnf = {}
1083 for x in self.tk.split(
1084 self.tk.call(_flatten((self._w, cmd)))):
1085 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1086 return cnf
1087 if type(cnf) is StringType:
1088 x = self.tk.split(
1089 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1090 return (x[0][1:],) + x[1:]
1091 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001092 # These used to be defined in Widget:
1093 def configure(self, cnf=None, **kw):
1094 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001095
Fredrik Lundh06d28152000-08-09 18:03:12 +00001096 The values for resources are specified as keyword
1097 arguments. To get an overview about
1098 the allowed keyword arguments call the method keys.
1099 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001100 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001101 config = configure
1102 def cget(self, key):
1103 """Return the resource value for a KEY given as string."""
1104 return self.tk.call(self._w, 'cget', '-' + key)
1105 __getitem__ = cget
1106 def __setitem__(self, key, value):
1107 self.configure({key: value})
1108 def keys(self):
1109 """Return a list of all resource names of this widget."""
1110 return map(lambda x: x[0][1:],
1111 self.tk.split(self.tk.call(self._w, 'configure')))
1112 def __str__(self):
1113 """Return the window path name of this widget."""
1114 return self._w
1115 # Pack methods that apply to the master
1116 _noarg_ = ['_noarg_']
1117 def pack_propagate(self, flag=_noarg_):
1118 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001119
Fredrik Lundh06d28152000-08-09 18:03:12 +00001120 A boolean argument specifies whether the geometry information
1121 of the slaves will determine the size of this widget. If no argument
1122 is given the current setting will be returned.
1123 """
1124 if flag is Misc._noarg_:
1125 return self._getboolean(self.tk.call(
1126 'pack', 'propagate', self._w))
1127 else:
1128 self.tk.call('pack', 'propagate', self._w, flag)
1129 propagate = pack_propagate
1130 def pack_slaves(self):
1131 """Return a list of all slaves of this widget
1132 in its packing order."""
1133 return map(self._nametowidget,
1134 self.tk.splitlist(
1135 self.tk.call('pack', 'slaves', self._w)))
1136 slaves = pack_slaves
1137 # Place method that applies to the master
1138 def place_slaves(self):
1139 """Return a list of all slaves of this widget
1140 in its packing order."""
1141 return map(self._nametowidget,
1142 self.tk.splitlist(
1143 self.tk.call(
1144 'place', 'slaves', self._w)))
1145 # Grid methods that apply to the master
1146 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1147 """Return a tuple of integer coordinates for the bounding
1148 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001149
Fredrik Lundh06d28152000-08-09 18:03:12 +00001150 If COLUMN, ROW is given the bounding box applies from
1151 the cell with row and column 0 to the specified
1152 cell. If COL2 and ROW2 are given the bounding box
1153 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001154
Fredrik Lundh06d28152000-08-09 18:03:12 +00001155 The returned integers specify the offset of the upper left
1156 corner in the master widget and the width and height.
1157 """
1158 args = ('grid', 'bbox', self._w)
1159 if column is not None and row is not None:
1160 args = args + (column, row)
1161 if col2 is not None and row2 is not None:
1162 args = args + (col2, row2)
1163 return self._getints(apply(self.tk.call, args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001164
Fredrik Lundh06d28152000-08-09 18:03:12 +00001165 bbox = grid_bbox
1166 def _grid_configure(self, command, index, cnf, kw):
1167 """Internal function."""
1168 if type(cnf) is StringType and not kw:
1169 if cnf[-1:] == '_':
1170 cnf = cnf[:-1]
1171 if cnf[:1] != '-':
1172 cnf = '-'+cnf
1173 options = (cnf,)
1174 else:
1175 options = self._options(cnf, kw)
1176 if not options:
1177 res = self.tk.call('grid',
1178 command, self._w, index)
1179 words = self.tk.splitlist(res)
1180 dict = {}
1181 for i in range(0, len(words), 2):
1182 key = words[i][1:]
1183 value = words[i+1]
1184 if not value:
1185 value = None
1186 elif '.' in value:
1187 value = getdouble(value)
1188 else:
1189 value = getint(value)
1190 dict[key] = value
1191 return dict
1192 res = self.tk.call(
1193 ('grid', command, self._w, index)
1194 + options)
1195 if len(options) == 1:
1196 if not res: return None
1197 # In Tk 7.5, -width can be a float
1198 if '.' in res: return getdouble(res)
1199 return getint(res)
1200 def grid_columnconfigure(self, index, cnf={}, **kw):
1201 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001202
Fredrik Lundh06d28152000-08-09 18:03:12 +00001203 Valid resources are minsize (minimum size of the column),
1204 weight (how much does additional space propagate to this column)
1205 and pad (how much space to let additionally)."""
1206 return self._grid_configure('columnconfigure', index, cnf, kw)
1207 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001208 def grid_location(self, x, y):
1209 """Return a tuple of column and row which identify the cell
1210 at which the pixel at position X and Y inside the master
1211 widget is located."""
1212 return self._getints(
1213 self.tk.call(
1214 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001215 def grid_propagate(self, flag=_noarg_):
1216 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001217
Fredrik Lundh06d28152000-08-09 18:03:12 +00001218 A boolean argument specifies whether the geometry information
1219 of the slaves will determine the size of this widget. If no argument
1220 is given, the current setting will be returned.
1221 """
1222 if flag is Misc._noarg_:
1223 return self._getboolean(self.tk.call(
1224 'grid', 'propagate', self._w))
1225 else:
1226 self.tk.call('grid', 'propagate', self._w, flag)
1227 def grid_rowconfigure(self, index, cnf={}, **kw):
1228 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001229
Fredrik Lundh06d28152000-08-09 18:03:12 +00001230 Valid resources are minsize (minimum size of the row),
1231 weight (how much does additional space propagate to this row)
1232 and pad (how much space to let additionally)."""
1233 return self._grid_configure('rowconfigure', index, cnf, kw)
1234 rowconfigure = grid_rowconfigure
1235 def grid_size(self):
1236 """Return a tuple of the number of column and rows in the grid."""
1237 return self._getints(
1238 self.tk.call('grid', 'size', self._w)) or None
1239 size = grid_size
1240 def grid_slaves(self, row=None, column=None):
1241 """Return a list of all slaves of this widget
1242 in its packing order."""
1243 args = ()
1244 if row is not None:
1245 args = args + ('-row', row)
1246 if column is not None:
1247 args = args + ('-column', column)
1248 return map(self._nametowidget,
1249 self.tk.splitlist(self.tk.call(
1250 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001251
Fredrik Lundh06d28152000-08-09 18:03:12 +00001252 # Support for the "event" command, new in Tk 4.2.
1253 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001254
Fredrik Lundh06d28152000-08-09 18:03:12 +00001255 def event_add(self, virtual, *sequences):
1256 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1257 to an event SEQUENCE such that the virtual event is triggered
1258 whenever SEQUENCE occurs."""
1259 args = ('event', 'add', virtual) + sequences
1260 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001261
Fredrik Lundh06d28152000-08-09 18:03:12 +00001262 def event_delete(self, virtual, *sequences):
1263 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1264 args = ('event', 'delete', virtual) + sequences
1265 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001266
Fredrik Lundh06d28152000-08-09 18:03:12 +00001267 def event_generate(self, sequence, **kw):
1268 """Generate an event SEQUENCE. Additional
1269 keyword arguments specify parameter of the event
1270 (e.g. x, y, rootx, rooty)."""
1271 args = ('event', 'generate', self._w, sequence)
1272 for k, v in kw.items():
1273 args = args + ('-%s' % k, str(v))
1274 self.tk.call(args)
1275
1276 def event_info(self, virtual=None):
1277 """Return a list of all virtual events or the information
1278 about the SEQUENCE bound to the virtual event VIRTUAL."""
1279 return self.tk.splitlist(
1280 self.tk.call('event', 'info', virtual))
1281
1282 # Image related commands
1283
1284 def image_names(self):
1285 """Return a list of all existing image names."""
1286 return self.tk.call('image', 'names')
1287
1288 def image_types(self):
1289 """Return a list of all available image types (e.g. phote bitmap)."""
1290 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001291
Guido van Rossum80f8be81997-12-02 19:51:39 +00001292
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001293class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001294 """Internal class. Stores function to call when some user
1295 defined Tcl function is called e.g. after an event occurred."""
1296 def __init__(self, func, subst, widget):
1297 """Store FUNC, SUBST and WIDGET as members."""
1298 self.func = func
1299 self.subst = subst
1300 self.widget = widget
1301 def __call__(self, *args):
1302 """Apply first function SUBST to arguments, than FUNC."""
1303 try:
1304 if self.subst:
1305 args = apply(self.subst, args)
1306 return apply(self.func, args)
1307 except SystemExit, msg:
1308 raise SystemExit, msg
1309 except:
1310 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001311
Guido van Rossume365a591998-05-01 19:48:20 +00001312
Guido van Rossum18468821994-06-20 07:49:28 +00001313class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001314 """Provides functions for the communication with the window manager."""
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001315
Fredrik Lundh06d28152000-08-09 18:03:12 +00001316 def wm_aspect(self,
1317 minNumer=None, minDenom=None,
1318 maxNumer=None, maxDenom=None):
1319 """Instruct the window manager to set the aspect ratio (width/height)
1320 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1321 of the actual values if no argument is given."""
1322 return self._getints(
1323 self.tk.call('wm', 'aspect', self._w,
1324 minNumer, minDenom,
1325 maxNumer, maxDenom))
1326 aspect = wm_aspect
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001327
1328 def wm_attributes(self, *args):
1329 """This subcommand returns or sets platform specific attributes
1330
1331 The first form returns a list of the platform specific flags and
1332 their values. The second form returns the value for the specific
1333 option. The third form sets one or more of the values. The values
1334 are as follows:
1335
1336 On Windows, -disabled gets or sets whether the window is in a
1337 disabled state. -toolwindow gets or sets the style of the window
1338 to toolwindow (as defined in the MSDN). -topmost gets or sets
1339 whether this is a topmost window (displays above all other
1340 windows).
1341
1342 On Macintosh, XXXXX
1343
1344 On Unix, there are currently no special attribute values.
1345 """
1346 args = ('wm', 'attributes', self._w) + args
1347 return self.tk.call(args)
1348 attributes=wm_attributes
1349
Fredrik Lundh06d28152000-08-09 18:03:12 +00001350 def wm_client(self, name=None):
1351 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1352 current value."""
1353 return self.tk.call('wm', 'client', self._w, name)
1354 client = wm_client
1355 def wm_colormapwindows(self, *wlist):
1356 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1357 of this widget. This list contains windows whose colormaps differ from their
1358 parents. Return current list of widgets if WLIST is empty."""
1359 if len(wlist) > 1:
1360 wlist = (wlist,) # Tk needs a list of windows here
1361 args = ('wm', 'colormapwindows', self._w) + wlist
1362 return map(self._nametowidget, self.tk.call(args))
1363 colormapwindows = wm_colormapwindows
1364 def wm_command(self, value=None):
1365 """Store VALUE in WM_COMMAND property. It is the command
1366 which shall be used to invoke the application. Return current
1367 command if VALUE is None."""
1368 return self.tk.call('wm', 'command', self._w, value)
1369 command = wm_command
1370 def wm_deiconify(self):
1371 """Deiconify this widget. If it was never mapped it will not be mapped.
1372 On Windows it will raise this widget and give it the focus."""
1373 return self.tk.call('wm', 'deiconify', self._w)
1374 deiconify = wm_deiconify
1375 def wm_focusmodel(self, model=None):
1376 """Set focus model to MODEL. "active" means that this widget will claim
1377 the focus itself, "passive" means that the window manager shall give
1378 the focus. Return current focus model if MODEL is None."""
1379 return self.tk.call('wm', 'focusmodel', self._w, model)
1380 focusmodel = wm_focusmodel
1381 def wm_frame(self):
1382 """Return identifier for decorative frame of this widget if present."""
1383 return self.tk.call('wm', 'frame', self._w)
1384 frame = wm_frame
1385 def wm_geometry(self, newGeometry=None):
1386 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1387 current value if None is given."""
1388 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1389 geometry = wm_geometry
1390 def wm_grid(self,
1391 baseWidth=None, baseHeight=None,
1392 widthInc=None, heightInc=None):
1393 """Instruct the window manager that this widget shall only be
1394 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1395 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1396 number of grid units requested in Tk_GeometryRequest."""
1397 return self._getints(self.tk.call(
1398 'wm', 'grid', self._w,
1399 baseWidth, baseHeight, widthInc, heightInc))
1400 grid = wm_grid
1401 def wm_group(self, pathName=None):
1402 """Set the group leader widgets for related widgets to PATHNAME. Return
1403 the group leader of this widget if None is given."""
1404 return self.tk.call('wm', 'group', self._w, pathName)
1405 group = wm_group
1406 def wm_iconbitmap(self, bitmap=None):
1407 """Set bitmap for the iconified widget to BITMAP. Return
1408 the bitmap if None is given."""
1409 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1410 iconbitmap = wm_iconbitmap
1411 def wm_iconify(self):
1412 """Display widget as icon."""
1413 return self.tk.call('wm', 'iconify', self._w)
1414 iconify = wm_iconify
1415 def wm_iconmask(self, bitmap=None):
1416 """Set mask for the icon bitmap of this widget. Return the
1417 mask if None is given."""
1418 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1419 iconmask = wm_iconmask
1420 def wm_iconname(self, newName=None):
1421 """Set the name of the icon for this widget. Return the name if
1422 None is given."""
1423 return self.tk.call('wm', 'iconname', self._w, newName)
1424 iconname = wm_iconname
1425 def wm_iconposition(self, x=None, y=None):
1426 """Set the position of the icon of this widget to X and Y. Return
1427 a tuple of the current values of X and X if None is given."""
1428 return self._getints(self.tk.call(
1429 'wm', 'iconposition', self._w, x, y))
1430 iconposition = wm_iconposition
1431 def wm_iconwindow(self, pathName=None):
1432 """Set widget PATHNAME to be displayed instead of icon. Return the current
1433 value if None is given."""
1434 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1435 iconwindow = wm_iconwindow
1436 def wm_maxsize(self, width=None, height=None):
1437 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1438 the values are given in grid units. Return the current values if None
1439 is given."""
1440 return self._getints(self.tk.call(
1441 'wm', 'maxsize', self._w, width, height))
1442 maxsize = wm_maxsize
1443 def wm_minsize(self, width=None, height=None):
1444 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1445 the values are given in grid units. Return the current values if None
1446 is given."""
1447 return self._getints(self.tk.call(
1448 'wm', 'minsize', self._w, width, height))
1449 minsize = wm_minsize
1450 def wm_overrideredirect(self, boolean=None):
1451 """Instruct the window manager to ignore this widget
1452 if BOOLEAN is given with 1. Return the current value if None
1453 is given."""
1454 return self._getboolean(self.tk.call(
1455 'wm', 'overrideredirect', self._w, boolean))
1456 overrideredirect = wm_overrideredirect
1457 def wm_positionfrom(self, who=None):
1458 """Instruct the window manager that the position of this widget shall
1459 be defined by the user if WHO is "user", and by its own policy if WHO is
1460 "program"."""
1461 return self.tk.call('wm', 'positionfrom', self._w, who)
1462 positionfrom = wm_positionfrom
1463 def wm_protocol(self, name=None, func=None):
1464 """Bind function FUNC to command NAME for this widget.
1465 Return the function bound to NAME if None is given. NAME could be
1466 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1467 if callable(func):
1468 command = self._register(func)
1469 else:
1470 command = func
1471 return self.tk.call(
1472 'wm', 'protocol', self._w, name, command)
1473 protocol = wm_protocol
1474 def wm_resizable(self, width=None, height=None):
1475 """Instruct the window manager whether this width can be resized
1476 in WIDTH or HEIGHT. Both values are boolean values."""
1477 return self.tk.call('wm', 'resizable', self._w, width, height)
1478 resizable = wm_resizable
1479 def wm_sizefrom(self, who=None):
1480 """Instruct the window manager that the size 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', 'sizefrom', self._w, who)
1484 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001485 def wm_state(self, newstate=None):
1486 """Query or set the state of this widget as one of normal, icon,
1487 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1488 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001489 state = wm_state
1490 def wm_title(self, string=None):
1491 """Set the title of this widget."""
1492 return self.tk.call('wm', 'title', self._w, string)
1493 title = wm_title
1494 def wm_transient(self, master=None):
1495 """Instruct the window manager that this widget is transient
1496 with regard to widget MASTER."""
1497 return self.tk.call('wm', 'transient', self._w, master)
1498 transient = wm_transient
1499 def wm_withdraw(self):
1500 """Withdraw this widget from the screen such that it is unmapped
1501 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1502 return self.tk.call('wm', 'withdraw', self._w)
1503 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001504
Guido van Rossum18468821994-06-20 07:49:28 +00001505
1506class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001507 """Toplevel widget of Tk which represents mostly the main window
1508 of an appliation. It has an associated Tcl interpreter."""
1509 _w = '.'
1510 def __init__(self, screenName=None, baseName=None, className='Tk'):
1511 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1512 be created. BASENAME will be used for the identification of the profile file (see
1513 readprofile).
1514 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1515 is the name of the widget class."""
1516 global _default_root
1517 self.master = None
1518 self.children = {}
1519 if baseName is None:
1520 import sys, os
1521 baseName = os.path.basename(sys.argv[0])
1522 baseName, ext = os.path.splitext(baseName)
1523 if ext not in ('.py', '.pyc', '.pyo'):
1524 baseName = baseName + ext
1525 self.tk = _tkinter.create(screenName, baseName, className)
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001526 self.tk.wantobjects(wantobjects)
Jack Jansenbe92af02001-08-23 13:25:59 +00001527 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001528 # Disable event scanning except for Command-Period
1529 _MacOS.SchedParams(1, 0)
1530 # Work around nasty MacTk bug
1531 # XXX Is this one still needed?
1532 self.update()
1533 # Version sanity checks
1534 tk_version = self.tk.getvar('tk_version')
1535 if tk_version != _tkinter.TK_VERSION:
1536 raise RuntimeError, \
1537 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1538 % (_tkinter.TK_VERSION, tk_version)
1539 tcl_version = self.tk.getvar('tcl_version')
1540 if tcl_version != _tkinter.TCL_VERSION:
1541 raise RuntimeError, \
1542 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1543 % (_tkinter.TCL_VERSION, tcl_version)
1544 if TkVersion < 4.0:
1545 raise RuntimeError, \
1546 "Tk 4.0 or higher is required; found Tk %s" \
1547 % str(TkVersion)
1548 self.tk.createcommand('tkerror', _tkerror)
1549 self.tk.createcommand('exit', _exit)
1550 self.readprofile(baseName, className)
1551 if _support_default_root and not _default_root:
1552 _default_root = self
1553 self.protocol("WM_DELETE_WINDOW", self.destroy)
1554 def destroy(self):
1555 """Destroy this and all descendants widgets. This will
1556 end the application of this Tcl interpreter."""
1557 for c in self.children.values(): c.destroy()
1558 self.tk.call('destroy', self._w)
1559 Misc.destroy(self)
1560 global _default_root
1561 if _support_default_root and _default_root is self:
1562 _default_root = None
1563 def readprofile(self, baseName, className):
1564 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1565 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1566 such a file exists in the home directory."""
1567 import os
1568 if os.environ.has_key('HOME'): home = os.environ['HOME']
1569 else: home = os.curdir
1570 class_tcl = os.path.join(home, '.%s.tcl' % className)
1571 class_py = os.path.join(home, '.%s.py' % className)
1572 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1573 base_py = os.path.join(home, '.%s.py' % baseName)
1574 dir = {'self': self}
1575 exec 'from Tkinter import *' in dir
1576 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001577 self.tk.call('source', class_tcl)
1578 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001579 execfile(class_py, dir)
1580 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001581 self.tk.call('source', base_tcl)
1582 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001583 execfile(base_py, dir)
1584 def report_callback_exception(self, exc, val, tb):
1585 """Internal function. It reports exception on sys.stderr."""
1586 import traceback, sys
1587 sys.stderr.write("Exception in Tkinter callback\n")
1588 sys.last_type = exc
1589 sys.last_value = val
1590 sys.last_traceback = tb
1591 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001592
Guido van Rossum368e06b1997-11-07 20:38:49 +00001593# Ideally, the classes Pack, Place and Grid disappear, the
1594# pack/place/grid methods are defined on the Widget class, and
1595# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1596# ...), with pack(), place() and grid() being short for
1597# pack_configure(), place_configure() and grid_columnconfigure(), and
1598# forget() being short for pack_forget(). As a practical matter, I'm
1599# afraid that there is too much code out there that may be using the
1600# Pack, Place or Grid class, so I leave them intact -- but only as
1601# backwards compatibility features. Also note that those methods that
1602# take a master as argument (e.g. pack_propagate) have been moved to
1603# the Misc class (which now incorporates all methods common between
1604# toplevel and interior widgets). Again, for compatibility, these are
1605# copied into the Pack, Place or Grid class.
1606
Guido van Rossum18468821994-06-20 07:49:28 +00001607class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001608 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001609
Fredrik Lundh06d28152000-08-09 18:03:12 +00001610 Base class to use the methods pack_* in every widget."""
1611 def pack_configure(self, cnf={}, **kw):
1612 """Pack a widget in the parent widget. Use as options:
1613 after=widget - pack it after you have packed widget
1614 anchor=NSEW (or subset) - position widget according to
1615 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001616 before=widget - pack it before you will pack widget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001617 expand=1 or 0 - expand widget if parent size grows
1618 fill=NONE or X or Y or BOTH - fill widget if widget grows
1619 in=master - use master to contain this widget
1620 ipadx=amount - add internal padding in x direction
1621 ipady=amount - add internal padding in y direction
1622 padx=amount - add padding in x direction
1623 pady=amount - add padding in y direction
1624 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1625 """
1626 self.tk.call(
1627 ('pack', 'configure', self._w)
1628 + self._options(cnf, kw))
1629 pack = configure = config = pack_configure
1630 def pack_forget(self):
1631 """Unmap this widget and do not use it for the packing order."""
1632 self.tk.call('pack', 'forget', self._w)
1633 forget = pack_forget
1634 def pack_info(self):
1635 """Return information about the packing options
1636 for this widget."""
1637 words = self.tk.splitlist(
1638 self.tk.call('pack', 'info', self._w))
1639 dict = {}
1640 for i in range(0, len(words), 2):
1641 key = words[i][1:]
1642 value = words[i+1]
1643 if value[:1] == '.':
1644 value = self._nametowidget(value)
1645 dict[key] = value
1646 return dict
1647 info = pack_info
1648 propagate = pack_propagate = Misc.pack_propagate
1649 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001650
1651class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001652 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001653
Fredrik Lundh06d28152000-08-09 18:03:12 +00001654 Base class to use the methods place_* in every widget."""
1655 def place_configure(self, cnf={}, **kw):
1656 """Place a widget in the parent widget. Use as options:
1657 in=master - master relative to which the widget is placed.
1658 x=amount - locate anchor of this widget at position x of master
1659 y=amount - locate anchor of this widget at position y of master
1660 relx=amount - locate anchor of this widget between 0.0 and 1.0
1661 relative to width of master (1.0 is right edge)
1662 rely=amount - locate anchor of this widget between 0.0 and 1.0
1663 relative to height of master (1.0 is bottom edge)
1664 anchor=NSEW (or subset) - position anchor according to given direction
1665 width=amount - width of this widget in pixel
1666 height=amount - height of this widget in pixel
1667 relwidth=amount - width of this widget between 0.0 and 1.0
1668 relative to width of master (1.0 is the same width
1669 as the master)
1670 relheight=amount - height of this widget between 0.0 and 1.0
1671 relative to height of master (1.0 is the same
1672 height as the master)
1673 bordermode="inside" or "outside" - whether to take border width of master widget
1674 into account
1675 """
1676 for k in ['in_']:
1677 if kw.has_key(k):
1678 kw[k[:-1]] = kw[k]
1679 del kw[k]
1680 self.tk.call(
1681 ('place', 'configure', self._w)
1682 + self._options(cnf, kw))
1683 place = configure = config = place_configure
1684 def place_forget(self):
1685 """Unmap this widget."""
1686 self.tk.call('place', 'forget', self._w)
1687 forget = place_forget
1688 def place_info(self):
1689 """Return information about the placing options
1690 for this widget."""
1691 words = self.tk.splitlist(
1692 self.tk.call('place', 'info', self._w))
1693 dict = {}
1694 for i in range(0, len(words), 2):
1695 key = words[i][1:]
1696 value = words[i+1]
1697 if value[:1] == '.':
1698 value = self._nametowidget(value)
1699 dict[key] = value
1700 return dict
1701 info = place_info
1702 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001703
Guido van Rossum37dcab11996-05-16 16:00:19 +00001704class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001705 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001706
Fredrik Lundh06d28152000-08-09 18:03:12 +00001707 Base class to use the methods grid_* in every widget."""
1708 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1709 def grid_configure(self, cnf={}, **kw):
1710 """Position a widget in the parent widget in a grid. Use as options:
1711 column=number - use cell identified with given column (starting with 0)
1712 columnspan=number - this widget will span several columns
1713 in=master - use master to contain this widget
1714 ipadx=amount - add internal padding in x direction
1715 ipady=amount - add internal padding in y direction
1716 padx=amount - add padding in x direction
1717 pady=amount - add padding in y direction
1718 row=number - use cell identified with given row (starting with 0)
1719 rowspan=number - this widget will span several rows
1720 sticky=NSEW - if cell is larger on which sides will this
1721 widget stick to the cell boundary
1722 """
1723 self.tk.call(
1724 ('grid', 'configure', self._w)
1725 + self._options(cnf, kw))
1726 grid = configure = config = grid_configure
1727 bbox = grid_bbox = Misc.grid_bbox
1728 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1729 def grid_forget(self):
1730 """Unmap this widget."""
1731 self.tk.call('grid', 'forget', self._w)
1732 forget = grid_forget
1733 def grid_remove(self):
1734 """Unmap this widget but remember the grid options."""
1735 self.tk.call('grid', 'remove', self._w)
1736 def grid_info(self):
1737 """Return information about the options
1738 for positioning this widget in a grid."""
1739 words = self.tk.splitlist(
1740 self.tk.call('grid', 'info', self._w))
1741 dict = {}
1742 for i in range(0, len(words), 2):
1743 key = words[i][1:]
1744 value = words[i+1]
1745 if value[:1] == '.':
1746 value = self._nametowidget(value)
1747 dict[key] = value
1748 return dict
1749 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001750 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001751 propagate = grid_propagate = Misc.grid_propagate
1752 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1753 size = grid_size = Misc.grid_size
1754 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001755
Guido van Rossum368e06b1997-11-07 20:38:49 +00001756class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001757 """Internal class."""
1758 def _setup(self, master, cnf):
1759 """Internal function. Sets up information about children."""
1760 if _support_default_root:
1761 global _default_root
1762 if not master:
1763 if not _default_root:
1764 _default_root = Tk()
1765 master = _default_root
1766 self.master = master
1767 self.tk = master.tk
1768 name = None
1769 if cnf.has_key('name'):
1770 name = cnf['name']
1771 del cnf['name']
1772 if not name:
1773 name = `id(self)`
1774 self._name = name
1775 if master._w=='.':
1776 self._w = '.' + name
1777 else:
1778 self._w = master._w + '.' + name
1779 self.children = {}
1780 if self.master.children.has_key(self._name):
1781 self.master.children[self._name].destroy()
1782 self.master.children[self._name] = self
1783 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1784 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1785 and appropriate options."""
1786 if kw:
1787 cnf = _cnfmerge((cnf, kw))
1788 self.widgetName = widgetName
1789 BaseWidget._setup(self, master, cnf)
1790 classes = []
1791 for k in cnf.keys():
1792 if type(k) is ClassType:
1793 classes.append((k, cnf[k]))
1794 del cnf[k]
1795 self.tk.call(
1796 (widgetName, self._w) + extra + self._options(cnf))
1797 for k, v in classes:
1798 k.configure(self, v)
1799 def destroy(self):
1800 """Destroy this and all descendants widgets."""
1801 for c in self.children.values(): c.destroy()
1802 if self.master.children.has_key(self._name):
1803 del self.master.children[self._name]
1804 self.tk.call('destroy', self._w)
1805 Misc.destroy(self)
1806 def _do(self, name, args=()):
1807 # XXX Obsolete -- better use self.tk.call directly!
1808 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001809
Guido van Rossum368e06b1997-11-07 20:38:49 +00001810class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001811 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001812
Fredrik Lundh06d28152000-08-09 18:03:12 +00001813 Base class for a widget which can be positioned with the geometry managers
1814 Pack, Place or Grid."""
1815 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001816
1817class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001818 """Toplevel widget, e.g. for dialogs."""
1819 def __init__(self, master=None, cnf={}, **kw):
1820 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001821
Fredrik Lundh06d28152000-08-09 18:03:12 +00001822 Valid resource names: background, bd, bg, borderwidth, class,
1823 colormap, container, cursor, height, highlightbackground,
1824 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1825 use, visual, width."""
1826 if kw:
1827 cnf = _cnfmerge((cnf, kw))
1828 extra = ()
1829 for wmkey in ['screen', 'class_', 'class', 'visual',
1830 'colormap']:
1831 if cnf.has_key(wmkey):
1832 val = cnf[wmkey]
1833 # TBD: a hack needed because some keys
1834 # are not valid as keyword arguments
1835 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1836 else: opt = '-'+wmkey
1837 extra = extra + (opt, val)
1838 del cnf[wmkey]
1839 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1840 root = self._root()
1841 self.iconname(root.iconname())
1842 self.title(root.title())
1843 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001844
1845class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001846 """Button widget."""
1847 def __init__(self, master=None, cnf={}, **kw):
1848 """Construct a button widget with the parent MASTER.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001849
1850 STANDARD OPTIONS
1851
1852 activebackground, activeforeground, anchor,
1853 background, bitmap, borderwidth, cursor,
1854 disabledforeground, font, foreground
1855 highlightbackground, highlightcolor,
1856 highlightthickness, image, justify,
1857 padx, pady, relief, repeatdelay,
1858 repeatinterval, takefocus, text,
1859 textvariable, underline, wraplength
1860
1861 WIDGET-SPECIFIC OPTIONS
1862
1863 command, compound, default, height,
1864 overrelief, state, width
1865 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001866 Widget.__init__(self, master, 'button', cnf, kw)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001867
Fredrik Lundh06d28152000-08-09 18:03:12 +00001868 def tkButtonEnter(self, *dummy):
1869 self.tk.call('tkButtonEnter', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001870
Fredrik Lundh06d28152000-08-09 18:03:12 +00001871 def tkButtonLeave(self, *dummy):
1872 self.tk.call('tkButtonLeave', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001873
Fredrik Lundh06d28152000-08-09 18:03:12 +00001874 def tkButtonDown(self, *dummy):
1875 self.tk.call('tkButtonDown', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001876
Fredrik Lundh06d28152000-08-09 18:03:12 +00001877 def tkButtonUp(self, *dummy):
1878 self.tk.call('tkButtonUp', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001879
Fredrik Lundh06d28152000-08-09 18:03:12 +00001880 def tkButtonInvoke(self, *dummy):
1881 self.tk.call('tkButtonInvoke', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001882
Fredrik Lundh06d28152000-08-09 18:03:12 +00001883 def flash(self):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001884 """Flash the button.
1885
1886 This is accomplished by redisplaying
1887 the button several times, alternating between active and
1888 normal colors. At the end of the flash the button is left
1889 in the same normal/active state as when the command was
1890 invoked. This command is ignored if the button's state is
1891 disabled.
1892 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001893 self.tk.call(self._w, 'flash')
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001894
Fredrik Lundh06d28152000-08-09 18:03:12 +00001895 def invoke(self):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001896 """Invoke the command associated with the button.
1897
1898 The return value is the return value from the command,
1899 or an empty string if there is no command associated with
1900 the button. This command is ignored if the button's state
1901 is disabled.
1902 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001903 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001904
1905# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001906# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001907def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001908 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001909def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001910 s = 'insert'
1911 for a in args:
1912 if a: s = s + (' ' + a)
1913 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001914def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001915 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001916def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001917 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001918def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001919 if y is None:
1920 return '@' + `x`
1921 else:
1922 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001923
1924class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001925 """Canvas widget to display graphical elements like lines or text."""
1926 def __init__(self, master=None, cnf={}, **kw):
1927 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001928
Fredrik Lundh06d28152000-08-09 18:03:12 +00001929 Valid resource names: background, bd, bg, borderwidth, closeenough,
1930 confine, cursor, height, highlightbackground, highlightcolor,
1931 highlightthickness, insertbackground, insertborderwidth,
1932 insertofftime, insertontime, insertwidth, offset, relief,
1933 scrollregion, selectbackground, selectborderwidth, selectforeground,
1934 state, takefocus, width, xscrollcommand, xscrollincrement,
1935 yscrollcommand, yscrollincrement."""
1936 Widget.__init__(self, master, 'canvas', cnf, kw)
1937 def addtag(self, *args):
1938 """Internal function."""
1939 self.tk.call((self._w, 'addtag') + args)
1940 def addtag_above(self, newtag, tagOrId):
1941 """Add tag NEWTAG to all items above TAGORID."""
1942 self.addtag(newtag, 'above', tagOrId)
1943 def addtag_all(self, newtag):
1944 """Add tag NEWTAG to all items."""
1945 self.addtag(newtag, 'all')
1946 def addtag_below(self, newtag, tagOrId):
1947 """Add tag NEWTAG to all items below TAGORID."""
1948 self.addtag(newtag, 'below', tagOrId)
1949 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1950 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1951 If several match take the top-most.
1952 All items closer than HALO are considered overlapping (all are
1953 closests). If START is specified the next below this tag is taken."""
1954 self.addtag(newtag, 'closest', x, y, halo, start)
1955 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1956 """Add tag NEWTAG to all items in the rectangle defined
1957 by X1,Y1,X2,Y2."""
1958 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1959 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1960 """Add tag NEWTAG to all items which overlap the rectangle
1961 defined by X1,Y1,X2,Y2."""
1962 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1963 def addtag_withtag(self, newtag, tagOrId):
1964 """Add tag NEWTAG to all items with TAGORID."""
1965 self.addtag(newtag, 'withtag', tagOrId)
1966 def bbox(self, *args):
1967 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1968 which encloses all items with tags specified as arguments."""
1969 return self._getints(
1970 self.tk.call((self._w, 'bbox') + args)) or None
1971 def tag_unbind(self, tagOrId, sequence, funcid=None):
1972 """Unbind for all items with TAGORID for event SEQUENCE the
1973 function identified with FUNCID."""
1974 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
1975 if funcid:
1976 self.deletecommand(funcid)
1977 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
1978 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001979
Fredrik Lundh06d28152000-08-09 18:03:12 +00001980 An additional boolean parameter ADD specifies whether FUNC will be
1981 called additionally to the other bound function or whether it will
1982 replace the previous function. See bind for the return value."""
1983 return self._bind((self._w, 'bind', tagOrId),
1984 sequence, func, add)
1985 def canvasx(self, screenx, gridspacing=None):
1986 """Return the canvas x coordinate of pixel position SCREENX rounded
1987 to nearest multiple of GRIDSPACING units."""
1988 return getdouble(self.tk.call(
1989 self._w, 'canvasx', screenx, gridspacing))
1990 def canvasy(self, screeny, gridspacing=None):
1991 """Return the canvas y coordinate of pixel position SCREENY rounded
1992 to nearest multiple of GRIDSPACING units."""
1993 return getdouble(self.tk.call(
1994 self._w, 'canvasy', screeny, gridspacing))
1995 def coords(self, *args):
1996 """Return a list of coordinates for the item given in ARGS."""
1997 # XXX Should use _flatten on args
1998 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00001999 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002000 self.tk.call((self._w, 'coords') + args)))
2001 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2002 """Internal function."""
2003 args = _flatten(args)
2004 cnf = args[-1]
2005 if type(cnf) in (DictionaryType, TupleType):
2006 args = args[:-1]
2007 else:
2008 cnf = {}
2009 return getint(apply(
2010 self.tk.call,
2011 (self._w, 'create', itemType)
2012 + args + self._options(cnf, kw)))
2013 def create_arc(self, *args, **kw):
2014 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2015 return self._create('arc', args, kw)
2016 def create_bitmap(self, *args, **kw):
2017 """Create bitmap with coordinates x1,y1."""
2018 return self._create('bitmap', args, kw)
2019 def create_image(self, *args, **kw):
2020 """Create image item with coordinates x1,y1."""
2021 return self._create('image', args, kw)
2022 def create_line(self, *args, **kw):
2023 """Create line with coordinates x1,y1,...,xn,yn."""
2024 return self._create('line', args, kw)
2025 def create_oval(self, *args, **kw):
2026 """Create oval with coordinates x1,y1,x2,y2."""
2027 return self._create('oval', args, kw)
2028 def create_polygon(self, *args, **kw):
2029 """Create polygon with coordinates x1,y1,...,xn,yn."""
2030 return self._create('polygon', args, kw)
2031 def create_rectangle(self, *args, **kw):
2032 """Create rectangle with coordinates x1,y1,x2,y2."""
2033 return self._create('rectangle', args, kw)
2034 def create_text(self, *args, **kw):
2035 """Create text with coordinates x1,y1."""
2036 return self._create('text', args, kw)
2037 def create_window(self, *args, **kw):
2038 """Create window with coordinates x1,y1,x2,y2."""
2039 return self._create('window', args, kw)
2040 def dchars(self, *args):
2041 """Delete characters of text items identified by tag or id in ARGS (possibly
2042 several times) from FIRST to LAST character (including)."""
2043 self.tk.call((self._w, 'dchars') + args)
2044 def delete(self, *args):
2045 """Delete items identified by all tag or ids contained in ARGS."""
2046 self.tk.call((self._w, 'delete') + args)
2047 def dtag(self, *args):
2048 """Delete tag or id given as last arguments in ARGS from items
2049 identified by first argument in ARGS."""
2050 self.tk.call((self._w, 'dtag') + args)
2051 def find(self, *args):
2052 """Internal function."""
2053 return self._getints(
2054 self.tk.call((self._w, 'find') + args)) or ()
2055 def find_above(self, tagOrId):
2056 """Return items above TAGORID."""
2057 return self.find('above', tagOrId)
2058 def find_all(self):
2059 """Return all items."""
2060 return self.find('all')
2061 def find_below(self, tagOrId):
2062 """Return all items below TAGORID."""
2063 return self.find('below', tagOrId)
2064 def find_closest(self, x, y, halo=None, start=None):
2065 """Return item which is closest to pixel at X, Y.
2066 If several match take the top-most.
2067 All items closer than HALO are considered overlapping (all are
2068 closests). If START is specified the next below this tag is taken."""
2069 return self.find('closest', x, y, halo, start)
2070 def find_enclosed(self, x1, y1, x2, y2):
2071 """Return all items in rectangle defined
2072 by X1,Y1,X2,Y2."""
2073 return self.find('enclosed', x1, y1, x2, y2)
2074 def find_overlapping(self, x1, y1, x2, y2):
2075 """Return all items which overlap the rectangle
2076 defined by X1,Y1,X2,Y2."""
2077 return self.find('overlapping', x1, y1, x2, y2)
2078 def find_withtag(self, tagOrId):
2079 """Return all items with TAGORID."""
2080 return self.find('withtag', tagOrId)
2081 def focus(self, *args):
2082 """Set focus to the first item specified in ARGS."""
2083 return self.tk.call((self._w, 'focus') + args)
2084 def gettags(self, *args):
2085 """Return tags associated with the first item specified in ARGS."""
2086 return self.tk.splitlist(
2087 self.tk.call((self._w, 'gettags') + args))
2088 def icursor(self, *args):
2089 """Set cursor at position POS in the item identified by TAGORID.
2090 In ARGS TAGORID must be first."""
2091 self.tk.call((self._w, 'icursor') + args)
2092 def index(self, *args):
2093 """Return position of cursor as integer in item specified in ARGS."""
2094 return getint(self.tk.call((self._w, 'index') + args))
2095 def insert(self, *args):
2096 """Insert TEXT in item TAGORID at position POS. ARGS must
2097 be TAGORID POS TEXT."""
2098 self.tk.call((self._w, 'insert') + args)
2099 def itemcget(self, tagOrId, option):
2100 """Return the resource value for an OPTION for item TAGORID."""
2101 return self.tk.call(
2102 (self._w, 'itemcget') + (tagOrId, '-'+option))
2103 def itemconfigure(self, tagOrId, cnf=None, **kw):
2104 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002105
Fredrik Lundh06d28152000-08-09 18:03:12 +00002106 The values for resources are specified as keyword
2107 arguments. To get an overview about
2108 the allowed keyword arguments call the method without arguments.
2109 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002110 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002111 itemconfig = itemconfigure
2112 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2113 # so the preferred name for them is tag_lower, tag_raise
2114 # (similar to tag_bind, and similar to the Text widget);
2115 # unfortunately can't delete the old ones yet (maybe in 1.6)
2116 def tag_lower(self, *args):
2117 """Lower an item TAGORID given in ARGS
2118 (optional below another item)."""
2119 self.tk.call((self._w, 'lower') + args)
2120 lower = tag_lower
2121 def move(self, *args):
2122 """Move an item TAGORID given in ARGS."""
2123 self.tk.call((self._w, 'move') + args)
2124 def postscript(self, cnf={}, **kw):
2125 """Print the contents of the canvas to a postscript
2126 file. Valid options: colormap, colormode, file, fontmap,
2127 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2128 rotate, witdh, x, y."""
2129 return self.tk.call((self._w, 'postscript') +
2130 self._options(cnf, kw))
2131 def tag_raise(self, *args):
2132 """Raise an item TAGORID given in ARGS
2133 (optional above another item)."""
2134 self.tk.call((self._w, 'raise') + args)
2135 lift = tkraise = tag_raise
2136 def scale(self, *args):
2137 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2138 self.tk.call((self._w, 'scale') + args)
2139 def scan_mark(self, x, y):
2140 """Remember the current X, Y coordinates."""
2141 self.tk.call(self._w, 'scan', 'mark', x, y)
2142 def scan_dragto(self, x, y):
2143 """Adjust the view of the canvas to 10 times the
2144 difference between X and Y and the coordinates given in
2145 scan_mark."""
2146 self.tk.call(self._w, 'scan', 'dragto', x, y)
2147 def select_adjust(self, tagOrId, index):
2148 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2149 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2150 def select_clear(self):
2151 """Clear the selection if it is in this widget."""
2152 self.tk.call(self._w, 'select', 'clear')
2153 def select_from(self, tagOrId, index):
2154 """Set the fixed end of a selection in item TAGORID to INDEX."""
2155 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2156 def select_item(self):
2157 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002158 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002159 def select_to(self, tagOrId, index):
2160 """Set the variable end of a selection in item TAGORID to INDEX."""
2161 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2162 def type(self, tagOrId):
2163 """Return the type of the item TAGORID."""
2164 return self.tk.call(self._w, 'type', tagOrId) or None
2165 def xview(self, *args):
2166 """Query and change horizontal position of the view."""
2167 if not args:
2168 return self._getdoubles(self.tk.call(self._w, 'xview'))
2169 self.tk.call((self._w, 'xview') + args)
2170 def xview_moveto(self, fraction):
2171 """Adjusts the view in the window so that FRACTION of the
2172 total width of the canvas is off-screen to the left."""
2173 self.tk.call(self._w, 'xview', 'moveto', fraction)
2174 def xview_scroll(self, number, what):
2175 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2176 self.tk.call(self._w, 'xview', 'scroll', number, what)
2177 def yview(self, *args):
2178 """Query and change vertical position of the view."""
2179 if not args:
2180 return self._getdoubles(self.tk.call(self._w, 'yview'))
2181 self.tk.call((self._w, 'yview') + args)
2182 def yview_moveto(self, fraction):
2183 """Adjusts the view in the window so that FRACTION of the
2184 total height of the canvas is off-screen to the top."""
2185 self.tk.call(self._w, 'yview', 'moveto', fraction)
2186 def yview_scroll(self, number, what):
2187 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2188 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002189
2190class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002191 """Checkbutton widget which is either in on- or off-state."""
2192 def __init__(self, master=None, cnf={}, **kw):
2193 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002194
Fredrik Lundh06d28152000-08-09 18:03:12 +00002195 Valid resource names: activebackground, activeforeground, anchor,
2196 background, bd, bg, bitmap, borderwidth, command, cursor,
2197 disabledforeground, fg, font, foreground, height,
2198 highlightbackground, highlightcolor, highlightthickness, image,
2199 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2200 selectcolor, selectimage, state, takefocus, text, textvariable,
2201 underline, variable, width, wraplength."""
2202 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2203 def deselect(self):
2204 """Put the button in off-state."""
2205 self.tk.call(self._w, 'deselect')
2206 def flash(self):
2207 """Flash the button."""
2208 self.tk.call(self._w, 'flash')
2209 def invoke(self):
2210 """Toggle the button and invoke a command if given as resource."""
2211 return self.tk.call(self._w, 'invoke')
2212 def select(self):
2213 """Put the button in on-state."""
2214 self.tk.call(self._w, 'select')
2215 def toggle(self):
2216 """Toggle the button."""
2217 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002218
2219class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002220 """Entry widget which allows to display simple text."""
2221 def __init__(self, master=None, cnf={}, **kw):
2222 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002223
Fredrik Lundh06d28152000-08-09 18:03:12 +00002224 Valid resource names: background, bd, bg, borderwidth, cursor,
2225 exportselection, fg, font, foreground, highlightbackground,
2226 highlightcolor, highlightthickness, insertbackground,
2227 insertborderwidth, insertofftime, insertontime, insertwidth,
2228 invalidcommand, invcmd, justify, relief, selectbackground,
2229 selectborderwidth, selectforeground, show, state, takefocus,
2230 textvariable, validate, validatecommand, vcmd, width,
2231 xscrollcommand."""
2232 Widget.__init__(self, master, 'entry', cnf, kw)
2233 def delete(self, first, last=None):
2234 """Delete text from FIRST to LAST (not included)."""
2235 self.tk.call(self._w, 'delete', first, last)
2236 def get(self):
2237 """Return the text."""
2238 return self.tk.call(self._w, 'get')
2239 def icursor(self, index):
2240 """Insert cursor at INDEX."""
2241 self.tk.call(self._w, 'icursor', index)
2242 def index(self, index):
2243 """Return position of cursor."""
2244 return getint(self.tk.call(
2245 self._w, 'index', index))
2246 def insert(self, index, string):
2247 """Insert STRING at INDEX."""
2248 self.tk.call(self._w, 'insert', index, string)
2249 def scan_mark(self, x):
2250 """Remember the current X, Y coordinates."""
2251 self.tk.call(self._w, 'scan', 'mark', x)
2252 def scan_dragto(self, x):
2253 """Adjust the view of the canvas to 10 times the
2254 difference between X and Y and the coordinates given in
2255 scan_mark."""
2256 self.tk.call(self._w, 'scan', 'dragto', x)
2257 def selection_adjust(self, index):
2258 """Adjust the end of the selection near the cursor to INDEX."""
2259 self.tk.call(self._w, 'selection', 'adjust', index)
2260 select_adjust = selection_adjust
2261 def selection_clear(self):
2262 """Clear the selection if it is in this widget."""
2263 self.tk.call(self._w, 'selection', 'clear')
2264 select_clear = selection_clear
2265 def selection_from(self, index):
2266 """Set the fixed end of a selection to INDEX."""
2267 self.tk.call(self._w, 'selection', 'from', index)
2268 select_from = selection_from
2269 def selection_present(self):
2270 """Return whether the widget has the selection."""
2271 return self.tk.getboolean(
2272 self.tk.call(self._w, 'selection', 'present'))
2273 select_present = selection_present
2274 def selection_range(self, start, end):
2275 """Set the selection from START to END (not included)."""
2276 self.tk.call(self._w, 'selection', 'range', start, end)
2277 select_range = selection_range
2278 def selection_to(self, index):
2279 """Set the variable end of a selection to INDEX."""
2280 self.tk.call(self._w, 'selection', 'to', index)
2281 select_to = selection_to
2282 def xview(self, index):
2283 """Query and change horizontal position of the view."""
2284 self.tk.call(self._w, 'xview', index)
2285 def xview_moveto(self, fraction):
2286 """Adjust the view in the window so that FRACTION of the
2287 total width of the entry is off-screen to the left."""
2288 self.tk.call(self._w, 'xview', 'moveto', fraction)
2289 def xview_scroll(self, number, what):
2290 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2291 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002292
2293class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002294 """Frame widget which may contain other widgets and can have a 3D border."""
2295 def __init__(self, master=None, cnf={}, **kw):
2296 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002297
Fredrik Lundh06d28152000-08-09 18:03:12 +00002298 Valid resource names: background, bd, bg, borderwidth, class,
2299 colormap, container, cursor, height, highlightbackground,
2300 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2301 cnf = _cnfmerge((cnf, kw))
2302 extra = ()
2303 if cnf.has_key('class_'):
2304 extra = ('-class', cnf['class_'])
2305 del cnf['class_']
2306 elif cnf.has_key('class'):
2307 extra = ('-class', cnf['class'])
2308 del cnf['class']
2309 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002310
2311class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002312 """Label widget which can display text and bitmaps."""
2313 def __init__(self, master=None, cnf={}, **kw):
2314 """Construct a label widget with the parent MASTER.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002315
2316 STANDARD OPTIONS
2317
2318 activebackground, activeforeground, anchor,
2319 background, bitmap, borderwidth, cursor,
2320 disabledforeground, font, foreground,
2321 highlightbackground, highlightcolor,
2322 highlightthickness, image, justify,
2323 padx, pady, relief, takefocus, text,
2324 textvariable, underline, wraplength
2325
2326 WIDGET-SPECIFIC OPTIONS
2327
2328 height, state, width
2329
2330 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002331 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002332
Guido van Rossum18468821994-06-20 07:49:28 +00002333class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002334 """Listbox widget which can display a list of strings."""
2335 def __init__(self, master=None, cnf={}, **kw):
2336 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002337
Fredrik Lundh06d28152000-08-09 18:03:12 +00002338 Valid resource names: background, bd, bg, borderwidth, cursor,
2339 exportselection, fg, font, foreground, height, highlightbackground,
2340 highlightcolor, highlightthickness, relief, selectbackground,
2341 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2342 width, xscrollcommand, yscrollcommand, listvariable."""
2343 Widget.__init__(self, master, 'listbox', cnf, kw)
2344 def activate(self, index):
2345 """Activate item identified by INDEX."""
2346 self.tk.call(self._w, 'activate', index)
2347 def bbox(self, *args):
2348 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2349 which encloses the item identified by index in ARGS."""
2350 return self._getints(
2351 self.tk.call((self._w, 'bbox') + args)) or None
2352 def curselection(self):
2353 """Return list of indices of currently selected item."""
2354 # XXX Ought to apply self._getints()...
2355 return self.tk.splitlist(self.tk.call(
2356 self._w, 'curselection'))
2357 def delete(self, first, last=None):
2358 """Delete items from FIRST to LAST (not included)."""
2359 self.tk.call(self._w, 'delete', first, last)
2360 def get(self, first, last=None):
2361 """Get list of items from FIRST to LAST (not included)."""
2362 if last:
2363 return self.tk.splitlist(self.tk.call(
2364 self._w, 'get', first, last))
2365 else:
2366 return self.tk.call(self._w, 'get', first)
2367 def index(self, index):
2368 """Return index of item identified with INDEX."""
2369 i = self.tk.call(self._w, 'index', index)
2370 if i == 'none': return None
2371 return getint(i)
2372 def insert(self, index, *elements):
2373 """Insert ELEMENTS at INDEX."""
2374 self.tk.call((self._w, 'insert', index) + elements)
2375 def nearest(self, y):
2376 """Get index of item which is nearest to y coordinate Y."""
2377 return getint(self.tk.call(
2378 self._w, 'nearest', y))
2379 def scan_mark(self, x, y):
2380 """Remember the current X, Y coordinates."""
2381 self.tk.call(self._w, 'scan', 'mark', x, y)
2382 def scan_dragto(self, x, y):
2383 """Adjust the view of the listbox to 10 times the
2384 difference between X and Y and the coordinates given in
2385 scan_mark."""
2386 self.tk.call(self._w, 'scan', 'dragto', x, y)
2387 def see(self, index):
2388 """Scroll such that INDEX is visible."""
2389 self.tk.call(self._w, 'see', index)
2390 def selection_anchor(self, index):
2391 """Set the fixed end oft the selection to INDEX."""
2392 self.tk.call(self._w, 'selection', 'anchor', index)
2393 select_anchor = selection_anchor
2394 def selection_clear(self, first, last=None):
2395 """Clear the selection from FIRST to LAST (not included)."""
2396 self.tk.call(self._w,
2397 'selection', 'clear', first, last)
2398 select_clear = selection_clear
2399 def selection_includes(self, index):
2400 """Return 1 if INDEX is part of the selection."""
2401 return self.tk.getboolean(self.tk.call(
2402 self._w, 'selection', 'includes', index))
2403 select_includes = selection_includes
2404 def selection_set(self, first, last=None):
2405 """Set the selection from FIRST to LAST (not included) without
2406 changing the currently selected elements."""
2407 self.tk.call(self._w, 'selection', 'set', first, last)
2408 select_set = selection_set
2409 def size(self):
2410 """Return the number of elements in the listbox."""
2411 return getint(self.tk.call(self._w, 'size'))
2412 def xview(self, *what):
2413 """Query and change horizontal position of the view."""
2414 if not what:
2415 return self._getdoubles(self.tk.call(self._w, 'xview'))
2416 self.tk.call((self._w, 'xview') + what)
2417 def xview_moveto(self, fraction):
2418 """Adjust the view in the window so that FRACTION of the
2419 total width of the entry is off-screen to the left."""
2420 self.tk.call(self._w, 'xview', 'moveto', fraction)
2421 def xview_scroll(self, number, what):
2422 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2423 self.tk.call(self._w, 'xview', 'scroll', number, what)
2424 def yview(self, *what):
2425 """Query and change vertical position of the view."""
2426 if not what:
2427 return self._getdoubles(self.tk.call(self._w, 'yview'))
2428 self.tk.call((self._w, 'yview') + what)
2429 def yview_moveto(self, fraction):
2430 """Adjust the view in the window so that FRACTION of the
2431 total width of the entry is off-screen to the top."""
2432 self.tk.call(self._w, 'yview', 'moveto', fraction)
2433 def yview_scroll(self, number, what):
2434 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2435 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002436 def itemcget(self, index, option):
2437 """Return the resource value for an ITEM and an OPTION."""
2438 return self.tk.call(
2439 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002440 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002441 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002442
2443 The values for resources are specified as keyword arguments.
2444 To get an overview about the allowed keyword arguments
2445 call the method without arguments.
2446 Valid resource names: background, bg, foreground, fg,
2447 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002448 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002449 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002450
2451class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002452 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2453 def __init__(self, master=None, cnf={}, **kw):
2454 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002455
Fredrik Lundh06d28152000-08-09 18:03:12 +00002456 Valid resource names: activebackground, activeborderwidth,
2457 activeforeground, background, bd, bg, borderwidth, cursor,
2458 disabledforeground, fg, font, foreground, postcommand, relief,
2459 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2460 Widget.__init__(self, master, 'menu', cnf, kw)
2461 def tk_bindForTraversal(self):
2462 pass # obsolete since Tk 4.0
2463 def tk_mbPost(self):
2464 self.tk.call('tk_mbPost', self._w)
2465 def tk_mbUnpost(self):
2466 self.tk.call('tk_mbUnpost')
2467 def tk_traverseToMenu(self, char):
2468 self.tk.call('tk_traverseToMenu', self._w, char)
2469 def tk_traverseWithinMenu(self, char):
2470 self.tk.call('tk_traverseWithinMenu', self._w, char)
2471 def tk_getMenuButtons(self):
2472 return self.tk.call('tk_getMenuButtons', self._w)
2473 def tk_nextMenu(self, count):
2474 self.tk.call('tk_nextMenu', count)
2475 def tk_nextMenuEntry(self, count):
2476 self.tk.call('tk_nextMenuEntry', count)
2477 def tk_invokeMenu(self):
2478 self.tk.call('tk_invokeMenu', self._w)
2479 def tk_firstMenu(self):
2480 self.tk.call('tk_firstMenu', self._w)
2481 def tk_mbButtonDown(self):
2482 self.tk.call('tk_mbButtonDown', self._w)
2483 def tk_popup(self, x, y, entry=""):
2484 """Post the menu at position X,Y with entry ENTRY."""
2485 self.tk.call('tk_popup', self._w, x, y, entry)
2486 def activate(self, index):
2487 """Activate entry at INDEX."""
2488 self.tk.call(self._w, 'activate', index)
2489 def add(self, itemType, cnf={}, **kw):
2490 """Internal function."""
2491 self.tk.call((self._w, 'add', itemType) +
2492 self._options(cnf, kw))
2493 def add_cascade(self, cnf={}, **kw):
2494 """Add hierarchical menu item."""
2495 self.add('cascade', cnf or kw)
2496 def add_checkbutton(self, cnf={}, **kw):
2497 """Add checkbutton menu item."""
2498 self.add('checkbutton', cnf or kw)
2499 def add_command(self, cnf={}, **kw):
2500 """Add command menu item."""
2501 self.add('command', cnf or kw)
2502 def add_radiobutton(self, cnf={}, **kw):
2503 """Addd radio menu item."""
2504 self.add('radiobutton', cnf or kw)
2505 def add_separator(self, cnf={}, **kw):
2506 """Add separator."""
2507 self.add('separator', cnf or kw)
2508 def insert(self, index, itemType, cnf={}, **kw):
2509 """Internal function."""
2510 self.tk.call((self._w, 'insert', index, itemType) +
2511 self._options(cnf, kw))
2512 def insert_cascade(self, index, cnf={}, **kw):
2513 """Add hierarchical menu item at INDEX."""
2514 self.insert(index, 'cascade', cnf or kw)
2515 def insert_checkbutton(self, index, cnf={}, **kw):
2516 """Add checkbutton menu item at INDEX."""
2517 self.insert(index, 'checkbutton', cnf or kw)
2518 def insert_command(self, index, cnf={}, **kw):
2519 """Add command menu item at INDEX."""
2520 self.insert(index, 'command', cnf or kw)
2521 def insert_radiobutton(self, index, cnf={}, **kw):
2522 """Addd radio menu item at INDEX."""
2523 self.insert(index, 'radiobutton', cnf or kw)
2524 def insert_separator(self, index, cnf={}, **kw):
2525 """Add separator at INDEX."""
2526 self.insert(index, 'separator', cnf or kw)
2527 def delete(self, index1, index2=None):
2528 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2529 self.tk.call(self._w, 'delete', index1, index2)
2530 def entrycget(self, index, option):
2531 """Return the resource value of an menu item for OPTION at INDEX."""
2532 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2533 def entryconfigure(self, index, cnf=None, **kw):
2534 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002535 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002536 entryconfig = entryconfigure
2537 def index(self, index):
2538 """Return the index of a menu item identified by INDEX."""
2539 i = self.tk.call(self._w, 'index', index)
2540 if i == 'none': return None
2541 return getint(i)
2542 def invoke(self, index):
2543 """Invoke a menu item identified by INDEX and execute
2544 the associated command."""
2545 return self.tk.call(self._w, 'invoke', index)
2546 def post(self, x, y):
2547 """Display a menu at position X,Y."""
2548 self.tk.call(self._w, 'post', x, y)
2549 def type(self, index):
2550 """Return the type of the menu item at INDEX."""
2551 return self.tk.call(self._w, 'type', index)
2552 def unpost(self):
2553 """Unmap a menu."""
2554 self.tk.call(self._w, 'unpost')
2555 def yposition(self, index):
2556 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2557 return getint(self.tk.call(
2558 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002559
2560class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002561 """Menubutton widget, obsolete since Tk8.0."""
2562 def __init__(self, master=None, cnf={}, **kw):
2563 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002564
2565class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002566 """Message widget to display multiline text. Obsolete since Label does it too."""
2567 def __init__(self, master=None, cnf={}, **kw):
2568 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002569
2570class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002571 """Radiobutton widget which shows only one of several buttons in on-state."""
2572 def __init__(self, master=None, cnf={}, **kw):
2573 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002574
Fredrik Lundh06d28152000-08-09 18:03:12 +00002575 Valid resource names: activebackground, activeforeground, anchor,
2576 background, bd, bg, bitmap, borderwidth, command, cursor,
2577 disabledforeground, fg, font, foreground, height,
2578 highlightbackground, highlightcolor, highlightthickness, image,
2579 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2580 state, takefocus, text, textvariable, underline, value, variable,
2581 width, wraplength."""
2582 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2583 def deselect(self):
2584 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002585
Fredrik Lundh06d28152000-08-09 18:03:12 +00002586 self.tk.call(self._w, 'deselect')
2587 def flash(self):
2588 """Flash the button."""
2589 self.tk.call(self._w, 'flash')
2590 def invoke(self):
2591 """Toggle the button and invoke a command if given as resource."""
2592 return self.tk.call(self._w, 'invoke')
2593 def select(self):
2594 """Put the button in on-state."""
2595 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002596
2597class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002598 """Scale widget which can display a numerical scale."""
2599 def __init__(self, master=None, cnf={}, **kw):
2600 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002601
Fredrik Lundh06d28152000-08-09 18:03:12 +00002602 Valid resource names: activebackground, background, bigincrement, bd,
2603 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2604 highlightbackground, highlightcolor, highlightthickness, label,
2605 length, orient, relief, repeatdelay, repeatinterval, resolution,
2606 showvalue, sliderlength, sliderrelief, state, takefocus,
2607 tickinterval, to, troughcolor, variable, width."""
2608 Widget.__init__(self, master, 'scale', cnf, kw)
2609 def get(self):
2610 """Get the current value as integer or float."""
2611 value = self.tk.call(self._w, 'get')
2612 try:
2613 return getint(value)
2614 except ValueError:
2615 return getdouble(value)
2616 def set(self, value):
2617 """Set the value to VALUE."""
2618 self.tk.call(self._w, 'set', value)
2619 def coords(self, value=None):
2620 """Return a tuple (X,Y) of the point along the centerline of the
2621 trough that corresponds to VALUE or the current value if None is
2622 given."""
2623
2624 return self._getints(self.tk.call(self._w, 'coords', value))
2625 def identify(self, x, y):
2626 """Return where the point X,Y lies. Valid return values are "slider",
2627 "though1" and "though2"."""
2628 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002629
2630class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002631 """Scrollbar widget which displays a slider at a certain position."""
2632 def __init__(self, master=None, cnf={}, **kw):
2633 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002634
Fredrik Lundh06d28152000-08-09 18:03:12 +00002635 Valid resource names: activebackground, activerelief,
2636 background, bd, bg, borderwidth, command, cursor,
2637 elementborderwidth, highlightbackground,
2638 highlightcolor, highlightthickness, jump, orient,
2639 relief, repeatdelay, repeatinterval, takefocus,
2640 troughcolor, width."""
2641 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2642 def activate(self, index):
2643 """Display the element at INDEX with activebackground and activerelief.
2644 INDEX can be "arrow1","slider" or "arrow2"."""
2645 self.tk.call(self._w, 'activate', index)
2646 def delta(self, deltax, deltay):
2647 """Return the fractional change of the scrollbar setting if it
2648 would be moved by DELTAX or DELTAY pixels."""
2649 return getdouble(
2650 self.tk.call(self._w, 'delta', deltax, deltay))
2651 def fraction(self, x, y):
2652 """Return the fractional value which corresponds to a slider
2653 position of X,Y."""
2654 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2655 def identify(self, x, y):
2656 """Return the element under position X,Y as one of
2657 "arrow1","slider","arrow2" or ""."""
2658 return self.tk.call(self._w, 'identify', x, y)
2659 def get(self):
2660 """Return the current fractional values (upper and lower end)
2661 of the slider position."""
2662 return self._getdoubles(self.tk.call(self._w, 'get'))
2663 def set(self, *args):
2664 """Set the fractional values of the slider position (upper and
2665 lower ends as value between 0 and 1)."""
2666 self.tk.call((self._w, 'set') + args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002667
2668
2669
Guido van Rossum18468821994-06-20 07:49:28 +00002670class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002671 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002672 def __init__(self, master=None, cnf={}, **kw):
2673 """Construct a text widget with the parent MASTER.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002674
2675 STANDARD OPTIONS
2676
2677 background, borderwidth, cursor,
2678 exportselection, font, foreground,
2679 highlightbackground, highlightcolor,
2680 highlightthickness, insertbackground,
2681 insertborderwidth, insertofftime,
2682 insertontime, insertwidth, padx, pady,
2683 relief, selectbackground,
2684 selectborderwidth, selectforeground,
2685 setgrid, takefocus,
2686 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002687
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002688 WIDGET-SPECIFIC OPTIONS
2689
2690 autoseparators, height, maxundo,
2691 spacing1, spacing2, spacing3,
2692 state, tabs, undo, width, wrap,
2693
2694 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002695 Widget.__init__(self, master, 'text', cnf, kw)
2696 def bbox(self, *args):
2697 """Return a tuple of (x,y,width,height) which gives the bounding
2698 box of the visible part of the character at the index in ARGS."""
2699 return self._getints(
2700 self.tk.call((self._w, 'bbox') + args)) or None
2701 def tk_textSelectTo(self, index):
2702 self.tk.call('tk_textSelectTo', self._w, index)
2703 def tk_textBackspace(self):
2704 self.tk.call('tk_textBackspace', self._w)
2705 def tk_textIndexCloser(self, a, b, c):
2706 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2707 def tk_textResetAnchor(self, index):
2708 self.tk.call('tk_textResetAnchor', self._w, index)
2709 def compare(self, index1, op, index2):
2710 """Return whether between index INDEX1 and index INDEX2 the
2711 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2712 return self.tk.getboolean(self.tk.call(
2713 self._w, 'compare', index1, op, index2))
2714 def debug(self, boolean=None):
2715 """Turn on the internal consistency checks of the B-Tree inside the text
2716 widget according to BOOLEAN."""
2717 return self.tk.getboolean(self.tk.call(
2718 self._w, 'debug', boolean))
2719 def delete(self, index1, index2=None):
2720 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2721 self.tk.call(self._w, 'delete', index1, index2)
2722 def dlineinfo(self, index):
2723 """Return tuple (x,y,width,height,baseline) giving the bounding box
2724 and baseline position of the visible part of the line containing
2725 the character at INDEX."""
2726 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002727 def dump(self, index1, index2=None, command=None, **kw):
2728 """Return the contents of the widget between index1 and index2.
2729
2730 The type of contents returned in filtered based on the keyword
2731 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2732 given and true, then the corresponding items are returned. The result
2733 is a list of triples of the form (key, value, index). If none of the
2734 keywords are true then 'all' is used by default.
2735
2736 If the 'command' argument is given, it is called once for each element
2737 of the list of triples, with the values of each triple serving as the
2738 arguments to the function. In this case the list is not returned."""
2739 args = []
2740 func_name = None
2741 result = None
2742 if not command:
2743 # Never call the dump command without the -command flag, since the
2744 # output could involve Tcl quoting and would be a pain to parse
2745 # right. Instead just set the command to build a list of triples
2746 # as if we had done the parsing.
2747 result = []
2748 def append_triple(key, value, index, result=result):
2749 result.append((key, value, index))
2750 command = append_triple
2751 try:
2752 if not isinstance(command, str):
2753 func_name = command = self._register(command)
2754 args += ["-command", command]
2755 for key in kw:
2756 if kw[key]: args.append("-" + key)
2757 args.append(index1)
2758 if index2:
2759 args.append(index2)
2760 self.tk.call(self._w, "dump", *args)
2761 return result
2762 finally:
2763 if func_name:
2764 self.deletecommand(func_name)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002765
2766 ## new in tk8.4
2767 def edit(self, *args):
2768 """Internal method
2769
2770 This method controls the undo mechanism and
2771 the modified flag. The exact behavior of the
2772 command depends on the option argument that
2773 follows the edit argument. The following forms
2774 of the command are currently supported:
2775
2776 edit_modified, edit_redo, edit_reset, edit_separator
2777 and edit_undo
2778
2779 """
2780 return self._getints(
2781 self.tk.call((self._w, 'edit') + args)) or ()
2782
2783 def edit_modified(self, arg=None):
2784 """Get or Set the modified flag
2785
2786 If arg is not specified, returns the modified
2787 flag of the widget. The insert, delete, edit undo and
2788 edit redo commands or the user can set or clear the
2789 modified flag. If boolean is specified, sets the
2790 modified flag of the widget to arg.
2791 """
2792 return self.edit("modified", arg)
2793
2794 def edit_redo(self):
2795 """Redo the last undone edit
2796
2797 When the undo option is true, reapplies the last
2798 undone edits provided no other edits were done since
2799 then. Generates an error when the redo stack is empty.
2800 Does nothing when the undo option is false.
2801 """
2802 return self.edit("redo")
2803
2804 def edit_reset(self):
2805 """Clears the undo and redo stacks
2806 """
2807 return self.edit("reset")
2808
2809 def edit_separator(self):
2810 """Inserts a separator (boundary) on the undo stack.
2811
2812 Does nothing when the undo option is false
2813 """
2814 return self.edit("separator")
2815
2816 def edit_undo(self):
2817 """Undoes the last edit action
2818
2819 If the undo option is true. An edit action is defined
2820 as all the insert and delete commands that are recorded
2821 on the undo stack in between two separators. Generates
2822 an error when the undo stack is empty. Does nothing
2823 when the undo option is false
2824 """
2825 return self.edit("undo")
2826
Fredrik Lundh06d28152000-08-09 18:03:12 +00002827 def get(self, index1, index2=None):
2828 """Return the text from INDEX1 to INDEX2 (not included)."""
2829 return self.tk.call(self._w, 'get', index1, index2)
2830 # (Image commands are new in 8.0)
2831 def image_cget(self, index, option):
2832 """Return the value of OPTION of an embedded image at INDEX."""
2833 if option[:1] != "-":
2834 option = "-" + option
2835 if option[-1:] == "_":
2836 option = option[:-1]
2837 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002838 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002839 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002840 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002841 def image_create(self, index, cnf={}, **kw):
2842 """Create an embedded image at INDEX."""
2843 return apply(self.tk.call,
2844 (self._w, "image", "create", index)
2845 + self._options(cnf, kw))
2846 def image_names(self):
2847 """Return all names of embedded images in this widget."""
2848 return self.tk.call(self._w, "image", "names")
2849 def index(self, index):
2850 """Return the index in the form line.char for INDEX."""
2851 return self.tk.call(self._w, 'index', index)
2852 def insert(self, index, chars, *args):
2853 """Insert CHARS before the characters at INDEX. An additional
2854 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2855 self.tk.call((self._w, 'insert', index, chars) + args)
2856 def mark_gravity(self, markName, direction=None):
2857 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2858 Return the current value if None is given for DIRECTION."""
2859 return self.tk.call(
2860 (self._w, 'mark', 'gravity', markName, direction))
2861 def mark_names(self):
2862 """Return all mark names."""
2863 return self.tk.splitlist(self.tk.call(
2864 self._w, 'mark', 'names'))
2865 def mark_set(self, markName, index):
2866 """Set mark MARKNAME before the character at INDEX."""
2867 self.tk.call(self._w, 'mark', 'set', markName, index)
2868 def mark_unset(self, *markNames):
2869 """Delete all marks in MARKNAMES."""
2870 self.tk.call((self._w, 'mark', 'unset') + markNames)
2871 def mark_next(self, index):
2872 """Return the name of the next mark after INDEX."""
2873 return self.tk.call(self._w, 'mark', 'next', index) or None
2874 def mark_previous(self, index):
2875 """Return the name of the previous mark before INDEX."""
2876 return self.tk.call(self._w, 'mark', 'previous', index) or None
2877 def scan_mark(self, x, y):
2878 """Remember the current X, Y coordinates."""
2879 self.tk.call(self._w, 'scan', 'mark', x, y)
2880 def scan_dragto(self, x, y):
2881 """Adjust the view of the text to 10 times the
2882 difference between X and Y and the coordinates given in
2883 scan_mark."""
2884 self.tk.call(self._w, 'scan', 'dragto', x, y)
2885 def search(self, pattern, index, stopindex=None,
2886 forwards=None, backwards=None, exact=None,
2887 regexp=None, nocase=None, count=None):
2888 """Search PATTERN beginning from INDEX until STOPINDEX.
2889 Return the index of the first character of a match or an empty string."""
2890 args = [self._w, 'search']
2891 if forwards: args.append('-forwards')
2892 if backwards: args.append('-backwards')
2893 if exact: args.append('-exact')
2894 if regexp: args.append('-regexp')
2895 if nocase: args.append('-nocase')
2896 if count: args.append('-count'); args.append(count)
2897 if pattern[0] == '-': args.append('--')
2898 args.append(pattern)
2899 args.append(index)
2900 if stopindex: args.append(stopindex)
2901 return self.tk.call(tuple(args))
2902 def see(self, index):
2903 """Scroll such that the character at INDEX is visible."""
2904 self.tk.call(self._w, 'see', index)
2905 def tag_add(self, tagName, index1, *args):
2906 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2907 Additional pairs of indices may follow in ARGS."""
2908 self.tk.call(
2909 (self._w, 'tag', 'add', tagName, index1) + args)
2910 def tag_unbind(self, tagName, sequence, funcid=None):
2911 """Unbind for all characters with TAGNAME for event SEQUENCE the
2912 function identified with FUNCID."""
2913 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2914 if funcid:
2915 self.deletecommand(funcid)
2916 def tag_bind(self, tagName, sequence, func, add=None):
2917 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002918
Fredrik Lundh06d28152000-08-09 18:03:12 +00002919 An additional boolean parameter ADD specifies whether FUNC will be
2920 called additionally to the other bound function or whether it will
2921 replace the previous function. See bind for the return value."""
2922 return self._bind((self._w, 'tag', 'bind', tagName),
2923 sequence, func, add)
2924 def tag_cget(self, tagName, option):
2925 """Return the value of OPTION for tag TAGNAME."""
2926 if option[:1] != '-':
2927 option = '-' + option
2928 if option[-1:] == '_':
2929 option = option[:-1]
2930 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002931 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002932 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002933 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002934 tag_config = tag_configure
2935 def tag_delete(self, *tagNames):
2936 """Delete all tags in TAGNAMES."""
2937 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2938 def tag_lower(self, tagName, belowThis=None):
2939 """Change the priority of tag TAGNAME such that it is lower
2940 than the priority of BELOWTHIS."""
2941 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2942 def tag_names(self, index=None):
2943 """Return a list of all tag names."""
2944 return self.tk.splitlist(
2945 self.tk.call(self._w, 'tag', 'names', index))
2946 def tag_nextrange(self, tagName, index1, index2=None):
2947 """Return a list of start and end index for the first sequence of
2948 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2949 The text is searched forward from INDEX1."""
2950 return self.tk.splitlist(self.tk.call(
2951 self._w, 'tag', 'nextrange', tagName, index1, index2))
2952 def tag_prevrange(self, tagName, index1, index2=None):
2953 """Return a list of start and end index for the first sequence of
2954 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2955 The text is searched backwards from INDEX1."""
2956 return self.tk.splitlist(self.tk.call(
2957 self._w, 'tag', 'prevrange', tagName, index1, index2))
2958 def tag_raise(self, tagName, aboveThis=None):
2959 """Change the priority of tag TAGNAME such that it is higher
2960 than the priority of ABOVETHIS."""
2961 self.tk.call(
2962 self._w, 'tag', 'raise', tagName, aboveThis)
2963 def tag_ranges(self, tagName):
2964 """Return a list of ranges of text which have tag TAGNAME."""
2965 return self.tk.splitlist(self.tk.call(
2966 self._w, 'tag', 'ranges', tagName))
2967 def tag_remove(self, tagName, index1, index2=None):
2968 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2969 self.tk.call(
2970 self._w, 'tag', 'remove', tagName, index1, index2)
2971 def window_cget(self, index, option):
2972 """Return the value of OPTION of an embedded window at INDEX."""
2973 if option[:1] != '-':
2974 option = '-' + option
2975 if option[-1:] == '_':
2976 option = option[:-1]
2977 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002978 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002979 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002980 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002981 window_config = window_configure
2982 def window_create(self, index, cnf={}, **kw):
2983 """Create a window at INDEX."""
2984 self.tk.call(
2985 (self._w, 'window', 'create', index)
2986 + self._options(cnf, kw))
2987 def window_names(self):
2988 """Return all names of embedded windows in this widget."""
2989 return self.tk.splitlist(
2990 self.tk.call(self._w, 'window', 'names'))
2991 def xview(self, *what):
2992 """Query and change horizontal position of the view."""
2993 if not what:
2994 return self._getdoubles(self.tk.call(self._w, 'xview'))
2995 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002996 def xview_moveto(self, fraction):
2997 """Adjusts the view in the window so that FRACTION of the
2998 total width of the canvas is off-screen to the left."""
2999 self.tk.call(self._w, 'xview', 'moveto', fraction)
3000 def xview_scroll(self, number, what):
3001 """Shift the x-view according to NUMBER which is measured
3002 in "units" or "pages" (WHAT)."""
3003 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003004 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003005 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003006 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003007 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003008 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003009 def yview_moveto(self, fraction):
3010 """Adjusts the view in the window so that FRACTION of the
3011 total height of the canvas is off-screen to the top."""
3012 self.tk.call(self._w, 'yview', 'moveto', fraction)
3013 def yview_scroll(self, number, what):
3014 """Shift the y-view according to NUMBER which is measured
3015 in "units" or "pages" (WHAT)."""
3016 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003017 def yview_pickplace(self, *what):
3018 """Obsolete function, use see."""
3019 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003020
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003021
Guido van Rossum28574b51996-10-21 15:16:51 +00003022class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003023 """Internal class. It wraps the command in the widget OptionMenu."""
3024 def __init__(self, var, value, callback=None):
3025 self.__value = value
3026 self.__var = var
3027 self.__callback = callback
3028 def __call__(self, *args):
3029 self.__var.set(self.__value)
3030 if self.__callback:
3031 apply(self.__callback, (self.__value,)+args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003032
3033class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003034 """OptionMenu which allows the user to select a value from a menu."""
3035 def __init__(self, master, variable, value, *values, **kwargs):
3036 """Construct an optionmenu widget with the parent MASTER, with
3037 the resource textvariable set to VARIABLE, the initially selected
3038 value VALUE, the other menu values VALUES and an additional
3039 keyword argument command."""
3040 kw = {"borderwidth": 2, "textvariable": variable,
3041 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3042 "highlightthickness": 2}
3043 Widget.__init__(self, master, "menubutton", kw)
3044 self.widgetName = 'tk_optionMenu'
3045 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3046 self.menuname = menu._w
3047 # 'command' is the only supported keyword
3048 callback = kwargs.get('command')
3049 if kwargs.has_key('command'):
3050 del kwargs['command']
3051 if kwargs:
3052 raise TclError, 'unknown option -'+kwargs.keys()[0]
3053 menu.add_command(label=value,
3054 command=_setit(variable, value, callback))
3055 for v in values:
3056 menu.add_command(label=v,
3057 command=_setit(variable, v, callback))
3058 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003059
Fredrik Lundh06d28152000-08-09 18:03:12 +00003060 def __getitem__(self, name):
3061 if name == 'menu':
3062 return self.__menu
3063 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003064
Fredrik Lundh06d28152000-08-09 18:03:12 +00003065 def destroy(self):
3066 """Destroy this widget and the associated menu."""
3067 Menubutton.destroy(self)
3068 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003069
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003070class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003071 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003072 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003073 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3074 self.name = None
3075 if not master:
3076 master = _default_root
3077 if not master:
3078 raise RuntimeError, 'Too early to create image'
3079 self.tk = master.tk
3080 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003081 Image._last_id += 1
3082 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003083 # The following is needed for systems where id(x)
3084 # can return a negative number, such as Linux/m68k:
3085 if name[0] == '-': name = '_' + name[1:]
3086 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3087 elif kw: cnf = kw
3088 options = ()
3089 for k, v in cnf.items():
3090 if callable(v):
3091 v = self._register(v)
3092 options = options + ('-'+k, v)
3093 self.tk.call(('image', 'create', imgtype, name,) + options)
3094 self.name = name
3095 def __str__(self): return self.name
3096 def __del__(self):
3097 if self.name:
3098 try:
3099 self.tk.call('image', 'delete', self.name)
3100 except TclError:
3101 # May happen if the root was destroyed
3102 pass
3103 def __setitem__(self, key, value):
3104 self.tk.call(self.name, 'configure', '-'+key, value)
3105 def __getitem__(self, key):
3106 return self.tk.call(self.name, 'configure', '-'+key)
3107 def configure(self, **kw):
3108 """Configure the image."""
3109 res = ()
3110 for k, v in _cnfmerge(kw).items():
3111 if v is not None:
3112 if k[-1] == '_': k = k[:-1]
3113 if callable(v):
3114 v = self._register(v)
3115 res = res + ('-'+k, v)
3116 self.tk.call((self.name, 'config') + res)
3117 config = configure
3118 def height(self):
3119 """Return the height of the image."""
3120 return getint(
3121 self.tk.call('image', 'height', self.name))
3122 def type(self):
3123 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3124 return self.tk.call('image', 'type', self.name)
3125 def width(self):
3126 """Return the width of the image."""
3127 return getint(
3128 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003129
3130class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003131 """Widget which can display colored images in GIF, PPM/PGM format."""
3132 def __init__(self, name=None, cnf={}, master=None, **kw):
3133 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003134
Fredrik Lundh06d28152000-08-09 18:03:12 +00003135 Valid resource names: data, format, file, gamma, height, palette,
3136 width."""
3137 apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
3138 def blank(self):
3139 """Display a transparent image."""
3140 self.tk.call(self.name, 'blank')
3141 def cget(self, option):
3142 """Return the value of OPTION."""
3143 return self.tk.call(self.name, 'cget', '-' + option)
3144 # XXX config
3145 def __getitem__(self, key):
3146 return self.tk.call(self.name, 'cget', '-' + key)
3147 # XXX copy -from, -to, ...?
3148 def copy(self):
3149 """Return a new PhotoImage with the same image as this widget."""
3150 destImage = PhotoImage()
3151 self.tk.call(destImage, 'copy', self.name)
3152 return destImage
3153 def zoom(self,x,y=''):
3154 """Return a new PhotoImage with the same image as this widget
3155 but zoom it with X and Y."""
3156 destImage = PhotoImage()
3157 if y=='': y=x
3158 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3159 return destImage
3160 def subsample(self,x,y=''):
3161 """Return a new PhotoImage based on the same image as this widget
3162 but use only every Xth or Yth pixel."""
3163 destImage = PhotoImage()
3164 if y=='': y=x
3165 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3166 return destImage
3167 def get(self, x, y):
3168 """Return the color (red, green, blue) of the pixel at X,Y."""
3169 return self.tk.call(self.name, 'get', x, y)
3170 def put(self, data, to=None):
3171 """Put row formated colors to image starting from
3172 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3173 args = (self.name, 'put', data)
3174 if to:
3175 if to[0] == '-to':
3176 to = to[1:]
3177 args = args + ('-to',) + tuple(to)
3178 self.tk.call(args)
3179 # XXX read
3180 def write(self, filename, format=None, from_coords=None):
3181 """Write image to file FILENAME in FORMAT starting from
3182 position FROM_COORDS."""
3183 args = (self.name, 'write', filename)
3184 if format:
3185 args = args + ('-format', format)
3186 if from_coords:
3187 args = args + ('-from',) + tuple(from_coords)
3188 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003189
3190class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003191 """Widget which can display a bitmap."""
3192 def __init__(self, name=None, cnf={}, master=None, **kw):
3193 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003194
Fredrik Lundh06d28152000-08-09 18:03:12 +00003195 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3196 apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003197
3198def image_names(): return _default_root.tk.call('image', 'names')
3199def image_types(): return _default_root.tk.call('image', 'types')
3200
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003201
3202class Spinbox(Widget):
3203 """spinbox widget."""
3204 def __init__(self, master=None, cnf={}, **kw):
3205 """Construct a spinbox widget with the parent MASTER.
3206
3207 STANDARD OPTIONS
3208
3209 activebackground, background, borderwidth,
3210 cursor, exportselection, font, foreground,
3211 highlightbackground, highlightcolor,
3212 highlightthickness, insertbackground,
3213 insertborderwidth, insertofftime,
3214 insertontime, insertwidth, justify, relief,
3215 repeatdelay, repeatinterval,
3216 selectbackground, selectborderwidth
3217 selectforeground, takefocus, textvariable
3218 xscrollcommand.
3219
3220 WIDGET-SPECIFIC OPTIONS
3221
3222 buttonbackground, buttoncursor,
3223 buttondownrelief, buttonuprelief,
3224 command, disabledbackground,
3225 disabledforeground, format, from,
3226 invalidcommand, increment,
3227 readonlybackground, state, to,
3228 validate, validatecommand values,
3229 width, wrap,
3230 """
3231 Widget.__init__(self, master, 'spinbox', cnf, kw)
3232
3233 def bbox(self, index):
3234 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3235 rectangle which encloses the character given by index.
3236
3237 The first two elements of the list give the x and y
3238 coordinates of the upper-left corner of the screen
3239 area covered by the character (in pixels relative
3240 to the widget) and the last two elements give the
3241 width and height of the character, in pixels. The
3242 bounding box may refer to a region outside the
3243 visible area of the window.
3244 """
3245 return self.tk.call(self._w, 'bbox', index)
3246
3247 def delete(self, first, last=None):
3248 """Delete one or more elements of the spinbox.
3249
3250 First is the index of the first character to delete,
3251 and last is the index of the character just after
3252 the last one to delete. If last isn't specified it
3253 defaults to first+1, i.e. a single character is
3254 deleted. This command returns an empty string.
3255 """
3256 return self.tk.call(self._w, 'delete', first, last)
3257
3258 def get(self):
3259 """Returns the spinbox's string"""
3260 return self.tk.call(self._w, 'get')
3261
3262 def icursor(self, index):
3263 """Alter the position of the insertion cursor.
3264
3265 The insertion cursor will be displayed just before
3266 the character given by index. Returns an empty string
3267 """
3268 return self.tk.call(self._w, 'icursor', index)
3269
3270 def identify(self, x, y):
3271 """Returns the name of the widget at position x, y
3272
3273 Return value is one of: none, buttondown, buttonup, entry
3274 """
3275 return self.tk.call(self._w, 'identify', x, y)
3276
3277 def index(self, index):
3278 """Returns the numerical index corresponding to index
3279 """
3280 return self.tk.call(self._w, 'index', index)
3281
3282 def insert(self, index, s):
3283 """Insert string s at index
3284
3285 Returns an empty string.
3286 """
3287 return self.tk.call(self._w, 'insert', index, s)
3288
3289 def invoke(self, element):
3290 """Causes the specified element to be invoked
3291
3292 The element could be buttondown or buttonup
3293 triggering the action associated with it.
3294 """
3295 return self.tk.call(self._w, 'invoke', element)
3296
3297 def scan(self, *args):
3298 """Internal function."""
3299 return self._getints(
3300 self.tk.call((self._w, 'scan') + args)) or ()
3301
3302 def scan_mark(self, x):
3303 """Records x and the current view in the spinbox window;
3304
3305 used in conjunction with later scan dragto commands.
3306 Typically this command is associated with a mouse button
3307 press in the widget. It returns an empty string.
3308 """
3309 return self.scan("mark", x)
3310
3311 def scan_dragto(self, x):
3312 """Compute the difference between the given x argument
3313 and the x argument to the last scan mark command
3314
3315 It then adjusts the view left or right by 10 times the
3316 difference in x-coordinates. This command is typically
3317 associated with mouse motion events in the widget, to
3318 produce the effect of dragging the spinbox at high speed
3319 through the window. The return value is an empty string.
3320 """
3321 return self.scan("dragto", x)
3322
3323 def selection(self, *args):
3324 """Internal function."""
3325 return self._getints(
3326 self.tk.call((self._w, 'selection') + args)) or ()
3327
3328 def selection_adjust(self, index):
3329 """Locate the end of the selection nearest to the character
3330 given by index,
3331
3332 Then adjust that end of the selection to be at index
3333 (i.e including but not going beyond index). The other
3334 end of the selection is made the anchor point for future
3335 select to commands. If the selection isn't currently in
3336 the spinbox, then a new selection is created to include
3337 the characters between index and the most recent selection
3338 anchor point, inclusive. Returns an empty string.
3339 """
3340 return self.selection("adjust", index)
3341
3342 def selection_clear(self):
3343 """Clear the selection
3344
3345 If the selection isn't in this widget then the
3346 command has no effect. Returns an empty string.
3347 """
3348 return self.selection("clear")
3349
3350 def selection_element(self, element=None):
3351 """Sets or gets the currently selected element.
3352
3353 If a spinbutton element is specified, it will be
3354 displayed depressed
3355 """
3356 return self.selection("element", element)
3357
3358###########################################################################
3359
3360class LabelFrame(Widget):
3361 """labelframe widget."""
3362 def __init__(self, master=None, cnf={}, **kw):
3363 """Construct a labelframe widget with the parent MASTER.
3364
3365 STANDARD OPTIONS
3366
3367 borderwidth, cursor, font, foreground,
3368 highlightbackground, highlightcolor,
3369 highlightthickness, padx, pady, relief,
3370 takefocus, text
3371
3372 WIDGET-SPECIFIC OPTIONS
3373
3374 background, class, colormap, container,
3375 height, labelanchor, labelwidget,
3376 visual, width
3377 """
3378 Widget.__init__(self, master, 'labelframe', cnf, kw)
3379
3380########################################################################
3381
3382class PanedWindow(Widget):
3383 """panedwindow widget."""
3384 def __init__(self, master=None, cnf={}, **kw):
3385 """Construct a panedwindow widget with the parent MASTER.
3386
3387 STANDARD OPTIONS
3388
3389 background, borderwidth, cursor, height,
3390 orient, relief, width
3391
3392 WIDGET-SPECIFIC OPTIONS
3393
3394 handlepad, handlesize, opaqueresize,
3395 sashcursor, sashpad, sashrelief,
3396 sashwidth, showhandle,
3397 """
3398 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3399
3400 def add(self, child, **kw):
3401 """Add a child widget to the panedwindow in a new pane.
3402
3403 The child argument is the name of the child widget
3404 followed by pairs of arguments that specify how to
3405 manage the windows. Options may have any of the values
3406 accepted by the configure subcommand.
3407 """
3408 self.tk.call((self._w, 'add', child) + self._options(kw))
3409
3410 def remove(self, child):
3411 """Remove the pane containing child from the panedwindow
3412
3413 All geometry management options for child will be forgotten.
3414 """
3415 self.tk.call(self._w, 'forget', child)
3416 forget=remove
3417
3418 def identify(self, x, y):
3419 """Identify the panedwindow component at point x, y
3420
3421 If the point is over a sash or a sash handle, the result
3422 is a two element list containing the index of the sash or
3423 handle, and a word indicating whether it is over a sash
3424 or a handle, such as {0 sash} or {2 handle}. If the point
3425 is over any other part of the panedwindow, the result is
3426 an empty list.
3427 """
3428 return self.tk.call(self._w, 'identify', x, y)
3429
3430 def proxy(self, *args):
3431 """Internal function."""
3432 return self._getints(
3433 self.tk.call((self._w, 'proxy') + args)) or ()
3434
3435 def proxy_coord(self):
3436 """Return the x and y pair of the most recent proxy location
3437 """
3438 return self.proxy("coord")
3439
3440 def proxy_forget(self):
3441 """Remove the proxy from the display.
3442 """
3443 return self.proxy("forget")
3444
3445 def proxy_place(self, x, y):
3446 """Place the proxy at the given x and y coordinates.
3447 """
3448 return self.proxy("place", x, y)
3449
3450 def sash(self, *args):
3451 """Internal function."""
3452 return self._getints(
3453 self.tk.call((self._w, 'sash') + args)) or ()
3454
3455 def sash_coord(self, index):
3456 """Return the current x and y pair for the sash given by index.
3457
3458 Index must be an integer between 0 and 1 less than the
3459 number of panes in the panedwindow. The coordinates given are
3460 those of the top left corner of the region containing the sash.
3461 pathName sash dragto index x y This command computes the
3462 difference between the given coordinates and the coordinates
3463 given to the last sash coord command for the given sash. It then
3464 moves that sash the computed difference. The return value is the
3465 empty string.
3466 """
3467 return self.sash("coord", index)
3468
3469 def sash_mark(self, index):
3470 """Records x and y for the sash given by index;
3471
3472 Used in conjunction with later dragto commands to move the sash.
3473 """
3474 return self.sash("mark", index)
3475
3476 def sash_place(self, index, x, y):
3477 """Place the sash given by index at the given coordinates
3478 """
3479 return self.sash("place", index, x, y)
3480
3481 def panecget(self, child, option):
3482 """Query a management option for window.
3483
3484 Option may be any value allowed by the paneconfigure subcommand
3485 """
3486 return self.tk.call(
3487 (self._w, 'panecget') + (child, '-'+option))
3488
3489 def paneconfigure(self, tagOrId, cnf=None, **kw):
3490 """Query or modify the management options for window.
3491
3492 If no option is specified, returns a list describing all
3493 of the available options for pathName. If option is
3494 specified with no value, then the command returns a list
3495 describing the one named option (this list will be identical
3496 to the corresponding sublist of the value returned if no
3497 option is specified). If one or more option-value pairs are
3498 specified, then the command modifies the given widget
3499 option(s) to have the given value(s); in this case the
3500 command returns an empty string. The following options
3501 are supported:
3502
3503 after window
3504 Insert the window after the window specified. window
3505 should be the name of a window already managed by pathName.
3506 before window
3507 Insert the window before the window specified. window
3508 should be the name of a window already managed by pathName.
3509 height size
3510 Specify a height for the window. The height will be the
3511 outer dimension of the window including its border, if
3512 any. If size is an empty string, or if -height is not
3513 specified, then the height requested internally by the
3514 window will be used initially; the height may later be
3515 adjusted by the movement of sashes in the panedwindow.
3516 Size may be any value accepted by Tk_GetPixels.
3517 minsize n
3518 Specifies that the size of the window cannot be made
3519 less than n. This constraint only affects the size of
3520 the widget in the paned dimension -- the x dimension
3521 for horizontal panedwindows, the y dimension for
3522 vertical panedwindows. May be any value accepted by
3523 Tk_GetPixels.
3524 padx n
3525 Specifies a non-negative value indicating how much
3526 extra space to leave on each side of the window in
3527 the X-direction. The value may have any of the forms
3528 accepted by Tk_GetPixels.
3529 pady n
3530 Specifies a non-negative value indicating how much
3531 extra space to leave on each side of the window in
3532 the Y-direction. The value may have any of the forms
3533 accepted by Tk_GetPixels.
3534 sticky style
3535 If a window's pane is larger than the requested
3536 dimensions of the window, this option may be used
3537 to position (or stretch) the window within its pane.
3538 Style is a string that contains zero or more of the
3539 characters n, s, e or w. The string can optionally
3540 contains spaces or commas, but they are ignored. Each
3541 letter refers to a side (north, south, east, or west)
3542 that the window will "stick" to. If both n and s
3543 (or e and w) are specified, the window will be
3544 stretched to fill the entire height (or width) of
3545 its cavity.
3546 width size
3547 Specify a width for the window. The width will be
3548 the outer dimension of the window including its
3549 border, if any. If size is an empty string, or
3550 if -width is not specified, then the width requested
3551 internally by the window will be used initially; the
3552 width may later be adjusted by the movement of sashes
3553 in the panedwindow. Size may be any value accepted by
3554 Tk_GetPixels.
3555
3556 """
3557 if cnf is None and not kw:
3558 cnf = {}
3559 for x in self.tk.split(
3560 self.tk.call(self._w,
3561 'paneconfigure', tagOrId)):
3562 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3563 return cnf
3564 if type(cnf) == StringType and not kw:
3565 x = self.tk.split(self.tk.call(
3566 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3567 return (x[0][1:],) + x[1:]
3568 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3569 self._options(cnf, kw))
3570 paneconfig = paneconfigure
3571
3572 def panes(self):
3573 """Returns an ordered list of the child panes."""
3574 return self.tk.call(self._w, 'panes')
3575
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003576######################################################################
3577# Extensions:
3578
3579class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003580 def __init__(self, master=None, cnf={}, **kw):
3581 Widget.__init__(self, master, 'studbutton', cnf, kw)
3582 self.bind('<Any-Enter>', self.tkButtonEnter)
3583 self.bind('<Any-Leave>', self.tkButtonLeave)
3584 self.bind('<1>', self.tkButtonDown)
3585 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003586
3587class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003588 def __init__(self, master=None, cnf={}, **kw):
3589 Widget.__init__(self, master, 'tributton', cnf, kw)
3590 self.bind('<Any-Enter>', self.tkButtonEnter)
3591 self.bind('<Any-Leave>', self.tkButtonLeave)
3592 self.bind('<1>', self.tkButtonDown)
3593 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3594 self['fg'] = self['bg']
3595 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003596
Guido van Rossumc417ef81996-08-21 23:38:59 +00003597######################################################################
3598# Test:
3599
3600def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003601 root = Tk()
3602 text = "This is Tcl/Tk version %s" % TclVersion
3603 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003604 try:
3605 text = text + unicode("\nThis should be a cedilla: \347",
3606 "iso-8859-1")
3607 except NameError:
3608 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003609 label = Label(root, text=text)
3610 label.pack()
3611 test = Button(root, text="Click me!",
3612 command=lambda root=root: root.test.configure(
3613 text="[%s]" % root.test['text']))
3614 test.pack()
3615 root.test = test
3616 quit = Button(root, text="QUIT", command=root.destroy)
3617 quit.pack()
3618 # The following three commands are needed so the window pops
3619 # up on top on Windows...
3620 root.iconify()
3621 root.update()
3622 root.deiconify()
3623 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003624
3625if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003626 _test()