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