blob: 7cbcb500bb4861960228c1b3e3c5deef5e9c0fff [file] [log] [blame]
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001"""Wrapper functions for Tcl/Tk.
2
3Tkinter provides classes which allow the display, positioning and
4control of widgets. Toplevel widgets are Tk and Toplevel. Other
5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00006Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
Raymond Hettingerff41c482003-04-06 09:01:11 +00007LabelFrame and PanedWindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00008
Raymond Hettingerff41c482003-04-06 09:01:11 +00009Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
Martin v. Löwis2ec36272002-10-13 10:22:08 +000011under Tk.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000012
13Widgets are positioned with one of the geometry managers Place, Pack
14or Grid. These managers can be called with methods place, pack, grid
15available in every Widget.
16
Guido van Rossuma0adb922001-09-01 18:29:55 +000017Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000019
20Example (Hello, World):
21import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25frame.pack(fill=BOTH,expand=1)
26label = Tkinter.Label(frame, text="Hello, World")
27label.pack(fill=X, expand=1)
28button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
29button.pack(side=BOTTOM)
30tk.mainloop()
31"""
Guido van Rossum2dcf5291994-07-06 09:23:20 +000032
Guido van Rossum37dcab11996-05-16 16:00:19 +000033__version__ = "$Revision$"
34
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import sys
36if sys.platform == "win32":
Fredrik Lundh06d28152000-08-09 18:03:12 +000037 import FixTk # Attempt to configure Tcl/Tk without requiring PATH
Guido van Rossumf8d579c1999-01-04 18:06:45 +000038import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000039tkinter = _tkinter # b/w compat for export
40TclError = _tkinter.TclError
Guido van Rossum7e9394a1995-03-17 16:21:33 +000041from types import *
Guido van Rossuma5773dd1995-09-07 19:22:00 +000042from Tkconstants import *
Guido van Rossumf0c891a1998-04-29 21:43:36 +000043try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000044 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000045except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000046 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000047
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000048wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000049
Eric S. Raymondfc170b12001-02-09 11:51:27 +000050TkVersion = float(_tkinter.TK_VERSION)
51TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000052
Guido van Rossumd6615ab1997-08-05 02:35:01 +000053READABLE = _tkinter.READABLE
54WRITABLE = _tkinter.WRITABLE
55EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000056
57# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
58try: _tkinter.createfilehandler
59except AttributeError: _tkinter.createfilehandler = None
60try: _tkinter.deletefilehandler
61except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000062
63
Guido van Rossum2dcf5291994-07-06 09:23:20 +000064def _flatten(tuple):
Fredrik Lundh06d28152000-08-09 18:03:12 +000065 """Internal function."""
66 res = ()
67 for item in tuple:
68 if type(item) in (TupleType, ListType):
69 res = res + _flatten(item)
70 elif item is not None:
71 res = res + (item,)
72 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000073
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000074try: _flatten = _tkinter._flatten
75except AttributeError: pass
76
Guido van Rossum2dcf5291994-07-06 09:23:20 +000077def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000078 """Internal function."""
79 if type(cnfs) is DictionaryType:
80 return cnfs
81 elif type(cnfs) in (NoneType, StringType):
82 return cnfs
83 else:
84 cnf = {}
85 for c in _flatten(cnfs):
86 try:
87 cnf.update(c)
88 except (AttributeError, TypeError), msg:
89 print "_cnfmerge: fallback due to:", msg
90 for k, v in c.items():
91 cnf[k] = v
92 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000093
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000094try: _cnfmerge = _tkinter._cnfmerge
95except AttributeError: pass
96
Guido van Rossum2dcf5291994-07-06 09:23:20 +000097class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000099
Fredrik Lundh06d28152000-08-09 18:03:12 +0000100 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000101
Fredrik Lundh06d28152000-08-09 18:03:12 +0000102 KeyPress, KeyRelease - for keyboard events
103 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
104 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
105 Colormap, Gravity, Reparent, Property, Destroy, Activate,
106 Deactivate - for window events.
107
108 If a callback function for one of these events is registered
109 using bind, bind_all, bind_class, or tag_bind, the callback is
110 called with an Event as first argument. It will have the
111 following attributes (in braces are the event types for which
112 the attribute is valid):
113
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000114 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000115 num - mouse button pressed (ButtonPress, ButtonRelease)
116 focus - whether the window has the focus (Enter, Leave)
117 height - height of the exposed window (Configure, Expose)
118 width - width of the exposed window (Configure, Expose)
119 keycode - keycode of the pressed key (KeyPress, KeyRelease)
120 state - state of the event as a number (ButtonPress, ButtonRelease,
121 Enter, KeyPress, KeyRelease,
122 Leave, Motion)
123 state - state as a string (Visibility)
124 time - when the event occurred
125 x - x-position of the mouse
126 y - y-position of the mouse
127 x_root - x-position of the mouse on the screen
128 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
129 y_root - y-position of the mouse on the screen
130 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
131 char - pressed character (KeyPress, KeyRelease)
132 send_event - see X/Windows documentation
Walter Dörwald966c2642005-11-09 17:12:43 +0000133 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000134 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:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000166 """Class to define value holders for e.g. buttons.
167
168 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
169 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000170 _default = ""
Martin v. Löwis337487e2006-06-17 09:15:14 +0000171 def __init__(self, master=None, value=None, name=None):
172 """Construct a variable
173
174 MASTER can be given as master widget.
175 VALUE is an optional value (defaults to "")
176 NAME is an optional Tcl name (defaults to PY_VARnum).
177
178 If NAME matches an existing variable and VALUE is omitted
179 then the existing value is retained.
Fredrik Lundh06d28152000-08-09 18:03:12 +0000180 """
181 global _varnum
182 if not master:
183 master = _default_root
184 self._master = master
185 self._tk = master.tk
Martin v. Löwis337487e2006-06-17 09:15:14 +0000186 if name:
187 self._name = name
188 else:
189 self._name = 'PY_VAR' + `_varnum`
190 _varnum += 1
191 if value != None:
192 self.set(value)
193 elif not self._tk.call("info", "exists", self._name):
194 self.set(self._default)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000195 def __del__(self):
196 """Unset the variable in Tcl."""
197 self._tk.globalunsetvar(self._name)
198 def __str__(self):
199 """Return the name of the variable in Tcl."""
200 return self._name
201 def set(self, value):
202 """Set the variable to VALUE."""
203 return self._tk.globalsetvar(self._name, value)
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000204 def get(self):
205 """Return value of variable."""
206 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000207 def trace_variable(self, mode, callback):
208 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000209
Fredrik Lundh06d28152000-08-09 18:03:12 +0000210 MODE is one of "r", "w", "u" for read, write, undefine.
211 CALLBACK must be a function which is called when
212 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000213
Fredrik Lundh06d28152000-08-09 18:03:12 +0000214 Return the name of the callback.
215 """
216 cbname = self._master._register(callback)
217 self._tk.call("trace", "variable", self._name, mode, cbname)
218 return cbname
219 trace = trace_variable
220 def trace_vdelete(self, mode, cbname):
221 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000222
Fredrik Lundh06d28152000-08-09 18:03:12 +0000223 MODE is one of "r", "w", "u" for read, write, undefine.
224 CBNAME is the name of the callback returned from trace_variable or trace.
225 """
226 self._tk.call("trace", "vdelete", self._name, mode, cbname)
227 self._master.deletecommand(cbname)
228 def trace_vinfo(self):
229 """Return all trace callback information."""
230 return map(self._tk.split, self._tk.splitlist(
231 self._tk.call("trace", "vinfo", self._name)))
Martin v. Löwis337487e2006-06-17 09:15:14 +0000232 def __eq__(self, other):
233 """Comparison for equality (==).
234
235 Note: if the Variable's master matters to behavior
236 also compare self._master == other._master
237 """
238 return self.__class__.__name__ == other.__class__.__name__ \
239 and self._name == other._name
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000240
241class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000242 """Value holder for strings variables."""
243 _default = ""
Martin v. Löwis337487e2006-06-17 09:15:14 +0000244 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000245 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000246
Martin v. Löwis337487e2006-06-17 09:15:14 +0000247 MASTER can be given as master widget.
248 VALUE is an optional value (defaults to "")
249 NAME is an optional Tcl name (defaults to PY_VARnum).
250
251 If NAME matches an existing variable and VALUE is omitted
252 then the existing value is retained.
253 """
254 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000255
Fredrik Lundh06d28152000-08-09 18:03:12 +0000256 def get(self):
257 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000258 value = self._tk.globalgetvar(self._name)
259 if isinstance(value, basestring):
260 return value
261 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000262
263class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000264 """Value holder for integer variables."""
265 _default = 0
Martin v. Löwis337487e2006-06-17 09:15:14 +0000266 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000267 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000268
Martin v. Löwis337487e2006-06-17 09:15:14 +0000269 MASTER can be given as master widget.
270 VALUE is an optional value (defaults to 0)
271 NAME is an optional Tcl name (defaults to PY_VARnum).
272
273 If NAME matches an existing variable and VALUE is omitted
274 then the existing value is retained.
275 """
276 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000277
Martin v. Löwis70c3dda2003-01-22 09:17:38 +0000278 def set(self, value):
279 """Set the variable to value, converting booleans to integers."""
280 if isinstance(value, bool):
281 value = int(value)
282 return Variable.set(self, value)
283
Fredrik Lundh06d28152000-08-09 18:03:12 +0000284 def get(self):
285 """Return the value of the variable as an integer."""
286 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000287
288class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000289 """Value holder for float variables."""
290 _default = 0.0
Martin v. Löwis337487e2006-06-17 09:15:14 +0000291 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000292 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000293
Martin v. Löwis337487e2006-06-17 09:15:14 +0000294 MASTER can be given as master widget.
295 VALUE is an optional value (defaults to 0.0)
296 NAME is an optional Tcl name (defaults to PY_VARnum).
297
298 If NAME matches an existing variable and VALUE is omitted
299 then the existing value is retained.
300 """
301 Variable.__init__(self, master, value, name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000302
303 def get(self):
304 """Return the value of the variable as a float."""
305 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000306
307class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000308 """Value holder for boolean variables."""
Martin v. Löwis337487e2006-06-17 09:15:14 +0000309 _default = False
310 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000311 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000312
Martin v. Löwis337487e2006-06-17 09:15:14 +0000313 MASTER can be given as master widget.
314 VALUE is an optional value (defaults to False)
315 NAME is an optional Tcl name (defaults to PY_VARnum).
316
317 If NAME matches an existing variable and VALUE is omitted
318 then the existing value is retained.
319 """
320 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000321
Fredrik Lundh06d28152000-08-09 18:03:12 +0000322 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000323 """Return the value of the variable as a bool."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000324 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000325
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000326def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000327 """Run the main loop of Tcl."""
328 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000329
Guido van Rossum0132f691998-04-30 17:50:36 +0000330getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000331
Guido van Rossum0132f691998-04-30 17:50:36 +0000332getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000333
334def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000335 """Convert true and false to integer values 1 and 0."""
336 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000337
Guido van Rossum368e06b1997-11-07 20:38:49 +0000338# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000339class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000340 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000341
Fredrik Lundh06d28152000-08-09 18:03:12 +0000342 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000343
Fredrik Lundh06d28152000-08-09 18:03:12 +0000344 # XXX font command?
345 _tclCommands = None
346 def destroy(self):
347 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000348
Fredrik Lundh06d28152000-08-09 18:03:12 +0000349 Delete all Tcl commands created for
350 this widget in the Tcl interpreter."""
351 if self._tclCommands is not None:
352 for name in self._tclCommands:
353 #print '- Tkinter: deleted command', name
354 self.tk.deletecommand(name)
355 self._tclCommands = None
356 def deletecommand(self, name):
357 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000358
Fredrik Lundh06d28152000-08-09 18:03:12 +0000359 Delete the Tcl command provided in NAME."""
360 #print '- Tkinter: deleted command', name
361 self.tk.deletecommand(name)
362 try:
363 self._tclCommands.remove(name)
364 except ValueError:
365 pass
366 def tk_strictMotif(self, boolean=None):
367 """Set Tcl internal variable, whether the look and feel
368 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000369
Fredrik Lundh06d28152000-08-09 18:03:12 +0000370 A parameter of 1 means adhere to Motif (e.g. no color
371 change if mouse passes over slider).
372 Returns the set value."""
373 return self.tk.getboolean(self.tk.call(
374 'set', 'tk_strictMotif', boolean))
375 def tk_bisque(self):
376 """Change the color scheme to light brown as used in Tk 3.6 and before."""
377 self.tk.call('tk_bisque')
378 def tk_setPalette(self, *args, **kw):
379 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000380
Fredrik Lundh06d28152000-08-09 18:03:12 +0000381 A single color as argument will cause that all colors of Tk
382 widget elements are derived from this.
383 Alternatively several keyword parameters and its associated
384 colors can be given. The following keywords are valid:
385 activeBackground, foreground, selectColor,
386 activeForeground, highlightBackground, selectBackground,
387 background, highlightColor, selectForeground,
388 disabledForeground, insertBackground, troughColor."""
389 self.tk.call(('tk_setPalette',)
390 + _flatten(args) + _flatten(kw.items()))
391 def tk_menuBar(self, *args):
392 """Do not use. Needed in Tk 3.6 and earlier."""
393 pass # obsolete since Tk 4.0
394 def wait_variable(self, name='PY_VAR'):
395 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000396
Fredrik Lundh06d28152000-08-09 18:03:12 +0000397 A parameter of type IntVar, StringVar, DoubleVar or
398 BooleanVar must be given."""
399 self.tk.call('tkwait', 'variable', name)
400 waitvar = wait_variable # XXX b/w compat
401 def wait_window(self, window=None):
402 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000403
Fredrik Lundh06d28152000-08-09 18:03:12 +0000404 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000405 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000406 window = self
407 self.tk.call('tkwait', 'window', window._w)
408 def wait_visibility(self, window=None):
409 """Wait until the visibility of a WIDGET changes
410 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000411
Fredrik Lundh06d28152000-08-09 18:03:12 +0000412 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000413 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000414 window = self
415 self.tk.call('tkwait', 'visibility', window._w)
416 def setvar(self, name='PY_VAR', value='1'):
417 """Set Tcl variable NAME to VALUE."""
418 self.tk.setvar(name, value)
419 def getvar(self, name='PY_VAR'):
420 """Return value of Tcl variable NAME."""
421 return self.tk.getvar(name)
422 getint = int
423 getdouble = float
424 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000425 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000426 return self.tk.getboolean(s)
427 def focus_set(self):
428 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000429
Fredrik Lundh06d28152000-08-09 18:03:12 +0000430 If the application currently does not have the focus
431 this widget will get the focus if the application gets
432 the focus through the window manager."""
433 self.tk.call('focus', self._w)
434 focus = focus_set # XXX b/w compat?
435 def focus_force(self):
436 """Direct input focus to this widget even if the
437 application does not have the focus. Use with
438 caution!"""
439 self.tk.call('focus', '-force', self._w)
440 def focus_get(self):
441 """Return the widget which has currently the focus in the
442 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000443
Fredrik Lundh06d28152000-08-09 18:03:12 +0000444 Use focus_displayof to allow working with several
445 displays. Return None if application does not have
446 the focus."""
447 name = self.tk.call('focus')
448 if name == 'none' or not name: return None
449 return self._nametowidget(name)
450 def focus_displayof(self):
451 """Return the widget which has currently the focus on the
452 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000453
Fredrik Lundh06d28152000-08-09 18:03:12 +0000454 Return None if the application does not have the focus."""
455 name = self.tk.call('focus', '-displayof', self._w)
456 if name == 'none' or not name: return None
457 return self._nametowidget(name)
458 def focus_lastfor(self):
459 """Return the widget which would have the focus if top level
460 for this widget gets the focus from the window manager."""
461 name = self.tk.call('focus', '-lastfor', self._w)
462 if name == 'none' or not name: return None
463 return self._nametowidget(name)
464 def tk_focusFollowsMouse(self):
465 """The widget under mouse will get automatically focus. Can not
466 be disabled easily."""
467 self.tk.call('tk_focusFollowsMouse')
468 def tk_focusNext(self):
469 """Return the next widget in the focus order which follows
470 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000471
Fredrik Lundh06d28152000-08-09 18:03:12 +0000472 The focus order first goes to the next child, then to
473 the children of the child recursively and then to the
474 next sibling which is higher in the stacking order. A
475 widget is omitted if it has the takefocus resource set
476 to 0."""
477 name = self.tk.call('tk_focusNext', self._w)
478 if not name: return None
479 return self._nametowidget(name)
480 def tk_focusPrev(self):
481 """Return previous widget in the focus order. See tk_focusNext for details."""
482 name = self.tk.call('tk_focusPrev', self._w)
483 if not name: return None
484 return self._nametowidget(name)
485 def after(self, ms, func=None, *args):
486 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000487
Fredrik Lundh06d28152000-08-09 18:03:12 +0000488 MS specifies the time in milliseconds. FUNC gives the
489 function which shall be called. Additional parameters
490 are given as parameters to the function call. Return
491 identifier to cancel scheduling with after_cancel."""
492 if not func:
493 # I'd rather use time.sleep(ms*0.001)
494 self.tk.call('after', ms)
495 else:
Georg Brandl4696ffb2006-04-02 21:09:51 +0000496 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000497 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000498 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000499 finally:
500 try:
Georg Brandl4696ffb2006-04-02 21:09:51 +0000501 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000502 except TclError:
503 pass
504 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000505 return self.tk.call('after', ms, name)
506 def after_idle(self, func, *args):
507 """Call FUNC once if the Tcl main loop has no event to
508 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000509
Fredrik Lundh06d28152000-08-09 18:03:12 +0000510 Return an identifier to cancel the scheduling with
511 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000512 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000513 def after_cancel(self, id):
514 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000515
Fredrik Lundh06d28152000-08-09 18:03:12 +0000516 Identifier returned by after or after_idle must be
517 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000518 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000519 data = self.tk.call('after', 'info', id)
520 # In Tk 8.3, splitlist returns: (script, type)
521 # In Tk 8.4, splitlist may return (script, type) or (script,)
522 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000523 self.deletecommand(script)
524 except TclError:
525 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000526 self.tk.call('after', 'cancel', id)
527 def bell(self, displayof=0):
528 """Ring a display's bell."""
529 self.tk.call(('bell',) + self._displayof(displayof))
Tim Petersaa220a72006-04-16 22:22:36 +0000530
Fredrik Lundh06d28152000-08-09 18:03:12 +0000531 # Clipboard handling:
Martin v. Löwis0db2a982006-04-16 20:55:38 +0000532 def clipboard_get(self, **kw):
533 """Retrieve data from the clipboard on window's display.
Tim Petersaa220a72006-04-16 22:22:36 +0000534
535 The window keyword defaults to the root window of the Tkinter
Martin v. Löwis0db2a982006-04-16 20:55:38 +0000536 application.
Tim Petersaa220a72006-04-16 22:22:36 +0000537
538 The type keyword specifies the form in which the data is
539 to be returned and should be an atom name such as STRING
540 or FILE_NAME. Type defaults to STRING.
541
Martin v. Löwis0db2a982006-04-16 20:55:38 +0000542 This command is equivalent to:
Tim Petersaa220a72006-04-16 22:22:36 +0000543
Martin v. Löwis0db2a982006-04-16 20:55:38 +0000544 selection_get(CLIPBOARD)
545 """
546 return self.tk.call(('clipboard', 'get') + self._options(kw))
Tim Petersaa220a72006-04-16 22:22:36 +0000547
Fredrik Lundh06d28152000-08-09 18:03:12 +0000548 def clipboard_clear(self, **kw):
549 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000550
Fredrik Lundh06d28152000-08-09 18:03:12 +0000551 A widget specified for the optional displayof keyword
552 argument specifies the target display."""
553 if not kw.has_key('displayof'): kw['displayof'] = self._w
554 self.tk.call(('clipboard', 'clear') + self._options(kw))
555 def clipboard_append(self, string, **kw):
556 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000557
Fredrik Lundh06d28152000-08-09 18:03:12 +0000558 A widget specified at the optional displayof keyword
559 argument specifies the target display. The clipboard
560 can be retrieved with selection_get."""
561 if not kw.has_key('displayof'): kw['displayof'] = self._w
562 self.tk.call(('clipboard', 'append') + self._options(kw)
563 + ('--', string))
564 # XXX grab current w/o window argument
565 def grab_current(self):
566 """Return widget which has currently the grab in this application
567 or None."""
568 name = self.tk.call('grab', 'current', self._w)
569 if not name: return None
570 return self._nametowidget(name)
571 def grab_release(self):
572 """Release grab for this widget if currently set."""
573 self.tk.call('grab', 'release', self._w)
574 def grab_set(self):
575 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000576
Fredrik Lundh06d28152000-08-09 18:03:12 +0000577 A grab directs all events to this and descendant
578 widgets in the application."""
579 self.tk.call('grab', 'set', self._w)
580 def grab_set_global(self):
581 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000582
Fredrik Lundh06d28152000-08-09 18:03:12 +0000583 A global grab directs all events to this and
584 descendant widgets on the display. Use with caution -
585 other applications do not get events anymore."""
586 self.tk.call('grab', 'set', '-global', self._w)
587 def grab_status(self):
588 """Return None, "local" or "global" if this widget has
589 no, a local or a global grab."""
590 status = self.tk.call('grab', 'status', self._w)
591 if status == 'none': status = None
592 return status
593 def lower(self, belowThis=None):
594 """Lower this widget in the stacking order."""
595 self.tk.call('lower', self._w, belowThis)
596 def option_add(self, pattern, value, priority = None):
597 """Set a VALUE (second parameter) for an option
598 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000599
Fredrik Lundh06d28152000-08-09 18:03:12 +0000600 An optional third parameter gives the numeric priority
601 (defaults to 80)."""
602 self.tk.call('option', 'add', pattern, value, priority)
603 def option_clear(self):
604 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000605
Fredrik Lundh06d28152000-08-09 18:03:12 +0000606 It will be reloaded if option_add is called."""
607 self.tk.call('option', 'clear')
608 def option_get(self, name, className):
609 """Return the value for an option NAME for this widget
610 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000611
Fredrik Lundh06d28152000-08-09 18:03:12 +0000612 Values with higher priority override lower values."""
613 return self.tk.call('option', 'get', self._w, name, className)
614 def option_readfile(self, fileName, priority = None):
615 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000616
Fredrik Lundh06d28152000-08-09 18:03:12 +0000617 An optional second parameter gives the numeric
618 priority."""
619 self.tk.call('option', 'readfile', fileName, priority)
620 def selection_clear(self, **kw):
621 """Clear the current X selection."""
622 if not kw.has_key('displayof'): kw['displayof'] = self._w
623 self.tk.call(('selection', 'clear') + self._options(kw))
624 def selection_get(self, **kw):
625 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000626
Fredrik Lundh06d28152000-08-09 18:03:12 +0000627 A keyword parameter selection specifies the name of
628 the selection and defaults to PRIMARY. A keyword
629 parameter displayof specifies a widget on the display
630 to use."""
631 if not kw.has_key('displayof'): kw['displayof'] = self._w
632 return self.tk.call(('selection', 'get') + self._options(kw))
633 def selection_handle(self, command, **kw):
634 """Specify a function COMMAND to call if the X
635 selection owned by this widget is queried by another
636 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000637
Fredrik Lundh06d28152000-08-09 18:03:12 +0000638 This function must return the contents of the
639 selection. The function will be called with the
640 arguments OFFSET and LENGTH which allows the chunking
641 of very long selections. The following keyword
642 parameters can be provided:
643 selection - name of the selection (default PRIMARY),
644 type - type of the selection (e.g. STRING, FILE_NAME)."""
645 name = self._register(command)
646 self.tk.call(('selection', 'handle') + self._options(kw)
647 + (self._w, name))
648 def selection_own(self, **kw):
649 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000650
Fredrik Lundh06d28152000-08-09 18:03:12 +0000651 A keyword parameter selection specifies the name of
652 the selection (default PRIMARY)."""
653 self.tk.call(('selection', 'own') +
654 self._options(kw) + (self._w,))
655 def selection_own_get(self, **kw):
656 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000657
Fredrik Lundh06d28152000-08-09 18:03:12 +0000658 The following keyword parameter can
659 be provided:
660 selection - name of the selection (default PRIMARY),
661 type - type of the selection (e.g. STRING, FILE_NAME)."""
662 if not kw.has_key('displayof'): kw['displayof'] = self._w
663 name = self.tk.call(('selection', 'own') + self._options(kw))
664 if not name: return None
665 return self._nametowidget(name)
666 def send(self, interp, cmd, *args):
667 """Send Tcl command CMD to different interpreter INTERP to be executed."""
668 return self.tk.call(('send', interp, cmd) + args)
669 def lower(self, belowThis=None):
670 """Lower this widget in the stacking order."""
671 self.tk.call('lower', self._w, belowThis)
672 def tkraise(self, aboveThis=None):
673 """Raise this widget in the stacking order."""
674 self.tk.call('raise', self._w, aboveThis)
675 lift = tkraise
676 def colormodel(self, value=None):
677 """Useless. Not implemented in Tk."""
678 return self.tk.call('tk', 'colormodel', self._w, value)
679 def winfo_atom(self, name, displayof=0):
680 """Return integer which represents atom NAME."""
681 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
682 return getint(self.tk.call(args))
683 def winfo_atomname(self, id, displayof=0):
684 """Return name of atom with identifier ID."""
685 args = ('winfo', 'atomname') \
686 + self._displayof(displayof) + (id,)
687 return self.tk.call(args)
688 def winfo_cells(self):
689 """Return number of cells in the colormap for this widget."""
690 return getint(
691 self.tk.call('winfo', 'cells', self._w))
692 def winfo_children(self):
693 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000694 result = []
695 for child in self.tk.splitlist(
696 self.tk.call('winfo', 'children', self._w)):
697 try:
698 # Tcl sometimes returns extra windows, e.g. for
699 # menus; those need to be skipped
700 result.append(self._nametowidget(child))
701 except KeyError:
702 pass
703 return result
704
Fredrik Lundh06d28152000-08-09 18:03:12 +0000705 def winfo_class(self):
706 """Return window class name of this widget."""
707 return self.tk.call('winfo', 'class', self._w)
708 def winfo_colormapfull(self):
709 """Return true if at the last color request the colormap was full."""
710 return self.tk.getboolean(
711 self.tk.call('winfo', 'colormapfull', self._w))
712 def winfo_containing(self, rootX, rootY, displayof=0):
713 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
714 args = ('winfo', 'containing') \
715 + self._displayof(displayof) + (rootX, rootY)
716 name = self.tk.call(args)
717 if not name: return None
718 return self._nametowidget(name)
719 def winfo_depth(self):
720 """Return the number of bits per pixel."""
721 return getint(self.tk.call('winfo', 'depth', self._w))
722 def winfo_exists(self):
723 """Return true if this widget exists."""
724 return getint(
725 self.tk.call('winfo', 'exists', self._w))
726 def winfo_fpixels(self, number):
727 """Return the number of pixels for the given distance NUMBER
728 (e.g. "3c") as float."""
729 return getdouble(self.tk.call(
730 'winfo', 'fpixels', self._w, number))
731 def winfo_geometry(self):
732 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
733 return self.tk.call('winfo', 'geometry', self._w)
734 def winfo_height(self):
735 """Return height of this widget."""
736 return getint(
737 self.tk.call('winfo', 'height', self._w))
738 def winfo_id(self):
739 """Return identifier ID for this widget."""
740 return self.tk.getint(
741 self.tk.call('winfo', 'id', self._w))
742 def winfo_interps(self, displayof=0):
743 """Return the name of all Tcl interpreters for this display."""
744 args = ('winfo', 'interps') + self._displayof(displayof)
745 return self.tk.splitlist(self.tk.call(args))
746 def winfo_ismapped(self):
747 """Return true if this widget is mapped."""
748 return getint(
749 self.tk.call('winfo', 'ismapped', self._w))
750 def winfo_manager(self):
751 """Return the window mananger name for this widget."""
752 return self.tk.call('winfo', 'manager', self._w)
753 def winfo_name(self):
754 """Return the name of this widget."""
755 return self.tk.call('winfo', 'name', self._w)
756 def winfo_parent(self):
757 """Return the name of the parent of this widget."""
758 return self.tk.call('winfo', 'parent', self._w)
759 def winfo_pathname(self, id, displayof=0):
760 """Return the pathname of the widget given by ID."""
761 args = ('winfo', 'pathname') \
762 + self._displayof(displayof) + (id,)
763 return self.tk.call(args)
764 def winfo_pixels(self, number):
765 """Rounded integer value of winfo_fpixels."""
766 return getint(
767 self.tk.call('winfo', 'pixels', self._w, number))
768 def winfo_pointerx(self):
769 """Return the x coordinate of the pointer on the root window."""
770 return getint(
771 self.tk.call('winfo', 'pointerx', self._w))
772 def winfo_pointerxy(self):
773 """Return a tuple of x and y coordinates of the pointer on the root window."""
774 return self._getints(
775 self.tk.call('winfo', 'pointerxy', self._w))
776 def winfo_pointery(self):
777 """Return the y coordinate of the pointer on the root window."""
778 return getint(
779 self.tk.call('winfo', 'pointery', self._w))
780 def winfo_reqheight(self):
781 """Return requested height of this widget."""
782 return getint(
783 self.tk.call('winfo', 'reqheight', self._w))
784 def winfo_reqwidth(self):
785 """Return requested width of this widget."""
786 return getint(
787 self.tk.call('winfo', 'reqwidth', self._w))
788 def winfo_rgb(self, color):
789 """Return tuple of decimal values for red, green, blue for
790 COLOR in this widget."""
791 return self._getints(
792 self.tk.call('winfo', 'rgb', self._w, color))
793 def winfo_rootx(self):
794 """Return x coordinate of upper left corner of this widget on the
795 root window."""
796 return getint(
797 self.tk.call('winfo', 'rootx', self._w))
798 def winfo_rooty(self):
799 """Return y coordinate of upper left corner of this widget on the
800 root window."""
801 return getint(
802 self.tk.call('winfo', 'rooty', self._w))
803 def winfo_screen(self):
804 """Return the screen name of this widget."""
805 return self.tk.call('winfo', 'screen', self._w)
806 def winfo_screencells(self):
807 """Return the number of the cells in the colormap of the screen
808 of this widget."""
809 return getint(
810 self.tk.call('winfo', 'screencells', self._w))
811 def winfo_screendepth(self):
812 """Return the number of bits per pixel of the root window of the
813 screen of this widget."""
814 return getint(
815 self.tk.call('winfo', 'screendepth', self._w))
816 def winfo_screenheight(self):
817 """Return the number of pixels of the height of the screen of this widget
818 in pixel."""
819 return getint(
820 self.tk.call('winfo', 'screenheight', self._w))
821 def winfo_screenmmheight(self):
822 """Return the number of pixels of the height of the screen of
823 this widget in mm."""
824 return getint(
825 self.tk.call('winfo', 'screenmmheight', self._w))
826 def winfo_screenmmwidth(self):
827 """Return the number of pixels of the width of the screen of
828 this widget in mm."""
829 return getint(
830 self.tk.call('winfo', 'screenmmwidth', self._w))
831 def winfo_screenvisual(self):
832 """Return one of the strings directcolor, grayscale, pseudocolor,
833 staticcolor, staticgray, or truecolor for the default
834 colormodel of this screen."""
835 return self.tk.call('winfo', 'screenvisual', self._w)
836 def winfo_screenwidth(self):
837 """Return the number of pixels of the width of the screen of
838 this widget in pixel."""
839 return getint(
840 self.tk.call('winfo', 'screenwidth', self._w))
841 def winfo_server(self):
842 """Return information of the X-Server of the screen of this widget in
843 the form "XmajorRminor vendor vendorVersion"."""
844 return self.tk.call('winfo', 'server', self._w)
845 def winfo_toplevel(self):
846 """Return the toplevel widget of this widget."""
847 return self._nametowidget(self.tk.call(
848 'winfo', 'toplevel', self._w))
849 def winfo_viewable(self):
850 """Return true if the widget and all its higher ancestors are mapped."""
851 return getint(
852 self.tk.call('winfo', 'viewable', self._w))
853 def winfo_visual(self):
854 """Return one of the strings directcolor, grayscale, pseudocolor,
855 staticcolor, staticgray, or truecolor for the
856 colormodel of this widget."""
857 return self.tk.call('winfo', 'visual', self._w)
858 def winfo_visualid(self):
859 """Return the X identifier for the visual for this widget."""
860 return self.tk.call('winfo', 'visualid', self._w)
861 def winfo_visualsavailable(self, includeids=0):
862 """Return a list of all visuals available for the screen
863 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000864
Fredrik Lundh06d28152000-08-09 18:03:12 +0000865 Each item in the list consists of a visual name (see winfo_visual), a
866 depth and if INCLUDEIDS=1 is given also the X identifier."""
867 data = self.tk.split(
868 self.tk.call('winfo', 'visualsavailable', self._w,
869 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000870 if type(data) is StringType:
871 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000872 return map(self.__winfo_parseitem, data)
873 def __winfo_parseitem(self, t):
874 """Internal function."""
875 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
876 def __winfo_getint(self, x):
877 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000878 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000879 def winfo_vrootheight(self):
880 """Return the height of the virtual root window associated with this
881 widget in pixels. If there is no virtual root window return the
882 height of the screen."""
883 return getint(
884 self.tk.call('winfo', 'vrootheight', self._w))
885 def winfo_vrootwidth(self):
886 """Return the width of the virtual root window associated with this
887 widget in pixel. If there is no virtual root window return the
888 width of the screen."""
889 return getint(
890 self.tk.call('winfo', 'vrootwidth', self._w))
891 def winfo_vrootx(self):
892 """Return the x offset of the virtual root relative to the root
893 window of the screen of this widget."""
894 return getint(
895 self.tk.call('winfo', 'vrootx', self._w))
896 def winfo_vrooty(self):
897 """Return the y offset of the virtual root relative to the root
898 window of the screen of this widget."""
899 return getint(
900 self.tk.call('winfo', 'vrooty', self._w))
901 def winfo_width(self):
902 """Return the width of this widget."""
903 return getint(
904 self.tk.call('winfo', 'width', self._w))
905 def winfo_x(self):
906 """Return the x coordinate of the upper left corner of this widget
907 in the parent."""
908 return getint(
909 self.tk.call('winfo', 'x', self._w))
910 def winfo_y(self):
911 """Return the y coordinate of the upper left corner of this widget
912 in the parent."""
913 return getint(
914 self.tk.call('winfo', 'y', self._w))
915 def update(self):
916 """Enter event loop until all pending events have been processed by Tcl."""
917 self.tk.call('update')
918 def update_idletasks(self):
919 """Enter event loop until all idle callbacks have been called. This
920 will update the display of windows but not process events caused by
921 the user."""
922 self.tk.call('update', 'idletasks')
923 def bindtags(self, tagList=None):
924 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000925
Fredrik Lundh06d28152000-08-09 18:03:12 +0000926 With no argument return the list of all bindtags associated with
927 this widget. With a list of strings as argument the bindtags are
928 set to this list. The bindtags determine in which order events are
929 processed (see bind)."""
930 if tagList is None:
931 return self.tk.splitlist(
932 self.tk.call('bindtags', self._w))
933 else:
934 self.tk.call('bindtags', self._w, tagList)
935 def _bind(self, what, sequence, func, add, needcleanup=1):
936 """Internal function."""
937 if type(func) is StringType:
938 self.tk.call(what + (sequence, func))
939 elif func:
940 funcid = self._register(func, self._substitute,
941 needcleanup)
942 cmd = ('%sif {"[%s %s]" == "break"} break\n'
943 %
944 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000945 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000946 self.tk.call(what + (sequence, cmd))
947 return funcid
948 elif sequence:
949 return self.tk.call(what + (sequence,))
950 else:
951 return self.tk.splitlist(self.tk.call(what))
952 def bind(self, sequence=None, func=None, add=None):
953 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000954
Fredrik Lundh06d28152000-08-09 18:03:12 +0000955 SEQUENCE is a string of concatenated event
956 patterns. An event pattern is of the form
957 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
958 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
959 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
960 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
961 Mod1, M1. TYPE is one of Activate, Enter, Map,
962 ButtonPress, Button, Expose, Motion, ButtonRelease
963 FocusIn, MouseWheel, Circulate, FocusOut, Property,
964 Colormap, Gravity Reparent, Configure, KeyPress, Key,
965 Unmap, Deactivate, KeyRelease Visibility, Destroy,
966 Leave and DETAIL is the button number for ButtonPress,
967 ButtonRelease and DETAIL is the Keysym for KeyPress and
968 KeyRelease. Examples are
969 <Control-Button-1> for pressing Control and mouse button 1 or
970 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
971 An event pattern can also be a virtual event of the form
972 <<AString>> where AString can be arbitrary. This
973 event can be generated by event_generate.
974 If events are concatenated they must appear shortly
975 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000976
Fredrik Lundh06d28152000-08-09 18:03:12 +0000977 FUNC will be called if the event sequence occurs with an
978 instance of Event as argument. If the return value of FUNC is
979 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000980
Fredrik Lundh06d28152000-08-09 18:03:12 +0000981 An additional boolean parameter ADD specifies whether FUNC will
982 be called additionally to the other bound function or whether
983 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000984
Fredrik Lundh06d28152000-08-09 18:03:12 +0000985 Bind will return an identifier to allow deletion of the bound function with
986 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000987
Fredrik Lundh06d28152000-08-09 18:03:12 +0000988 If FUNC or SEQUENCE is omitted the bound function or list
989 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000990
Fredrik Lundh06d28152000-08-09 18:03:12 +0000991 return self._bind(('bind', self._w), sequence, func, add)
992 def unbind(self, sequence, funcid=None):
993 """Unbind for this widget for event SEQUENCE the
994 function identified with FUNCID."""
995 self.tk.call('bind', self._w, sequence, '')
996 if funcid:
997 self.deletecommand(funcid)
998 def bind_all(self, sequence=None, func=None, add=None):
999 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1000 An additional boolean parameter ADD specifies whether FUNC will
1001 be called additionally to the other bound function or whether
1002 it will replace the previous function. See bind for the return value."""
1003 return self._bind(('bind', 'all'), sequence, func, add, 0)
1004 def unbind_all(self, sequence):
1005 """Unbind for all widgets for event SEQUENCE all functions."""
1006 self.tk.call('bind', 'all' , sequence, '')
1007 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001008
Fredrik Lundh06d28152000-08-09 18:03:12 +00001009 """Bind to widgets with bindtag CLASSNAME at event
1010 SEQUENCE a call of function FUNC. An additional
1011 boolean parameter ADD specifies whether FUNC will be
1012 called additionally to the other bound function or
1013 whether it will replace the previous function. See bind for
1014 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001015
Fredrik Lundh06d28152000-08-09 18:03:12 +00001016 return self._bind(('bind', className), sequence, func, add, 0)
1017 def unbind_class(self, className, sequence):
1018 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1019 all functions."""
1020 self.tk.call('bind', className , sequence, '')
1021 def mainloop(self, n=0):
1022 """Call the mainloop of Tk."""
1023 self.tk.mainloop(n)
1024 def quit(self):
1025 """Quit the Tcl interpreter. All widgets will be destroyed."""
1026 self.tk.quit()
1027 def _getints(self, string):
1028 """Internal function."""
1029 if string:
1030 return tuple(map(getint, self.tk.splitlist(string)))
1031 def _getdoubles(self, string):
1032 """Internal function."""
1033 if string:
1034 return tuple(map(getdouble, self.tk.splitlist(string)))
1035 def _getboolean(self, string):
1036 """Internal function."""
1037 if string:
1038 return self.tk.getboolean(string)
1039 def _displayof(self, displayof):
1040 """Internal function."""
1041 if displayof:
1042 return ('-displayof', displayof)
1043 if displayof is None:
1044 return ('-displayof', self._w)
1045 return ()
1046 def _options(self, cnf, kw = None):
1047 """Internal function."""
1048 if kw:
1049 cnf = _cnfmerge((cnf, kw))
1050 else:
1051 cnf = _cnfmerge(cnf)
1052 res = ()
1053 for k, v in cnf.items():
1054 if v is not None:
1055 if k[-1] == '_': k = k[:-1]
1056 if callable(v):
1057 v = self._register(v)
1058 res = res + ('-'+k, v)
1059 return res
1060 def nametowidget(self, name):
1061 """Return the Tkinter instance of a widget identified by
1062 its Tcl name NAME."""
1063 w = self
1064 if name[0] == '.':
1065 w = w._root()
1066 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001067 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +00001068 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001069 if i >= 0:
1070 name, tail = name[:i], name[i+1:]
1071 else:
1072 tail = ''
1073 w = w.children[name]
1074 name = tail
1075 return w
1076 _nametowidget = nametowidget
1077 def _register(self, func, subst=None, needcleanup=1):
1078 """Return a newly created Tcl function. If this
1079 function is called, the Python function FUNC will
1080 be executed. An optional function SUBST can
1081 be given which will be executed before FUNC."""
1082 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001083 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001084 try:
1085 func = func.im_func
1086 except AttributeError:
1087 pass
1088 try:
1089 name = name + func.__name__
1090 except AttributeError:
1091 pass
1092 self.tk.createcommand(name, f)
1093 if needcleanup:
1094 if self._tclCommands is None:
1095 self._tclCommands = []
1096 self._tclCommands.append(name)
1097 #print '+ Tkinter created command', name
1098 return name
1099 register = _register
1100 def _root(self):
1101 """Internal function."""
1102 w = self
1103 while w.master: w = w.master
1104 return w
1105 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1106 '%s', '%t', '%w', '%x', '%y',
1107 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001108 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001109 def _substitute(self, *args):
1110 """Internal function."""
1111 if len(args) != len(self._subst_format): return args
1112 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001113
Fredrik Lundh06d28152000-08-09 18:03:12 +00001114 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001115 def getint_event(s):
1116 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1117 try:
1118 return int(s)
1119 except ValueError:
1120 return s
1121
Fredrik Lundh06d28152000-08-09 18:03:12 +00001122 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1123 # Missing: (a, c, d, m, o, v, B, R)
1124 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001125 # serial field: valid vor all events
1126 # number of button: ButtonPress and ButtonRelease events only
1127 # height field: Configure, ConfigureRequest, Create,
1128 # ResizeRequest, and Expose events only
1129 # keycode field: KeyPress and KeyRelease events only
1130 # time field: "valid for events that contain a time field"
1131 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1132 # and Expose events only
1133 # x field: "valid for events that contain a x field"
1134 # y field: "valid for events that contain a y field"
1135 # keysym as decimal: KeyPress and KeyRelease events only
1136 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1137 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001138 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001139 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001140 try: e.focus = getboolean(f)
1141 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001142 e.height = getint_event(h)
1143 e.keycode = getint_event(k)
1144 e.state = getint_event(s)
1145 e.time = getint_event(t)
1146 e.width = getint_event(w)
1147 e.x = getint_event(x)
1148 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001149 e.char = A
1150 try: e.send_event = getboolean(E)
1151 except TclError: pass
1152 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001153 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001154 e.type = T
1155 try:
1156 e.widget = self._nametowidget(W)
1157 except KeyError:
1158 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001159 e.x_root = getint_event(X)
1160 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001161 try:
1162 e.delta = getint(D)
1163 except ValueError:
1164 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001165 return (e,)
1166 def _report_exception(self):
1167 """Internal function."""
1168 import sys
1169 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1170 root = self._root()
1171 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001172 def _configure(self, cmd, cnf, kw):
1173 """Internal function."""
1174 if kw:
1175 cnf = _cnfmerge((cnf, kw))
1176 elif cnf:
1177 cnf = _cnfmerge(cnf)
1178 if cnf is None:
1179 cnf = {}
1180 for x in self.tk.split(
1181 self.tk.call(_flatten((self._w, cmd)))):
1182 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1183 return cnf
1184 if type(cnf) is StringType:
1185 x = self.tk.split(
1186 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1187 return (x[0][1:],) + x[1:]
1188 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001189 # These used to be defined in Widget:
1190 def configure(self, cnf=None, **kw):
1191 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001192
Fredrik Lundh06d28152000-08-09 18:03:12 +00001193 The values for resources are specified as keyword
1194 arguments. To get an overview about
1195 the allowed keyword arguments call the method keys.
1196 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001197 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001198 config = configure
1199 def cget(self, key):
1200 """Return the resource value for a KEY given as string."""
1201 return self.tk.call(self._w, 'cget', '-' + key)
1202 __getitem__ = cget
1203 def __setitem__(self, key, value):
1204 self.configure({key: value})
1205 def keys(self):
1206 """Return a list of all resource names of this widget."""
1207 return map(lambda x: x[0][1:],
1208 self.tk.split(self.tk.call(self._w, 'configure')))
1209 def __str__(self):
1210 """Return the window path name of this widget."""
1211 return self._w
1212 # Pack methods that apply to the master
1213 _noarg_ = ['_noarg_']
1214 def pack_propagate(self, flag=_noarg_):
1215 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001216
Fredrik Lundh06d28152000-08-09 18:03:12 +00001217 A boolean argument specifies whether the geometry information
1218 of the slaves will determine the size of this widget. If no argument
1219 is given the current setting will be returned.
1220 """
1221 if flag is Misc._noarg_:
1222 return self._getboolean(self.tk.call(
1223 'pack', 'propagate', self._w))
1224 else:
1225 self.tk.call('pack', 'propagate', self._w, flag)
1226 propagate = pack_propagate
1227 def pack_slaves(self):
1228 """Return a list of all slaves of this widget
1229 in its packing order."""
1230 return map(self._nametowidget,
1231 self.tk.splitlist(
1232 self.tk.call('pack', 'slaves', self._w)))
1233 slaves = pack_slaves
1234 # Place method that applies to the master
1235 def place_slaves(self):
1236 """Return a list of all slaves of this widget
1237 in its packing order."""
1238 return map(self._nametowidget,
1239 self.tk.splitlist(
1240 self.tk.call(
1241 'place', 'slaves', self._w)))
1242 # Grid methods that apply to the master
1243 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1244 """Return a tuple of integer coordinates for the bounding
1245 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001246
Fredrik Lundh06d28152000-08-09 18:03:12 +00001247 If COLUMN, ROW is given the bounding box applies from
1248 the cell with row and column 0 to the specified
1249 cell. If COL2 and ROW2 are given the bounding box
1250 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001251
Fredrik Lundh06d28152000-08-09 18:03:12 +00001252 The returned integers specify the offset of the upper left
1253 corner in the master widget and the width and height.
1254 """
1255 args = ('grid', 'bbox', self._w)
1256 if column is not None and row is not None:
1257 args = args + (column, row)
1258 if col2 is not None and row2 is not None:
1259 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001260 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001261
Fredrik Lundh06d28152000-08-09 18:03:12 +00001262 bbox = grid_bbox
1263 def _grid_configure(self, command, index, cnf, kw):
1264 """Internal function."""
1265 if type(cnf) is StringType and not kw:
1266 if cnf[-1:] == '_':
1267 cnf = cnf[:-1]
1268 if cnf[:1] != '-':
1269 cnf = '-'+cnf
1270 options = (cnf,)
1271 else:
1272 options = self._options(cnf, kw)
1273 if not options:
1274 res = self.tk.call('grid',
1275 command, self._w, index)
1276 words = self.tk.splitlist(res)
1277 dict = {}
1278 for i in range(0, len(words), 2):
1279 key = words[i][1:]
1280 value = words[i+1]
1281 if not value:
1282 value = None
1283 elif '.' in value:
1284 value = getdouble(value)
1285 else:
1286 value = getint(value)
1287 dict[key] = value
1288 return dict
1289 res = self.tk.call(
1290 ('grid', command, self._w, index)
1291 + options)
1292 if len(options) == 1:
1293 if not res: return None
1294 # In Tk 7.5, -width can be a float
1295 if '.' in res: return getdouble(res)
1296 return getint(res)
1297 def grid_columnconfigure(self, index, cnf={}, **kw):
1298 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001299
Fredrik Lundh06d28152000-08-09 18:03:12 +00001300 Valid resources are minsize (minimum size of the column),
1301 weight (how much does additional space propagate to this column)
1302 and pad (how much space to let additionally)."""
1303 return self._grid_configure('columnconfigure', index, cnf, kw)
1304 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001305 def grid_location(self, x, y):
1306 """Return a tuple of column and row which identify the cell
1307 at which the pixel at position X and Y inside the master
1308 widget is located."""
1309 return self._getints(
1310 self.tk.call(
1311 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001312 def grid_propagate(self, flag=_noarg_):
1313 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001314
Fredrik Lundh06d28152000-08-09 18:03:12 +00001315 A boolean argument specifies whether the geometry information
1316 of the slaves will determine the size of this widget. If no argument
1317 is given, the current setting will be returned.
1318 """
1319 if flag is Misc._noarg_:
1320 return self._getboolean(self.tk.call(
1321 'grid', 'propagate', self._w))
1322 else:
1323 self.tk.call('grid', 'propagate', self._w, flag)
1324 def grid_rowconfigure(self, index, cnf={}, **kw):
1325 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001326
Fredrik Lundh06d28152000-08-09 18:03:12 +00001327 Valid resources are minsize (minimum size of the row),
1328 weight (how much does additional space propagate to this row)
1329 and pad (how much space to let additionally)."""
1330 return self._grid_configure('rowconfigure', index, cnf, kw)
1331 rowconfigure = grid_rowconfigure
1332 def grid_size(self):
1333 """Return a tuple of the number of column and rows in the grid."""
1334 return self._getints(
1335 self.tk.call('grid', 'size', self._w)) or None
1336 size = grid_size
1337 def grid_slaves(self, row=None, column=None):
1338 """Return a list of all slaves of this widget
1339 in its packing order."""
1340 args = ()
1341 if row is not None:
1342 args = args + ('-row', row)
1343 if column is not None:
1344 args = args + ('-column', column)
1345 return map(self._nametowidget,
1346 self.tk.splitlist(self.tk.call(
1347 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001348
Fredrik Lundh06d28152000-08-09 18:03:12 +00001349 # Support for the "event" command, new in Tk 4.2.
1350 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001351
Fredrik Lundh06d28152000-08-09 18:03:12 +00001352 def event_add(self, virtual, *sequences):
1353 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1354 to an event SEQUENCE such that the virtual event is triggered
1355 whenever SEQUENCE occurs."""
1356 args = ('event', 'add', virtual) + sequences
1357 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001358
Fredrik Lundh06d28152000-08-09 18:03:12 +00001359 def event_delete(self, virtual, *sequences):
1360 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1361 args = ('event', 'delete', virtual) + sequences
1362 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001363
Fredrik Lundh06d28152000-08-09 18:03:12 +00001364 def event_generate(self, sequence, **kw):
1365 """Generate an event SEQUENCE. Additional
1366 keyword arguments specify parameter of the event
1367 (e.g. x, y, rootx, rooty)."""
1368 args = ('event', 'generate', self._w, sequence)
1369 for k, v in kw.items():
1370 args = args + ('-%s' % k, str(v))
1371 self.tk.call(args)
1372
1373 def event_info(self, virtual=None):
1374 """Return a list of all virtual events or the information
1375 about the SEQUENCE bound to the virtual event VIRTUAL."""
1376 return self.tk.splitlist(
1377 self.tk.call('event', 'info', virtual))
1378
1379 # Image related commands
1380
1381 def image_names(self):
1382 """Return a list of all existing image names."""
1383 return self.tk.call('image', 'names')
1384
1385 def image_types(self):
1386 """Return a list of all available image types (e.g. phote bitmap)."""
1387 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001388
Guido van Rossum80f8be81997-12-02 19:51:39 +00001389
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001390class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001391 """Internal class. Stores function to call when some user
1392 defined Tcl function is called e.g. after an event occurred."""
1393 def __init__(self, func, subst, widget):
1394 """Store FUNC, SUBST and WIDGET as members."""
1395 self.func = func
1396 self.subst = subst
1397 self.widget = widget
1398 def __call__(self, *args):
1399 """Apply first function SUBST to arguments, than FUNC."""
1400 try:
1401 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001402 args = self.subst(*args)
1403 return self.func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001404 except SystemExit, msg:
1405 raise SystemExit, msg
1406 except:
1407 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001408
Guido van Rossume365a591998-05-01 19:48:20 +00001409
Guido van Rossum18468821994-06-20 07:49:28 +00001410class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001411 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001412
Fredrik Lundh06d28152000-08-09 18:03:12 +00001413 def wm_aspect(self,
1414 minNumer=None, minDenom=None,
1415 maxNumer=None, maxDenom=None):
1416 """Instruct the window manager to set the aspect ratio (width/height)
1417 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1418 of the actual values if no argument is given."""
1419 return self._getints(
1420 self.tk.call('wm', 'aspect', self._w,
1421 minNumer, minDenom,
1422 maxNumer, maxDenom))
1423 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001424
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001425 def wm_attributes(self, *args):
1426 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001427
1428 The first form returns a list of the platform specific flags and
1429 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001430 option. The third form sets one or more of the values. The values
1431 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001432
1433 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001434 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001435 to toolwindow (as defined in the MSDN). -topmost gets or sets
1436 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001437 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001438
1439 On Macintosh, XXXXX
1440
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001441 On Unix, there are currently no special attribute values.
1442 """
1443 args = ('wm', 'attributes', self._w) + args
1444 return self.tk.call(args)
1445 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001446
Fredrik Lundh06d28152000-08-09 18:03:12 +00001447 def wm_client(self, name=None):
1448 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1449 current value."""
1450 return self.tk.call('wm', 'client', self._w, name)
1451 client = wm_client
1452 def wm_colormapwindows(self, *wlist):
1453 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1454 of this widget. This list contains windows whose colormaps differ from their
1455 parents. Return current list of widgets if WLIST is empty."""
1456 if len(wlist) > 1:
1457 wlist = (wlist,) # Tk needs a list of windows here
1458 args = ('wm', 'colormapwindows', self._w) + wlist
1459 return map(self._nametowidget, self.tk.call(args))
1460 colormapwindows = wm_colormapwindows
1461 def wm_command(self, value=None):
1462 """Store VALUE in WM_COMMAND property. It is the command
1463 which shall be used to invoke the application. Return current
1464 command if VALUE is None."""
1465 return self.tk.call('wm', 'command', self._w, value)
1466 command = wm_command
1467 def wm_deiconify(self):
1468 """Deiconify this widget. If it was never mapped it will not be mapped.
1469 On Windows it will raise this widget and give it the focus."""
1470 return self.tk.call('wm', 'deiconify', self._w)
1471 deiconify = wm_deiconify
1472 def wm_focusmodel(self, model=None):
1473 """Set focus model to MODEL. "active" means that this widget will claim
1474 the focus itself, "passive" means that the window manager shall give
1475 the focus. Return current focus model if MODEL is None."""
1476 return self.tk.call('wm', 'focusmodel', self._w, model)
1477 focusmodel = wm_focusmodel
1478 def wm_frame(self):
1479 """Return identifier for decorative frame of this widget if present."""
1480 return self.tk.call('wm', 'frame', self._w)
1481 frame = wm_frame
1482 def wm_geometry(self, newGeometry=None):
1483 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1484 current value if None is given."""
1485 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1486 geometry = wm_geometry
1487 def wm_grid(self,
1488 baseWidth=None, baseHeight=None,
1489 widthInc=None, heightInc=None):
1490 """Instruct the window manager that this widget shall only be
1491 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1492 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1493 number of grid units requested in Tk_GeometryRequest."""
1494 return self._getints(self.tk.call(
1495 'wm', 'grid', self._w,
1496 baseWidth, baseHeight, widthInc, heightInc))
1497 grid = wm_grid
1498 def wm_group(self, pathName=None):
1499 """Set the group leader widgets for related widgets to PATHNAME. Return
1500 the group leader of this widget if None is given."""
1501 return self.tk.call('wm', 'group', self._w, pathName)
1502 group = wm_group
1503 def wm_iconbitmap(self, bitmap=None):
1504 """Set bitmap for the iconified widget to BITMAP. Return
1505 the bitmap if None is given."""
1506 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1507 iconbitmap = wm_iconbitmap
1508 def wm_iconify(self):
1509 """Display widget as icon."""
1510 return self.tk.call('wm', 'iconify', self._w)
1511 iconify = wm_iconify
1512 def wm_iconmask(self, bitmap=None):
1513 """Set mask for the icon bitmap of this widget. Return the
1514 mask if None is given."""
1515 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1516 iconmask = wm_iconmask
1517 def wm_iconname(self, newName=None):
1518 """Set the name of the icon for this widget. Return the name if
1519 None is given."""
1520 return self.tk.call('wm', 'iconname', self._w, newName)
1521 iconname = wm_iconname
1522 def wm_iconposition(self, x=None, y=None):
1523 """Set the position of the icon of this widget to X and Y. Return
1524 a tuple of the current values of X and X if None is given."""
1525 return self._getints(self.tk.call(
1526 'wm', 'iconposition', self._w, x, y))
1527 iconposition = wm_iconposition
1528 def wm_iconwindow(self, pathName=None):
1529 """Set widget PATHNAME to be displayed instead of icon. Return the current
1530 value if None is given."""
1531 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1532 iconwindow = wm_iconwindow
1533 def wm_maxsize(self, width=None, height=None):
1534 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1535 the values are given in grid units. Return the current values if None
1536 is given."""
1537 return self._getints(self.tk.call(
1538 'wm', 'maxsize', self._w, width, height))
1539 maxsize = wm_maxsize
1540 def wm_minsize(self, width=None, height=None):
1541 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1542 the values are given in grid units. Return the current values if None
1543 is given."""
1544 return self._getints(self.tk.call(
1545 'wm', 'minsize', self._w, width, height))
1546 minsize = wm_minsize
1547 def wm_overrideredirect(self, boolean=None):
1548 """Instruct the window manager to ignore this widget
1549 if BOOLEAN is given with 1. Return the current value if None
1550 is given."""
1551 return self._getboolean(self.tk.call(
1552 'wm', 'overrideredirect', self._w, boolean))
1553 overrideredirect = wm_overrideredirect
1554 def wm_positionfrom(self, who=None):
1555 """Instruct the window manager that the position of this widget shall
1556 be defined by the user if WHO is "user", and by its own policy if WHO is
1557 "program"."""
1558 return self.tk.call('wm', 'positionfrom', self._w, who)
1559 positionfrom = wm_positionfrom
1560 def wm_protocol(self, name=None, func=None):
1561 """Bind function FUNC to command NAME for this widget.
1562 Return the function bound to NAME if None is given. NAME could be
1563 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1564 if callable(func):
1565 command = self._register(func)
1566 else:
1567 command = func
1568 return self.tk.call(
1569 'wm', 'protocol', self._w, name, command)
1570 protocol = wm_protocol
1571 def wm_resizable(self, width=None, height=None):
1572 """Instruct the window manager whether this width can be resized
1573 in WIDTH or HEIGHT. Both values are boolean values."""
1574 return self.tk.call('wm', 'resizable', self._w, width, height)
1575 resizable = wm_resizable
1576 def wm_sizefrom(self, who=None):
1577 """Instruct the window manager that the size of this widget shall
1578 be defined by the user if WHO is "user", and by its own policy if WHO is
1579 "program"."""
1580 return self.tk.call('wm', 'sizefrom', self._w, who)
1581 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001582 def wm_state(self, newstate=None):
1583 """Query or set the state of this widget as one of normal, icon,
1584 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1585 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001586 state = wm_state
1587 def wm_title(self, string=None):
1588 """Set the title of this widget."""
1589 return self.tk.call('wm', 'title', self._w, string)
1590 title = wm_title
1591 def wm_transient(self, master=None):
1592 """Instruct the window manager that this widget is transient
1593 with regard to widget MASTER."""
1594 return self.tk.call('wm', 'transient', self._w, master)
1595 transient = wm_transient
1596 def wm_withdraw(self):
1597 """Withdraw this widget from the screen such that it is unmapped
1598 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1599 return self.tk.call('wm', 'withdraw', self._w)
1600 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001601
Guido van Rossum18468821994-06-20 07:49:28 +00001602
1603class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001604 """Toplevel widget of Tk which represents mostly the main window
1605 of an appliation. It has an associated Tcl interpreter."""
1606 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001607 def __init__(self, screenName=None, baseName=None, className='Tk',
1608 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001609 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1610 be created. BASENAME will be used for the identification of the profile file (see
1611 readprofile).
1612 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1613 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001614 self.master = None
1615 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001616 self._tkloaded = 0
1617 # to avoid recursions in the getattr code in case of failure, we
1618 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001619 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001620 if baseName is None:
1621 import sys, os
1622 baseName = os.path.basename(sys.argv[0])
1623 baseName, ext = os.path.splitext(baseName)
1624 if ext not in ('.py', '.pyc', '.pyo'):
1625 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001626 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001627 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001628 if useTk:
1629 self._loadtk()
1630 self.readprofile(baseName, className)
1631 def loadtk(self):
1632 if not self._tkloaded:
1633 self.tk.loadtk()
1634 self._loadtk()
1635 def _loadtk(self):
1636 self._tkloaded = 1
1637 global _default_root
Jack Jansenbe92af02001-08-23 13:25:59 +00001638 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001639 # Disable event scanning except for Command-Period
1640 _MacOS.SchedParams(1, 0)
1641 # Work around nasty MacTk bug
1642 # XXX Is this one still needed?
1643 self.update()
1644 # Version sanity checks
1645 tk_version = self.tk.getvar('tk_version')
1646 if tk_version != _tkinter.TK_VERSION:
1647 raise RuntimeError, \
1648 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1649 % (_tkinter.TK_VERSION, tk_version)
Martin v. Löwis54895972003-05-24 11:37:15 +00001650 # Under unknown circumstances, tcl_version gets coerced to float
1651 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001652 if tcl_version != _tkinter.TCL_VERSION:
1653 raise RuntimeError, \
1654 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1655 % (_tkinter.TCL_VERSION, tcl_version)
1656 if TkVersion < 4.0:
1657 raise RuntimeError, \
1658 "Tk 4.0 or higher is required; found Tk %s" \
1659 % str(TkVersion)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001660 # Create and register the tkerror and exit commands
1661 # We need to inline parts of _register here, _ register
1662 # would register differently-named commands.
1663 if self._tclCommands is None:
1664 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001665 self.tk.createcommand('tkerror', _tkerror)
1666 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001667 self._tclCommands.append('tkerror')
1668 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001669 if _support_default_root and not _default_root:
1670 _default_root = self
1671 self.protocol("WM_DELETE_WINDOW", self.destroy)
1672 def destroy(self):
1673 """Destroy this and all descendants widgets. This will
1674 end the application of this Tcl interpreter."""
1675 for c in self.children.values(): c.destroy()
1676 self.tk.call('destroy', self._w)
1677 Misc.destroy(self)
1678 global _default_root
1679 if _support_default_root and _default_root is self:
1680 _default_root = None
1681 def readprofile(self, baseName, className):
1682 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1683 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1684 such a file exists in the home directory."""
1685 import os
1686 if os.environ.has_key('HOME'): home = os.environ['HOME']
1687 else: home = os.curdir
1688 class_tcl = os.path.join(home, '.%s.tcl' % className)
1689 class_py = os.path.join(home, '.%s.py' % className)
1690 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1691 base_py = os.path.join(home, '.%s.py' % baseName)
1692 dir = {'self': self}
1693 exec 'from Tkinter import *' in dir
1694 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001695 self.tk.call('source', class_tcl)
1696 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001697 execfile(class_py, dir)
1698 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001699 self.tk.call('source', base_tcl)
1700 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001701 execfile(base_py, dir)
1702 def report_callback_exception(self, exc, val, tb):
1703 """Internal function. It reports exception on sys.stderr."""
1704 import traceback, sys
1705 sys.stderr.write("Exception in Tkinter callback\n")
1706 sys.last_type = exc
1707 sys.last_value = val
1708 sys.last_traceback = tb
1709 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001710 def __getattr__(self, attr):
1711 "Delegate attribute access to the interpreter object"
1712 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001713
Guido van Rossum368e06b1997-11-07 20:38:49 +00001714# Ideally, the classes Pack, Place and Grid disappear, the
1715# pack/place/grid methods are defined on the Widget class, and
1716# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1717# ...), with pack(), place() and grid() being short for
1718# pack_configure(), place_configure() and grid_columnconfigure(), and
1719# forget() being short for pack_forget(). As a practical matter, I'm
1720# afraid that there is too much code out there that may be using the
1721# Pack, Place or Grid class, so I leave them intact -- but only as
1722# backwards compatibility features. Also note that those methods that
1723# take a master as argument (e.g. pack_propagate) have been moved to
1724# the Misc class (which now incorporates all methods common between
1725# toplevel and interior widgets). Again, for compatibility, these are
1726# copied into the Pack, Place or Grid class.
1727
David Aschere2b4b322004-02-18 05:59:53 +00001728
1729def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1730 return Tk(screenName, baseName, className, useTk)
1731
Guido van Rossum18468821994-06-20 07:49:28 +00001732class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001733 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001734
Fredrik Lundh06d28152000-08-09 18:03:12 +00001735 Base class to use the methods pack_* in every widget."""
1736 def pack_configure(self, cnf={}, **kw):
1737 """Pack a widget in the parent widget. Use as options:
1738 after=widget - pack it after you have packed widget
1739 anchor=NSEW (or subset) - position widget according to
1740 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001741 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001742 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001743 fill=NONE or X or Y or BOTH - fill widget if widget grows
1744 in=master - use master to contain this widget
1745 ipadx=amount - add internal padding in x direction
1746 ipady=amount - add internal padding in y direction
1747 padx=amount - add padding in x direction
1748 pady=amount - add padding in y direction
1749 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1750 """
1751 self.tk.call(
1752 ('pack', 'configure', self._w)
1753 + self._options(cnf, kw))
1754 pack = configure = config = pack_configure
1755 def pack_forget(self):
1756 """Unmap this widget and do not use it for the packing order."""
1757 self.tk.call('pack', 'forget', self._w)
1758 forget = pack_forget
1759 def pack_info(self):
1760 """Return information about the packing options
1761 for this widget."""
1762 words = self.tk.splitlist(
1763 self.tk.call('pack', 'info', self._w))
1764 dict = {}
1765 for i in range(0, len(words), 2):
1766 key = words[i][1:]
1767 value = words[i+1]
1768 if value[:1] == '.':
1769 value = self._nametowidget(value)
1770 dict[key] = value
1771 return dict
1772 info = pack_info
1773 propagate = pack_propagate = Misc.pack_propagate
1774 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001775
1776class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001777 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001778
Fredrik Lundh06d28152000-08-09 18:03:12 +00001779 Base class to use the methods place_* in every widget."""
1780 def place_configure(self, cnf={}, **kw):
1781 """Place a widget in the parent widget. Use as options:
1782 in=master - master relative to which the widget is placed.
1783 x=amount - locate anchor of this widget at position x of master
1784 y=amount - locate anchor of this widget at position y of master
1785 relx=amount - locate anchor of this widget between 0.0 and 1.0
1786 relative to width of master (1.0 is right edge)
1787 rely=amount - locate anchor of this widget between 0.0 and 1.0
1788 relative to height of master (1.0 is bottom edge)
1789 anchor=NSEW (or subset) - position anchor according to given direction
1790 width=amount - width of this widget in pixel
1791 height=amount - height of this widget in pixel
1792 relwidth=amount - width of this widget between 0.0 and 1.0
1793 relative to width of master (1.0 is the same width
1794 as the master)
1795 relheight=amount - height of this widget between 0.0 and 1.0
1796 relative to height of master (1.0 is the same
1797 height as the master)
1798 bordermode="inside" or "outside" - whether to take border width of master widget
1799 into account
1800 """
1801 for k in ['in_']:
1802 if kw.has_key(k):
1803 kw[k[:-1]] = kw[k]
1804 del kw[k]
1805 self.tk.call(
1806 ('place', 'configure', self._w)
1807 + self._options(cnf, kw))
1808 place = configure = config = place_configure
1809 def place_forget(self):
1810 """Unmap this widget."""
1811 self.tk.call('place', 'forget', self._w)
1812 forget = place_forget
1813 def place_info(self):
1814 """Return information about the placing options
1815 for this widget."""
1816 words = self.tk.splitlist(
1817 self.tk.call('place', 'info', self._w))
1818 dict = {}
1819 for i in range(0, len(words), 2):
1820 key = words[i][1:]
1821 value = words[i+1]
1822 if value[:1] == '.':
1823 value = self._nametowidget(value)
1824 dict[key] = value
1825 return dict
1826 info = place_info
1827 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001828
Guido van Rossum37dcab11996-05-16 16:00:19 +00001829class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001830 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001831
Fredrik Lundh06d28152000-08-09 18:03:12 +00001832 Base class to use the methods grid_* in every widget."""
1833 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1834 def grid_configure(self, cnf={}, **kw):
1835 """Position a widget in the parent widget in a grid. Use as options:
1836 column=number - use cell identified with given column (starting with 0)
1837 columnspan=number - this widget will span several columns
1838 in=master - use master to contain this widget
1839 ipadx=amount - add internal padding in x direction
1840 ipady=amount - add internal padding in y direction
1841 padx=amount - add padding in x direction
1842 pady=amount - add padding in y direction
1843 row=number - use cell identified with given row (starting with 0)
1844 rowspan=number - this widget will span several rows
1845 sticky=NSEW - if cell is larger on which sides will this
1846 widget stick to the cell boundary
1847 """
1848 self.tk.call(
1849 ('grid', 'configure', self._w)
1850 + self._options(cnf, kw))
1851 grid = configure = config = grid_configure
1852 bbox = grid_bbox = Misc.grid_bbox
1853 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1854 def grid_forget(self):
1855 """Unmap this widget."""
1856 self.tk.call('grid', 'forget', self._w)
1857 forget = grid_forget
1858 def grid_remove(self):
1859 """Unmap this widget but remember the grid options."""
1860 self.tk.call('grid', 'remove', self._w)
1861 def grid_info(self):
1862 """Return information about the options
1863 for positioning this widget in a grid."""
1864 words = self.tk.splitlist(
1865 self.tk.call('grid', 'info', self._w))
1866 dict = {}
1867 for i in range(0, len(words), 2):
1868 key = words[i][1:]
1869 value = words[i+1]
1870 if value[:1] == '.':
1871 value = self._nametowidget(value)
1872 dict[key] = value
1873 return dict
1874 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001875 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001876 propagate = grid_propagate = Misc.grid_propagate
1877 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1878 size = grid_size = Misc.grid_size
1879 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001880
Guido van Rossum368e06b1997-11-07 20:38:49 +00001881class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001882 """Internal class."""
1883 def _setup(self, master, cnf):
1884 """Internal function. Sets up information about children."""
1885 if _support_default_root:
1886 global _default_root
1887 if not master:
1888 if not _default_root:
1889 _default_root = Tk()
1890 master = _default_root
1891 self.master = master
1892 self.tk = master.tk
1893 name = None
1894 if cnf.has_key('name'):
1895 name = cnf['name']
1896 del cnf['name']
1897 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001898 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001899 self._name = name
1900 if master._w=='.':
1901 self._w = '.' + name
1902 else:
1903 self._w = master._w + '.' + name
1904 self.children = {}
1905 if self.master.children.has_key(self._name):
1906 self.master.children[self._name].destroy()
1907 self.master.children[self._name] = self
1908 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1909 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1910 and appropriate options."""
1911 if kw:
1912 cnf = _cnfmerge((cnf, kw))
1913 self.widgetName = widgetName
1914 BaseWidget._setup(self, master, cnf)
1915 classes = []
1916 for k in cnf.keys():
1917 if type(k) is ClassType:
1918 classes.append((k, cnf[k]))
1919 del cnf[k]
1920 self.tk.call(
1921 (widgetName, self._w) + extra + self._options(cnf))
1922 for k, v in classes:
1923 k.configure(self, v)
1924 def destroy(self):
1925 """Destroy this and all descendants widgets."""
1926 for c in self.children.values(): c.destroy()
1927 if self.master.children.has_key(self._name):
1928 del self.master.children[self._name]
1929 self.tk.call('destroy', self._w)
1930 Misc.destroy(self)
1931 def _do(self, name, args=()):
1932 # XXX Obsolete -- better use self.tk.call directly!
1933 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001934
Guido van Rossum368e06b1997-11-07 20:38:49 +00001935class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001936 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001937
Fredrik Lundh06d28152000-08-09 18:03:12 +00001938 Base class for a widget which can be positioned with the geometry managers
1939 Pack, Place or Grid."""
1940 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001941
1942class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001943 """Toplevel widget, e.g. for dialogs."""
1944 def __init__(self, master=None, cnf={}, **kw):
1945 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001946
Fredrik Lundh06d28152000-08-09 18:03:12 +00001947 Valid resource names: background, bd, bg, borderwidth, class,
1948 colormap, container, cursor, height, highlightbackground,
1949 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1950 use, visual, width."""
1951 if kw:
1952 cnf = _cnfmerge((cnf, kw))
1953 extra = ()
1954 for wmkey in ['screen', 'class_', 'class', 'visual',
1955 'colormap']:
1956 if cnf.has_key(wmkey):
1957 val = cnf[wmkey]
1958 # TBD: a hack needed because some keys
1959 # are not valid as keyword arguments
1960 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1961 else: opt = '-'+wmkey
1962 extra = extra + (opt, val)
1963 del cnf[wmkey]
1964 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1965 root = self._root()
1966 self.iconname(root.iconname())
1967 self.title(root.title())
1968 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001969
1970class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001971 """Button widget."""
1972 def __init__(self, master=None, cnf={}, **kw):
1973 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001974
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001975 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001976
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001977 activebackground, activeforeground, anchor,
1978 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001979 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001980 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001981 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001982 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001983 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001984 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001985
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001986 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001987
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001988 command, compound, default, height,
1989 overrelief, state, width
1990 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001991 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001992
Fredrik Lundh06d28152000-08-09 18:03:12 +00001993 def tkButtonEnter(self, *dummy):
1994 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001995
Fredrik Lundh06d28152000-08-09 18:03:12 +00001996 def tkButtonLeave(self, *dummy):
1997 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001998
Fredrik Lundh06d28152000-08-09 18:03:12 +00001999 def tkButtonDown(self, *dummy):
2000 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002001
Fredrik Lundh06d28152000-08-09 18:03:12 +00002002 def tkButtonUp(self, *dummy):
2003 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002004
Fredrik Lundh06d28152000-08-09 18:03:12 +00002005 def tkButtonInvoke(self, *dummy):
2006 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002007
Fredrik Lundh06d28152000-08-09 18:03:12 +00002008 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002009 """Flash the button.
2010
2011 This is accomplished by redisplaying
2012 the button several times, alternating between active and
2013 normal colors. At the end of the flash the button is left
2014 in the same normal/active state as when the command was
2015 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002016 disabled.
2017 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002018 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002019
Fredrik Lundh06d28152000-08-09 18:03:12 +00002020 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002021 """Invoke the command associated with the button.
2022
2023 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002024 or an empty string if there is no command associated with
2025 the button. This command is ignored if the button's state
2026 is disabled.
2027 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002028 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002029
2030# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002031# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00002032def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002033 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00002034def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002035 s = 'insert'
2036 for a in args:
2037 if a: s = s + (' ' + a)
2038 return s
Guido van Rossum18468821994-06-20 07:49:28 +00002039def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002040 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00002041def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002042 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00002043def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002044 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002045 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002046 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002047 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002048
2049class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002050 """Canvas widget to display graphical elements like lines or text."""
2051 def __init__(self, master=None, cnf={}, **kw):
2052 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002053
Fredrik Lundh06d28152000-08-09 18:03:12 +00002054 Valid resource names: background, bd, bg, borderwidth, closeenough,
2055 confine, cursor, height, highlightbackground, highlightcolor,
2056 highlightthickness, insertbackground, insertborderwidth,
2057 insertofftime, insertontime, insertwidth, offset, relief,
2058 scrollregion, selectbackground, selectborderwidth, selectforeground,
2059 state, takefocus, width, xscrollcommand, xscrollincrement,
2060 yscrollcommand, yscrollincrement."""
2061 Widget.__init__(self, master, 'canvas', cnf, kw)
2062 def addtag(self, *args):
2063 """Internal function."""
2064 self.tk.call((self._w, 'addtag') + args)
2065 def addtag_above(self, newtag, tagOrId):
2066 """Add tag NEWTAG to all items above TAGORID."""
2067 self.addtag(newtag, 'above', tagOrId)
2068 def addtag_all(self, newtag):
2069 """Add tag NEWTAG to all items."""
2070 self.addtag(newtag, 'all')
2071 def addtag_below(self, newtag, tagOrId):
2072 """Add tag NEWTAG to all items below TAGORID."""
2073 self.addtag(newtag, 'below', tagOrId)
2074 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2075 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2076 If several match take the top-most.
2077 All items closer than HALO are considered overlapping (all are
2078 closests). If START is specified the next below this tag is taken."""
2079 self.addtag(newtag, 'closest', x, y, halo, start)
2080 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2081 """Add tag NEWTAG to all items in the rectangle defined
2082 by X1,Y1,X2,Y2."""
2083 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2084 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2085 """Add tag NEWTAG to all items which overlap the rectangle
2086 defined by X1,Y1,X2,Y2."""
2087 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2088 def addtag_withtag(self, newtag, tagOrId):
2089 """Add tag NEWTAG to all items with TAGORID."""
2090 self.addtag(newtag, 'withtag', tagOrId)
2091 def bbox(self, *args):
2092 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2093 which encloses all items with tags specified as arguments."""
2094 return self._getints(
2095 self.tk.call((self._w, 'bbox') + args)) or None
2096 def tag_unbind(self, tagOrId, sequence, funcid=None):
2097 """Unbind for all items with TAGORID for event SEQUENCE the
2098 function identified with FUNCID."""
2099 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2100 if funcid:
2101 self.deletecommand(funcid)
2102 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2103 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002104
Fredrik Lundh06d28152000-08-09 18:03:12 +00002105 An additional boolean parameter ADD specifies whether FUNC will be
2106 called additionally to the other bound function or whether it will
2107 replace the previous function. See bind for the return value."""
2108 return self._bind((self._w, 'bind', tagOrId),
2109 sequence, func, add)
2110 def canvasx(self, screenx, gridspacing=None):
2111 """Return the canvas x coordinate of pixel position SCREENX rounded
2112 to nearest multiple of GRIDSPACING units."""
2113 return getdouble(self.tk.call(
2114 self._w, 'canvasx', screenx, gridspacing))
2115 def canvasy(self, screeny, gridspacing=None):
2116 """Return the canvas y coordinate of pixel position SCREENY rounded
2117 to nearest multiple of GRIDSPACING units."""
2118 return getdouble(self.tk.call(
2119 self._w, 'canvasy', screeny, gridspacing))
2120 def coords(self, *args):
2121 """Return a list of coordinates for the item given in ARGS."""
2122 # XXX Should use _flatten on args
2123 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002124 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002125 self.tk.call((self._w, 'coords') + args)))
2126 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2127 """Internal function."""
2128 args = _flatten(args)
2129 cnf = args[-1]
2130 if type(cnf) in (DictionaryType, TupleType):
2131 args = args[:-1]
2132 else:
2133 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002134 return getint(self.tk.call(
2135 self._w, 'create', itemType,
2136 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002137 def create_arc(self, *args, **kw):
2138 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2139 return self._create('arc', args, kw)
2140 def create_bitmap(self, *args, **kw):
2141 """Create bitmap with coordinates x1,y1."""
2142 return self._create('bitmap', args, kw)
2143 def create_image(self, *args, **kw):
2144 """Create image item with coordinates x1,y1."""
2145 return self._create('image', args, kw)
2146 def create_line(self, *args, **kw):
2147 """Create line with coordinates x1,y1,...,xn,yn."""
2148 return self._create('line', args, kw)
2149 def create_oval(self, *args, **kw):
2150 """Create oval with coordinates x1,y1,x2,y2."""
2151 return self._create('oval', args, kw)
2152 def create_polygon(self, *args, **kw):
2153 """Create polygon with coordinates x1,y1,...,xn,yn."""
2154 return self._create('polygon', args, kw)
2155 def create_rectangle(self, *args, **kw):
2156 """Create rectangle with coordinates x1,y1,x2,y2."""
2157 return self._create('rectangle', args, kw)
2158 def create_text(self, *args, **kw):
2159 """Create text with coordinates x1,y1."""
2160 return self._create('text', args, kw)
2161 def create_window(self, *args, **kw):
2162 """Create window with coordinates x1,y1,x2,y2."""
2163 return self._create('window', args, kw)
2164 def dchars(self, *args):
2165 """Delete characters of text items identified by tag or id in ARGS (possibly
2166 several times) from FIRST to LAST character (including)."""
2167 self.tk.call((self._w, 'dchars') + args)
2168 def delete(self, *args):
2169 """Delete items identified by all tag or ids contained in ARGS."""
2170 self.tk.call((self._w, 'delete') + args)
2171 def dtag(self, *args):
2172 """Delete tag or id given as last arguments in ARGS from items
2173 identified by first argument in ARGS."""
2174 self.tk.call((self._w, 'dtag') + args)
2175 def find(self, *args):
2176 """Internal function."""
2177 return self._getints(
2178 self.tk.call((self._w, 'find') + args)) or ()
2179 def find_above(self, tagOrId):
2180 """Return items above TAGORID."""
2181 return self.find('above', tagOrId)
2182 def find_all(self):
2183 """Return all items."""
2184 return self.find('all')
2185 def find_below(self, tagOrId):
2186 """Return all items below TAGORID."""
2187 return self.find('below', tagOrId)
2188 def find_closest(self, x, y, halo=None, start=None):
2189 """Return item which is closest to pixel at X, Y.
2190 If several match take the top-most.
2191 All items closer than HALO are considered overlapping (all are
2192 closests). If START is specified the next below this tag is taken."""
2193 return self.find('closest', x, y, halo, start)
2194 def find_enclosed(self, x1, y1, x2, y2):
2195 """Return all items in rectangle defined
2196 by X1,Y1,X2,Y2."""
2197 return self.find('enclosed', x1, y1, x2, y2)
2198 def find_overlapping(self, x1, y1, x2, y2):
2199 """Return all items which overlap the rectangle
2200 defined by X1,Y1,X2,Y2."""
2201 return self.find('overlapping', x1, y1, x2, y2)
2202 def find_withtag(self, tagOrId):
2203 """Return all items with TAGORID."""
2204 return self.find('withtag', tagOrId)
2205 def focus(self, *args):
2206 """Set focus to the first item specified in ARGS."""
2207 return self.tk.call((self._w, 'focus') + args)
2208 def gettags(self, *args):
2209 """Return tags associated with the first item specified in ARGS."""
2210 return self.tk.splitlist(
2211 self.tk.call((self._w, 'gettags') + args))
2212 def icursor(self, *args):
2213 """Set cursor at position POS in the item identified by TAGORID.
2214 In ARGS TAGORID must be first."""
2215 self.tk.call((self._w, 'icursor') + args)
2216 def index(self, *args):
2217 """Return position of cursor as integer in item specified in ARGS."""
2218 return getint(self.tk.call((self._w, 'index') + args))
2219 def insert(self, *args):
2220 """Insert TEXT in item TAGORID at position POS. ARGS must
2221 be TAGORID POS TEXT."""
2222 self.tk.call((self._w, 'insert') + args)
2223 def itemcget(self, tagOrId, option):
2224 """Return the resource value for an OPTION for item TAGORID."""
2225 return self.tk.call(
2226 (self._w, 'itemcget') + (tagOrId, '-'+option))
2227 def itemconfigure(self, tagOrId, cnf=None, **kw):
2228 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002229
Fredrik Lundh06d28152000-08-09 18:03:12 +00002230 The values for resources are specified as keyword
2231 arguments. To get an overview about
2232 the allowed keyword arguments call the method without arguments.
2233 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002234 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002235 itemconfig = itemconfigure
2236 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2237 # so the preferred name for them is tag_lower, tag_raise
2238 # (similar to tag_bind, and similar to the Text widget);
2239 # unfortunately can't delete the old ones yet (maybe in 1.6)
2240 def tag_lower(self, *args):
2241 """Lower an item TAGORID given in ARGS
2242 (optional below another item)."""
2243 self.tk.call((self._w, 'lower') + args)
2244 lower = tag_lower
2245 def move(self, *args):
2246 """Move an item TAGORID given in ARGS."""
2247 self.tk.call((self._w, 'move') + args)
2248 def postscript(self, cnf={}, **kw):
2249 """Print the contents of the canvas to a postscript
2250 file. Valid options: colormap, colormode, file, fontmap,
2251 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2252 rotate, witdh, x, y."""
2253 return self.tk.call((self._w, 'postscript') +
2254 self._options(cnf, kw))
2255 def tag_raise(self, *args):
2256 """Raise an item TAGORID given in ARGS
2257 (optional above another item)."""
2258 self.tk.call((self._w, 'raise') + args)
2259 lift = tkraise = tag_raise
2260 def scale(self, *args):
2261 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2262 self.tk.call((self._w, 'scale') + args)
2263 def scan_mark(self, x, y):
2264 """Remember the current X, Y coordinates."""
2265 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002266 def scan_dragto(self, x, y, gain=10):
2267 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002268 difference between X and Y and the coordinates given in
2269 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002270 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002271 def select_adjust(self, tagOrId, index):
2272 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2273 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2274 def select_clear(self):
2275 """Clear the selection if it is in this widget."""
2276 self.tk.call(self._w, 'select', 'clear')
2277 def select_from(self, tagOrId, index):
2278 """Set the fixed end of a selection in item TAGORID to INDEX."""
2279 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2280 def select_item(self):
2281 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002282 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002283 def select_to(self, tagOrId, index):
2284 """Set the variable end of a selection in item TAGORID to INDEX."""
2285 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2286 def type(self, tagOrId):
2287 """Return the type of the item TAGORID."""
2288 return self.tk.call(self._w, 'type', tagOrId) or None
2289 def xview(self, *args):
2290 """Query and change horizontal position of the view."""
2291 if not args:
2292 return self._getdoubles(self.tk.call(self._w, 'xview'))
2293 self.tk.call((self._w, 'xview') + args)
2294 def xview_moveto(self, fraction):
2295 """Adjusts the view in the window so that FRACTION of the
2296 total width of the canvas is off-screen to the left."""
2297 self.tk.call(self._w, 'xview', 'moveto', fraction)
2298 def xview_scroll(self, number, what):
2299 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2300 self.tk.call(self._w, 'xview', 'scroll', number, what)
2301 def yview(self, *args):
2302 """Query and change vertical position of the view."""
2303 if not args:
2304 return self._getdoubles(self.tk.call(self._w, 'yview'))
2305 self.tk.call((self._w, 'yview') + args)
2306 def yview_moveto(self, fraction):
2307 """Adjusts the view in the window so that FRACTION of the
2308 total height of the canvas is off-screen to the top."""
2309 self.tk.call(self._w, 'yview', 'moveto', fraction)
2310 def yview_scroll(self, number, what):
2311 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2312 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002313
2314class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002315 """Checkbutton widget which is either in on- or off-state."""
2316 def __init__(self, master=None, cnf={}, **kw):
2317 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002318
Fredrik Lundh06d28152000-08-09 18:03:12 +00002319 Valid resource names: activebackground, activeforeground, anchor,
2320 background, bd, bg, bitmap, borderwidth, command, cursor,
2321 disabledforeground, fg, font, foreground, height,
2322 highlightbackground, highlightcolor, highlightthickness, image,
2323 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2324 selectcolor, selectimage, state, takefocus, text, textvariable,
2325 underline, variable, width, wraplength."""
2326 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2327 def deselect(self):
2328 """Put the button in off-state."""
2329 self.tk.call(self._w, 'deselect')
2330 def flash(self):
2331 """Flash the button."""
2332 self.tk.call(self._w, 'flash')
2333 def invoke(self):
2334 """Toggle the button and invoke a command if given as resource."""
2335 return self.tk.call(self._w, 'invoke')
2336 def select(self):
2337 """Put the button in on-state."""
2338 self.tk.call(self._w, 'select')
2339 def toggle(self):
2340 """Toggle the button."""
2341 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002342
2343class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002344 """Entry widget which allows to display simple text."""
2345 def __init__(self, master=None, cnf={}, **kw):
2346 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002347
Fredrik Lundh06d28152000-08-09 18:03:12 +00002348 Valid resource names: background, bd, bg, borderwidth, cursor,
2349 exportselection, fg, font, foreground, highlightbackground,
2350 highlightcolor, highlightthickness, insertbackground,
2351 insertborderwidth, insertofftime, insertontime, insertwidth,
2352 invalidcommand, invcmd, justify, relief, selectbackground,
2353 selectborderwidth, selectforeground, show, state, takefocus,
2354 textvariable, validate, validatecommand, vcmd, width,
2355 xscrollcommand."""
2356 Widget.__init__(self, master, 'entry', cnf, kw)
2357 def delete(self, first, last=None):
2358 """Delete text from FIRST to LAST (not included)."""
2359 self.tk.call(self._w, 'delete', first, last)
2360 def get(self):
2361 """Return the text."""
2362 return self.tk.call(self._w, 'get')
2363 def icursor(self, index):
2364 """Insert cursor at INDEX."""
2365 self.tk.call(self._w, 'icursor', index)
2366 def index(self, index):
2367 """Return position of cursor."""
2368 return getint(self.tk.call(
2369 self._w, 'index', index))
2370 def insert(self, index, string):
2371 """Insert STRING at INDEX."""
2372 self.tk.call(self._w, 'insert', index, string)
2373 def scan_mark(self, x):
2374 """Remember the current X, Y coordinates."""
2375 self.tk.call(self._w, 'scan', 'mark', x)
2376 def scan_dragto(self, x):
2377 """Adjust the view of the canvas to 10 times the
2378 difference between X and Y and the coordinates given in
2379 scan_mark."""
2380 self.tk.call(self._w, 'scan', 'dragto', x)
2381 def selection_adjust(self, index):
2382 """Adjust the end of the selection near the cursor to INDEX."""
2383 self.tk.call(self._w, 'selection', 'adjust', index)
2384 select_adjust = selection_adjust
2385 def selection_clear(self):
2386 """Clear the selection if it is in this widget."""
2387 self.tk.call(self._w, 'selection', 'clear')
2388 select_clear = selection_clear
2389 def selection_from(self, index):
2390 """Set the fixed end of a selection to INDEX."""
2391 self.tk.call(self._w, 'selection', 'from', index)
2392 select_from = selection_from
2393 def selection_present(self):
2394 """Return whether the widget has the selection."""
2395 return self.tk.getboolean(
2396 self.tk.call(self._w, 'selection', 'present'))
2397 select_present = selection_present
2398 def selection_range(self, start, end):
2399 """Set the selection from START to END (not included)."""
2400 self.tk.call(self._w, 'selection', 'range', start, end)
2401 select_range = selection_range
2402 def selection_to(self, index):
2403 """Set the variable end of a selection to INDEX."""
2404 self.tk.call(self._w, 'selection', 'to', index)
2405 select_to = selection_to
2406 def xview(self, index):
2407 """Query and change horizontal position of the view."""
2408 self.tk.call(self._w, 'xview', index)
2409 def xview_moveto(self, fraction):
2410 """Adjust the view in the window so that FRACTION of the
2411 total width of the entry is off-screen to the left."""
2412 self.tk.call(self._w, 'xview', 'moveto', fraction)
2413 def xview_scroll(self, number, what):
2414 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2415 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002416
2417class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002418 """Frame widget which may contain other widgets and can have a 3D border."""
2419 def __init__(self, master=None, cnf={}, **kw):
2420 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002421
Fredrik Lundh06d28152000-08-09 18:03:12 +00002422 Valid resource names: background, bd, bg, borderwidth, class,
2423 colormap, container, cursor, height, highlightbackground,
2424 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2425 cnf = _cnfmerge((cnf, kw))
2426 extra = ()
2427 if cnf.has_key('class_'):
2428 extra = ('-class', cnf['class_'])
2429 del cnf['class_']
2430 elif cnf.has_key('class'):
2431 extra = ('-class', cnf['class'])
2432 del cnf['class']
2433 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002434
2435class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002436 """Label widget which can display text and bitmaps."""
2437 def __init__(self, master=None, cnf={}, **kw):
2438 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002439
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002440 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002441
2442 activebackground, activeforeground, anchor,
2443 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002444 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002445 highlightbackground, highlightcolor,
2446 highlightthickness, image, justify,
2447 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002448 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002449
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002450 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002451
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002452 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002453
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002454 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002455 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002456
Guido van Rossum18468821994-06-20 07:49:28 +00002457class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002458 """Listbox widget which can display a list of strings."""
2459 def __init__(self, master=None, cnf={}, **kw):
2460 """Construct a listbox 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: background, bd, bg, borderwidth, cursor,
2463 exportselection, fg, font, foreground, height, highlightbackground,
2464 highlightcolor, highlightthickness, relief, selectbackground,
2465 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2466 width, xscrollcommand, yscrollcommand, listvariable."""
2467 Widget.__init__(self, master, 'listbox', cnf, kw)
2468 def activate(self, index):
2469 """Activate item identified by INDEX."""
2470 self.tk.call(self._w, 'activate', index)
2471 def bbox(self, *args):
2472 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2473 which encloses the item identified by index in ARGS."""
2474 return self._getints(
2475 self.tk.call((self._w, 'bbox') + args)) or None
2476 def curselection(self):
2477 """Return list of indices of currently selected item."""
2478 # XXX Ought to apply self._getints()...
2479 return self.tk.splitlist(self.tk.call(
2480 self._w, 'curselection'))
2481 def delete(self, first, last=None):
2482 """Delete items from FIRST to LAST (not included)."""
2483 self.tk.call(self._w, 'delete', first, last)
2484 def get(self, first, last=None):
2485 """Get list of items from FIRST to LAST (not included)."""
2486 if last:
2487 return self.tk.splitlist(self.tk.call(
2488 self._w, 'get', first, last))
2489 else:
2490 return self.tk.call(self._w, 'get', first)
2491 def index(self, index):
2492 """Return index of item identified with INDEX."""
2493 i = self.tk.call(self._w, 'index', index)
2494 if i == 'none': return None
2495 return getint(i)
2496 def insert(self, index, *elements):
2497 """Insert ELEMENTS at INDEX."""
2498 self.tk.call((self._w, 'insert', index) + elements)
2499 def nearest(self, y):
2500 """Get index of item which is nearest to y coordinate Y."""
2501 return getint(self.tk.call(
2502 self._w, 'nearest', y))
2503 def scan_mark(self, x, y):
2504 """Remember the current X, Y coordinates."""
2505 self.tk.call(self._w, 'scan', 'mark', x, y)
2506 def scan_dragto(self, x, y):
2507 """Adjust the view of the listbox to 10 times the
2508 difference between X and Y and the coordinates given in
2509 scan_mark."""
2510 self.tk.call(self._w, 'scan', 'dragto', x, y)
2511 def see(self, index):
2512 """Scroll such that INDEX is visible."""
2513 self.tk.call(self._w, 'see', index)
2514 def selection_anchor(self, index):
2515 """Set the fixed end oft the selection to INDEX."""
2516 self.tk.call(self._w, 'selection', 'anchor', index)
2517 select_anchor = selection_anchor
2518 def selection_clear(self, first, last=None):
2519 """Clear the selection from FIRST to LAST (not included)."""
2520 self.tk.call(self._w,
2521 'selection', 'clear', first, last)
2522 select_clear = selection_clear
2523 def selection_includes(self, index):
2524 """Return 1 if INDEX is part of the selection."""
2525 return self.tk.getboolean(self.tk.call(
2526 self._w, 'selection', 'includes', index))
2527 select_includes = selection_includes
2528 def selection_set(self, first, last=None):
2529 """Set the selection from FIRST to LAST (not included) without
2530 changing the currently selected elements."""
2531 self.tk.call(self._w, 'selection', 'set', first, last)
2532 select_set = selection_set
2533 def size(self):
2534 """Return the number of elements in the listbox."""
2535 return getint(self.tk.call(self._w, 'size'))
2536 def xview(self, *what):
2537 """Query and change horizontal position of the view."""
2538 if not what:
2539 return self._getdoubles(self.tk.call(self._w, 'xview'))
2540 self.tk.call((self._w, 'xview') + what)
2541 def xview_moveto(self, fraction):
2542 """Adjust the view in the window so that FRACTION of the
2543 total width of the entry is off-screen to the left."""
2544 self.tk.call(self._w, 'xview', 'moveto', fraction)
2545 def xview_scroll(self, number, what):
2546 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2547 self.tk.call(self._w, 'xview', 'scroll', number, what)
2548 def yview(self, *what):
2549 """Query and change vertical position of the view."""
2550 if not what:
2551 return self._getdoubles(self.tk.call(self._w, 'yview'))
2552 self.tk.call((self._w, 'yview') + what)
2553 def yview_moveto(self, fraction):
2554 """Adjust the view in the window so that FRACTION of the
2555 total width of the entry is off-screen to the top."""
2556 self.tk.call(self._w, 'yview', 'moveto', fraction)
2557 def yview_scroll(self, number, what):
2558 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2559 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002560 def itemcget(self, index, option):
2561 """Return the resource value for an ITEM and an OPTION."""
2562 return self.tk.call(
2563 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002564 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002565 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002566
2567 The values for resources are specified as keyword arguments.
2568 To get an overview about the allowed keyword arguments
2569 call the method without arguments.
2570 Valid resource names: background, bg, foreground, fg,
2571 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002572 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002573 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002574
2575class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002576 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2577 def __init__(self, master=None, cnf={}, **kw):
2578 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002579
Fredrik Lundh06d28152000-08-09 18:03:12 +00002580 Valid resource names: activebackground, activeborderwidth,
2581 activeforeground, background, bd, bg, borderwidth, cursor,
2582 disabledforeground, fg, font, foreground, postcommand, relief,
2583 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2584 Widget.__init__(self, master, 'menu', cnf, kw)
2585 def tk_bindForTraversal(self):
2586 pass # obsolete since Tk 4.0
2587 def tk_mbPost(self):
2588 self.tk.call('tk_mbPost', self._w)
2589 def tk_mbUnpost(self):
2590 self.tk.call('tk_mbUnpost')
2591 def tk_traverseToMenu(self, char):
2592 self.tk.call('tk_traverseToMenu', self._w, char)
2593 def tk_traverseWithinMenu(self, char):
2594 self.tk.call('tk_traverseWithinMenu', self._w, char)
2595 def tk_getMenuButtons(self):
2596 return self.tk.call('tk_getMenuButtons', self._w)
2597 def tk_nextMenu(self, count):
2598 self.tk.call('tk_nextMenu', count)
2599 def tk_nextMenuEntry(self, count):
2600 self.tk.call('tk_nextMenuEntry', count)
2601 def tk_invokeMenu(self):
2602 self.tk.call('tk_invokeMenu', self._w)
2603 def tk_firstMenu(self):
2604 self.tk.call('tk_firstMenu', self._w)
2605 def tk_mbButtonDown(self):
2606 self.tk.call('tk_mbButtonDown', self._w)
2607 def tk_popup(self, x, y, entry=""):
2608 """Post the menu at position X,Y with entry ENTRY."""
2609 self.tk.call('tk_popup', self._w, x, y, entry)
2610 def activate(self, index):
2611 """Activate entry at INDEX."""
2612 self.tk.call(self._w, 'activate', index)
2613 def add(self, itemType, cnf={}, **kw):
2614 """Internal function."""
2615 self.tk.call((self._w, 'add', itemType) +
2616 self._options(cnf, kw))
2617 def add_cascade(self, cnf={}, **kw):
2618 """Add hierarchical menu item."""
2619 self.add('cascade', cnf or kw)
2620 def add_checkbutton(self, cnf={}, **kw):
2621 """Add checkbutton menu item."""
2622 self.add('checkbutton', cnf or kw)
2623 def add_command(self, cnf={}, **kw):
2624 """Add command menu item."""
2625 self.add('command', cnf or kw)
2626 def add_radiobutton(self, cnf={}, **kw):
2627 """Addd radio menu item."""
2628 self.add('radiobutton', cnf or kw)
2629 def add_separator(self, cnf={}, **kw):
2630 """Add separator."""
2631 self.add('separator', cnf or kw)
2632 def insert(self, index, itemType, cnf={}, **kw):
2633 """Internal function."""
2634 self.tk.call((self._w, 'insert', index, itemType) +
2635 self._options(cnf, kw))
2636 def insert_cascade(self, index, cnf={}, **kw):
2637 """Add hierarchical menu item at INDEX."""
2638 self.insert(index, 'cascade', cnf or kw)
2639 def insert_checkbutton(self, index, cnf={}, **kw):
2640 """Add checkbutton menu item at INDEX."""
2641 self.insert(index, 'checkbutton', cnf or kw)
2642 def insert_command(self, index, cnf={}, **kw):
2643 """Add command menu item at INDEX."""
2644 self.insert(index, 'command', cnf or kw)
2645 def insert_radiobutton(self, index, cnf={}, **kw):
2646 """Addd radio menu item at INDEX."""
2647 self.insert(index, 'radiobutton', cnf or kw)
2648 def insert_separator(self, index, cnf={}, **kw):
2649 """Add separator at INDEX."""
2650 self.insert(index, 'separator', cnf or kw)
2651 def delete(self, index1, index2=None):
2652 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2653 self.tk.call(self._w, 'delete', index1, index2)
2654 def entrycget(self, index, option):
2655 """Return the resource value of an menu item for OPTION at INDEX."""
2656 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2657 def entryconfigure(self, index, cnf=None, **kw):
2658 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002659 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002660 entryconfig = entryconfigure
2661 def index(self, index):
2662 """Return the index of a menu item identified by INDEX."""
2663 i = self.tk.call(self._w, 'index', index)
2664 if i == 'none': return None
2665 return getint(i)
2666 def invoke(self, index):
2667 """Invoke a menu item identified by INDEX and execute
2668 the associated command."""
2669 return self.tk.call(self._w, 'invoke', index)
2670 def post(self, x, y):
2671 """Display a menu at position X,Y."""
2672 self.tk.call(self._w, 'post', x, y)
2673 def type(self, index):
2674 """Return the type of the menu item at INDEX."""
2675 return self.tk.call(self._w, 'type', index)
2676 def unpost(self):
2677 """Unmap a menu."""
2678 self.tk.call(self._w, 'unpost')
2679 def yposition(self, index):
2680 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2681 return getint(self.tk.call(
2682 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002683
2684class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002685 """Menubutton widget, obsolete since Tk8.0."""
2686 def __init__(self, master=None, cnf={}, **kw):
2687 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002688
2689class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002690 """Message widget to display multiline text. Obsolete since Label does it too."""
2691 def __init__(self, master=None, cnf={}, **kw):
2692 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002693
2694class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002695 """Radiobutton widget which shows only one of several buttons in on-state."""
2696 def __init__(self, master=None, cnf={}, **kw):
2697 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002698
Fredrik Lundh06d28152000-08-09 18:03:12 +00002699 Valid resource names: activebackground, activeforeground, anchor,
2700 background, bd, bg, bitmap, borderwidth, command, cursor,
2701 disabledforeground, fg, font, foreground, height,
2702 highlightbackground, highlightcolor, highlightthickness, image,
2703 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2704 state, takefocus, text, textvariable, underline, value, variable,
2705 width, wraplength."""
2706 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2707 def deselect(self):
2708 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002709
Fredrik Lundh06d28152000-08-09 18:03:12 +00002710 self.tk.call(self._w, 'deselect')
2711 def flash(self):
2712 """Flash the button."""
2713 self.tk.call(self._w, 'flash')
2714 def invoke(self):
2715 """Toggle the button and invoke a command if given as resource."""
2716 return self.tk.call(self._w, 'invoke')
2717 def select(self):
2718 """Put the button in on-state."""
2719 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002720
2721class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002722 """Scale widget which can display a numerical scale."""
2723 def __init__(self, master=None, cnf={}, **kw):
2724 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002725
Fredrik Lundh06d28152000-08-09 18:03:12 +00002726 Valid resource names: activebackground, background, bigincrement, bd,
2727 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2728 highlightbackground, highlightcolor, highlightthickness, label,
2729 length, orient, relief, repeatdelay, repeatinterval, resolution,
2730 showvalue, sliderlength, sliderrelief, state, takefocus,
2731 tickinterval, to, troughcolor, variable, width."""
2732 Widget.__init__(self, master, 'scale', cnf, kw)
2733 def get(self):
2734 """Get the current value as integer or float."""
2735 value = self.tk.call(self._w, 'get')
2736 try:
2737 return getint(value)
2738 except ValueError:
2739 return getdouble(value)
2740 def set(self, value):
2741 """Set the value to VALUE."""
2742 self.tk.call(self._w, 'set', value)
2743 def coords(self, value=None):
2744 """Return a tuple (X,Y) of the point along the centerline of the
2745 trough that corresponds to VALUE or the current value if None is
2746 given."""
2747
2748 return self._getints(self.tk.call(self._w, 'coords', value))
2749 def identify(self, x, y):
2750 """Return where the point X,Y lies. Valid return values are "slider",
2751 "though1" and "though2"."""
2752 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002753
2754class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002755 """Scrollbar widget which displays a slider at a certain position."""
2756 def __init__(self, master=None, cnf={}, **kw):
2757 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002758
Fredrik Lundh06d28152000-08-09 18:03:12 +00002759 Valid resource names: activebackground, activerelief,
2760 background, bd, bg, borderwidth, command, cursor,
2761 elementborderwidth, highlightbackground,
2762 highlightcolor, highlightthickness, jump, orient,
2763 relief, repeatdelay, repeatinterval, takefocus,
2764 troughcolor, width."""
2765 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2766 def activate(self, index):
2767 """Display the element at INDEX with activebackground and activerelief.
2768 INDEX can be "arrow1","slider" or "arrow2"."""
2769 self.tk.call(self._w, 'activate', index)
2770 def delta(self, deltax, deltay):
2771 """Return the fractional change of the scrollbar setting if it
2772 would be moved by DELTAX or DELTAY pixels."""
2773 return getdouble(
2774 self.tk.call(self._w, 'delta', deltax, deltay))
2775 def fraction(self, x, y):
2776 """Return the fractional value which corresponds to a slider
2777 position of X,Y."""
2778 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2779 def identify(self, x, y):
2780 """Return the element under position X,Y as one of
2781 "arrow1","slider","arrow2" or ""."""
2782 return self.tk.call(self._w, 'identify', x, y)
2783 def get(self):
2784 """Return the current fractional values (upper and lower end)
2785 of the slider position."""
2786 return self._getdoubles(self.tk.call(self._w, 'get'))
2787 def set(self, *args):
2788 """Set the fractional values of the slider position (upper and
2789 lower ends as value between 0 and 1)."""
2790 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002791
2792
2793
Guido van Rossum18468821994-06-20 07:49:28 +00002794class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002795 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002796 def __init__(self, master=None, cnf={}, **kw):
2797 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002798
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002799 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002800
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002801 background, borderwidth, cursor,
2802 exportselection, font, foreground,
2803 highlightbackground, highlightcolor,
2804 highlightthickness, insertbackground,
2805 insertborderwidth, insertofftime,
2806 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002807 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002808 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002809 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002810 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002811
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002812 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002813
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002814 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002815 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002816 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002817
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002818 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002819 Widget.__init__(self, master, 'text', cnf, kw)
2820 def bbox(self, *args):
2821 """Return a tuple of (x,y,width,height) which gives the bounding
2822 box of the visible part of the character at the index in ARGS."""
2823 return self._getints(
2824 self.tk.call((self._w, 'bbox') + args)) or None
2825 def tk_textSelectTo(self, index):
2826 self.tk.call('tk_textSelectTo', self._w, index)
2827 def tk_textBackspace(self):
2828 self.tk.call('tk_textBackspace', self._w)
2829 def tk_textIndexCloser(self, a, b, c):
2830 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2831 def tk_textResetAnchor(self, index):
2832 self.tk.call('tk_textResetAnchor', self._w, index)
2833 def compare(self, index1, op, index2):
2834 """Return whether between index INDEX1 and index INDEX2 the
2835 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2836 return self.tk.getboolean(self.tk.call(
2837 self._w, 'compare', index1, op, index2))
2838 def debug(self, boolean=None):
2839 """Turn on the internal consistency checks of the B-Tree inside the text
2840 widget according to BOOLEAN."""
2841 return self.tk.getboolean(self.tk.call(
2842 self._w, 'debug', boolean))
2843 def delete(self, index1, index2=None):
2844 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2845 self.tk.call(self._w, 'delete', index1, index2)
2846 def dlineinfo(self, index):
2847 """Return tuple (x,y,width,height,baseline) giving the bounding box
2848 and baseline position of the visible part of the line containing
2849 the character at INDEX."""
2850 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002851 def dump(self, index1, index2=None, command=None, **kw):
2852 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002853
Guido van Rossum256705b2002-04-23 13:29:43 +00002854 The type of contents returned in filtered based on the keyword
2855 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2856 given and true, then the corresponding items are returned. The result
2857 is a list of triples of the form (key, value, index). If none of the
2858 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002859
Guido van Rossum256705b2002-04-23 13:29:43 +00002860 If the 'command' argument is given, it is called once for each element
2861 of the list of triples, with the values of each triple serving as the
2862 arguments to the function. In this case the list is not returned."""
2863 args = []
2864 func_name = None
2865 result = None
2866 if not command:
2867 # Never call the dump command without the -command flag, since the
2868 # output could involve Tcl quoting and would be a pain to parse
2869 # right. Instead just set the command to build a list of triples
2870 # as if we had done the parsing.
2871 result = []
2872 def append_triple(key, value, index, result=result):
2873 result.append((key, value, index))
2874 command = append_triple
2875 try:
2876 if not isinstance(command, str):
2877 func_name = command = self._register(command)
2878 args += ["-command", command]
2879 for key in kw:
2880 if kw[key]: args.append("-" + key)
2881 args.append(index1)
2882 if index2:
2883 args.append(index2)
2884 self.tk.call(self._w, "dump", *args)
2885 return result
2886 finally:
2887 if func_name:
2888 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002889
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002890 ## new in tk8.4
2891 def edit(self, *args):
2892 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002893
2894 This method controls the undo mechanism and
2895 the modified flag. The exact behavior of the
2896 command depends on the option argument that
2897 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002898 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002899
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002900 edit_modified, edit_redo, edit_reset, edit_separator
2901 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002902
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002903 """
2904 return self._getints(
2905 self.tk.call((self._w, 'edit') + args)) or ()
2906
2907 def edit_modified(self, arg=None):
2908 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002909
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002910 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002911 flag of the widget. The insert, delete, edit undo and
2912 edit redo commands or the user can set or clear the
2913 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002914 modified flag of the widget to arg.
2915 """
2916 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002917
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002918 def edit_redo(self):
2919 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002920
2921 When the undo option is true, reapplies the last
2922 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002923 then. Generates an error when the redo stack is empty.
2924 Does nothing when the undo option is false.
2925 """
2926 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002927
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002928 def edit_reset(self):
2929 """Clears the undo and redo stacks
2930 """
2931 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002932
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002933 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002934 """Inserts a separator (boundary) on the undo stack.
2935
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002936 Does nothing when the undo option is false
2937 """
2938 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002939
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002940 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002941 """Undoes the last edit action
2942
2943 If the undo option is true. An edit action is defined
2944 as all the insert and delete commands that are recorded
2945 on the undo stack in between two separators. Generates
2946 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002947 when the undo option is false
2948 """
2949 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002950
Fredrik Lundh06d28152000-08-09 18:03:12 +00002951 def get(self, index1, index2=None):
2952 """Return the text from INDEX1 to INDEX2 (not included)."""
2953 return self.tk.call(self._w, 'get', index1, index2)
2954 # (Image commands are new in 8.0)
2955 def image_cget(self, index, option):
2956 """Return the value of OPTION of an embedded image at INDEX."""
2957 if option[:1] != "-":
2958 option = "-" + option
2959 if option[-1:] == "_":
2960 option = option[:-1]
2961 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002962 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002963 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002964 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002965 def image_create(self, index, cnf={}, **kw):
2966 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002967 return self.tk.call(
2968 self._w, "image", "create", index,
2969 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002970 def image_names(self):
2971 """Return all names of embedded images in this widget."""
2972 return self.tk.call(self._w, "image", "names")
2973 def index(self, index):
2974 """Return the index in the form line.char for INDEX."""
2975 return self.tk.call(self._w, 'index', index)
2976 def insert(self, index, chars, *args):
2977 """Insert CHARS before the characters at INDEX. An additional
2978 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2979 self.tk.call((self._w, 'insert', index, chars) + args)
2980 def mark_gravity(self, markName, direction=None):
2981 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2982 Return the current value if None is given for DIRECTION."""
2983 return self.tk.call(
2984 (self._w, 'mark', 'gravity', markName, direction))
2985 def mark_names(self):
2986 """Return all mark names."""
2987 return self.tk.splitlist(self.tk.call(
2988 self._w, 'mark', 'names'))
2989 def mark_set(self, markName, index):
2990 """Set mark MARKNAME before the character at INDEX."""
2991 self.tk.call(self._w, 'mark', 'set', markName, index)
2992 def mark_unset(self, *markNames):
2993 """Delete all marks in MARKNAMES."""
2994 self.tk.call((self._w, 'mark', 'unset') + markNames)
2995 def mark_next(self, index):
2996 """Return the name of the next mark after INDEX."""
2997 return self.tk.call(self._w, 'mark', 'next', index) or None
2998 def mark_previous(self, index):
2999 """Return the name of the previous mark before INDEX."""
3000 return self.tk.call(self._w, 'mark', 'previous', index) or None
3001 def scan_mark(self, x, y):
3002 """Remember the current X, Y coordinates."""
3003 self.tk.call(self._w, 'scan', 'mark', x, y)
3004 def scan_dragto(self, x, y):
3005 """Adjust the view of the text to 10 times the
3006 difference between X and Y and the coordinates given in
3007 scan_mark."""
3008 self.tk.call(self._w, 'scan', 'dragto', x, y)
3009 def search(self, pattern, index, stopindex=None,
3010 forwards=None, backwards=None, exact=None,
3011 regexp=None, nocase=None, count=None):
3012 """Search PATTERN beginning from INDEX until STOPINDEX.
3013 Return the index of the first character of a match or an empty string."""
3014 args = [self._w, 'search']
3015 if forwards: args.append('-forwards')
3016 if backwards: args.append('-backwards')
3017 if exact: args.append('-exact')
3018 if regexp: args.append('-regexp')
3019 if nocase: args.append('-nocase')
3020 if count: args.append('-count'); args.append(count)
3021 if pattern[0] == '-': args.append('--')
3022 args.append(pattern)
3023 args.append(index)
3024 if stopindex: args.append(stopindex)
3025 return self.tk.call(tuple(args))
3026 def see(self, index):
3027 """Scroll such that the character at INDEX is visible."""
3028 self.tk.call(self._w, 'see', index)
3029 def tag_add(self, tagName, index1, *args):
3030 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3031 Additional pairs of indices may follow in ARGS."""
3032 self.tk.call(
3033 (self._w, 'tag', 'add', tagName, index1) + args)
3034 def tag_unbind(self, tagName, sequence, funcid=None):
3035 """Unbind for all characters with TAGNAME for event SEQUENCE the
3036 function identified with FUNCID."""
3037 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3038 if funcid:
3039 self.deletecommand(funcid)
3040 def tag_bind(self, tagName, sequence, func, add=None):
3041 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003042
Fredrik Lundh06d28152000-08-09 18:03:12 +00003043 An additional boolean parameter ADD specifies whether FUNC will be
3044 called additionally to the other bound function or whether it will
3045 replace the previous function. See bind for the return value."""
3046 return self._bind((self._w, 'tag', 'bind', tagName),
3047 sequence, func, add)
3048 def tag_cget(self, tagName, option):
3049 """Return the value of OPTION for tag TAGNAME."""
3050 if option[:1] != '-':
3051 option = '-' + option
3052 if option[-1:] == '_':
3053 option = option[:-1]
3054 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003055 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003056 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003057 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003058 tag_config = tag_configure
3059 def tag_delete(self, *tagNames):
3060 """Delete all tags in TAGNAMES."""
3061 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3062 def tag_lower(self, tagName, belowThis=None):
3063 """Change the priority of tag TAGNAME such that it is lower
3064 than the priority of BELOWTHIS."""
3065 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3066 def tag_names(self, index=None):
3067 """Return a list of all tag names."""
3068 return self.tk.splitlist(
3069 self.tk.call(self._w, 'tag', 'names', index))
3070 def tag_nextrange(self, tagName, index1, index2=None):
3071 """Return a list of start and end index for the first sequence of
3072 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3073 The text is searched forward from INDEX1."""
3074 return self.tk.splitlist(self.tk.call(
3075 self._w, 'tag', 'nextrange', tagName, index1, index2))
3076 def tag_prevrange(self, tagName, index1, index2=None):
3077 """Return a list of start and end index for the first sequence of
3078 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3079 The text is searched backwards from INDEX1."""
3080 return self.tk.splitlist(self.tk.call(
3081 self._w, 'tag', 'prevrange', tagName, index1, index2))
3082 def tag_raise(self, tagName, aboveThis=None):
3083 """Change the priority of tag TAGNAME such that it is higher
3084 than the priority of ABOVETHIS."""
3085 self.tk.call(
3086 self._w, 'tag', 'raise', tagName, aboveThis)
3087 def tag_ranges(self, tagName):
3088 """Return a list of ranges of text which have tag TAGNAME."""
3089 return self.tk.splitlist(self.tk.call(
3090 self._w, 'tag', 'ranges', tagName))
3091 def tag_remove(self, tagName, index1, index2=None):
3092 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3093 self.tk.call(
3094 self._w, 'tag', 'remove', tagName, index1, index2)
3095 def window_cget(self, index, option):
3096 """Return the value of OPTION of an embedded window at INDEX."""
3097 if option[:1] != '-':
3098 option = '-' + option
3099 if option[-1:] == '_':
3100 option = option[:-1]
3101 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003102 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003103 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003104 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003105 window_config = window_configure
3106 def window_create(self, index, cnf={}, **kw):
3107 """Create a window at INDEX."""
3108 self.tk.call(
3109 (self._w, 'window', 'create', index)
3110 + self._options(cnf, kw))
3111 def window_names(self):
3112 """Return all names of embedded windows in this widget."""
3113 return self.tk.splitlist(
3114 self.tk.call(self._w, 'window', 'names'))
3115 def xview(self, *what):
3116 """Query and change horizontal position of the view."""
3117 if not what:
3118 return self._getdoubles(self.tk.call(self._w, 'xview'))
3119 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003120 def xview_moveto(self, fraction):
3121 """Adjusts the view in the window so that FRACTION of the
3122 total width of the canvas is off-screen to the left."""
3123 self.tk.call(self._w, 'xview', 'moveto', fraction)
3124 def xview_scroll(self, number, what):
3125 """Shift the x-view according to NUMBER which is measured
3126 in "units" or "pages" (WHAT)."""
3127 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003128 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003129 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003130 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003131 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003132 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003133 def yview_moveto(self, fraction):
3134 """Adjusts the view in the window so that FRACTION of the
3135 total height of the canvas is off-screen to the top."""
3136 self.tk.call(self._w, 'yview', 'moveto', fraction)
3137 def yview_scroll(self, number, what):
3138 """Shift the y-view according to NUMBER which is measured
3139 in "units" or "pages" (WHAT)."""
3140 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003141 def yview_pickplace(self, *what):
3142 """Obsolete function, use see."""
3143 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003144
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003145
Guido van Rossum28574b51996-10-21 15:16:51 +00003146class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003147 """Internal class. It wraps the command in the widget OptionMenu."""
3148 def __init__(self, var, value, callback=None):
3149 self.__value = value
3150 self.__var = var
3151 self.__callback = callback
3152 def __call__(self, *args):
3153 self.__var.set(self.__value)
3154 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003155 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003156
3157class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003158 """OptionMenu which allows the user to select a value from a menu."""
3159 def __init__(self, master, variable, value, *values, **kwargs):
3160 """Construct an optionmenu widget with the parent MASTER, with
3161 the resource textvariable set to VARIABLE, the initially selected
3162 value VALUE, the other menu values VALUES and an additional
3163 keyword argument command."""
3164 kw = {"borderwidth": 2, "textvariable": variable,
3165 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3166 "highlightthickness": 2}
3167 Widget.__init__(self, master, "menubutton", kw)
3168 self.widgetName = 'tk_optionMenu'
3169 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3170 self.menuname = menu._w
3171 # 'command' is the only supported keyword
3172 callback = kwargs.get('command')
3173 if kwargs.has_key('command'):
3174 del kwargs['command']
3175 if kwargs:
3176 raise TclError, 'unknown option -'+kwargs.keys()[0]
3177 menu.add_command(label=value,
3178 command=_setit(variable, value, callback))
3179 for v in values:
3180 menu.add_command(label=v,
3181 command=_setit(variable, v, callback))
3182 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003183
Fredrik Lundh06d28152000-08-09 18:03:12 +00003184 def __getitem__(self, name):
3185 if name == 'menu':
3186 return self.__menu
3187 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003188
Fredrik Lundh06d28152000-08-09 18:03:12 +00003189 def destroy(self):
3190 """Destroy this widget and the associated menu."""
3191 Menubutton.destroy(self)
3192 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003193
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003194class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003195 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003196 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003197 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3198 self.name = None
3199 if not master:
3200 master = _default_root
3201 if not master:
3202 raise RuntimeError, 'Too early to create image'
3203 self.tk = master.tk
3204 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003205 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003206 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003207 # The following is needed for systems where id(x)
3208 # can return a negative number, such as Linux/m68k:
3209 if name[0] == '-': name = '_' + name[1:]
3210 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3211 elif kw: cnf = kw
3212 options = ()
3213 for k, v in cnf.items():
3214 if callable(v):
3215 v = self._register(v)
3216 options = options + ('-'+k, v)
3217 self.tk.call(('image', 'create', imgtype, name,) + options)
3218 self.name = name
3219 def __str__(self): return self.name
3220 def __del__(self):
3221 if self.name:
3222 try:
3223 self.tk.call('image', 'delete', self.name)
3224 except TclError:
3225 # May happen if the root was destroyed
3226 pass
3227 def __setitem__(self, key, value):
3228 self.tk.call(self.name, 'configure', '-'+key, value)
3229 def __getitem__(self, key):
3230 return self.tk.call(self.name, 'configure', '-'+key)
3231 def configure(self, **kw):
3232 """Configure the image."""
3233 res = ()
3234 for k, v in _cnfmerge(kw).items():
3235 if v is not None:
3236 if k[-1] == '_': k = k[:-1]
3237 if callable(v):
3238 v = self._register(v)
3239 res = res + ('-'+k, v)
3240 self.tk.call((self.name, 'config') + res)
3241 config = configure
3242 def height(self):
3243 """Return the height of the image."""
3244 return getint(
3245 self.tk.call('image', 'height', self.name))
3246 def type(self):
3247 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3248 return self.tk.call('image', 'type', self.name)
3249 def width(self):
3250 """Return the width of the image."""
3251 return getint(
3252 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003253
3254class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003255 """Widget which can display colored images in GIF, PPM/PGM format."""
3256 def __init__(self, name=None, cnf={}, master=None, **kw):
3257 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003258
Fredrik Lundh06d28152000-08-09 18:03:12 +00003259 Valid resource names: data, format, file, gamma, height, palette,
3260 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003261 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003262 def blank(self):
3263 """Display a transparent image."""
3264 self.tk.call(self.name, 'blank')
3265 def cget(self, option):
3266 """Return the value of OPTION."""
3267 return self.tk.call(self.name, 'cget', '-' + option)
3268 # XXX config
3269 def __getitem__(self, key):
3270 return self.tk.call(self.name, 'cget', '-' + key)
3271 # XXX copy -from, -to, ...?
3272 def copy(self):
3273 """Return a new PhotoImage with the same image as this widget."""
3274 destImage = PhotoImage()
3275 self.tk.call(destImage, 'copy', self.name)
3276 return destImage
3277 def zoom(self,x,y=''):
3278 """Return a new PhotoImage with the same image as this widget
3279 but zoom it with X and Y."""
3280 destImage = PhotoImage()
3281 if y=='': y=x
3282 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3283 return destImage
3284 def subsample(self,x,y=''):
3285 """Return a new PhotoImage based on the same image as this widget
3286 but use only every Xth or Yth pixel."""
3287 destImage = PhotoImage()
3288 if y=='': y=x
3289 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3290 return destImage
3291 def get(self, x, y):
3292 """Return the color (red, green, blue) of the pixel at X,Y."""
3293 return self.tk.call(self.name, 'get', x, y)
3294 def put(self, data, to=None):
3295 """Put row formated colors to image starting from
3296 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3297 args = (self.name, 'put', data)
3298 if to:
3299 if to[0] == '-to':
3300 to = to[1:]
3301 args = args + ('-to',) + tuple(to)
3302 self.tk.call(args)
3303 # XXX read
3304 def write(self, filename, format=None, from_coords=None):
3305 """Write image to file FILENAME in FORMAT starting from
3306 position FROM_COORDS."""
3307 args = (self.name, 'write', filename)
3308 if format:
3309 args = args + ('-format', format)
3310 if from_coords:
3311 args = args + ('-from',) + tuple(from_coords)
3312 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003313
3314class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003315 """Widget which can display a bitmap."""
3316 def __init__(self, name=None, cnf={}, master=None, **kw):
3317 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003318
Fredrik Lundh06d28152000-08-09 18:03:12 +00003319 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003320 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003321
3322def image_names(): return _default_root.tk.call('image', 'names')
3323def image_types(): return _default_root.tk.call('image', 'types')
3324
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003325
3326class Spinbox(Widget):
3327 """spinbox widget."""
3328 def __init__(self, master=None, cnf={}, **kw):
3329 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003330
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003331 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003332
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003333 activebackground, background, borderwidth,
3334 cursor, exportselection, font, foreground,
3335 highlightbackground, highlightcolor,
3336 highlightthickness, insertbackground,
3337 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003338 insertontime, insertwidth, justify, relief,
3339 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003340 selectbackground, selectborderwidth
3341 selectforeground, takefocus, textvariable
3342 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003343
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003344 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003345
3346 buttonbackground, buttoncursor,
3347 buttondownrelief, buttonuprelief,
3348 command, disabledbackground,
3349 disabledforeground, format, from,
3350 invalidcommand, increment,
3351 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003352 validate, validatecommand values,
3353 width, wrap,
3354 """
3355 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003356
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003357 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003358 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3359 rectangle which encloses the character given by index.
3360
3361 The first two elements of the list give the x and y
3362 coordinates of the upper-left corner of the screen
3363 area covered by the character (in pixels relative
3364 to the widget) and the last two elements give the
3365 width and height of the character, in pixels. The
3366 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003367 visible area of the window.
3368 """
3369 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003370
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003371 def delete(self, first, last=None):
3372 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003373
3374 First is the index of the first character to delete,
3375 and last is the index of the character just after
3376 the last one to delete. If last isn't specified it
3377 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003378 deleted. This command returns an empty string.
3379 """
3380 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003381
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003382 def get(self):
3383 """Returns the spinbox's string"""
3384 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003385
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003386 def icursor(self, index):
3387 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003388
3389 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003390 the character given by index. Returns an empty string
3391 """
3392 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003393
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003394 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003395 """Returns the name of the widget at position x, y
3396
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003397 Return value is one of: none, buttondown, buttonup, entry
3398 """
3399 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003400
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003401 def index(self, index):
3402 """Returns the numerical index corresponding to index
3403 """
3404 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003405
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003406 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003407 """Insert string s at index
3408
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003409 Returns an empty string.
3410 """
3411 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003412
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003413 def invoke(self, element):
3414 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003415
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003416 The element could be buttondown or buttonup
3417 triggering the action associated with it.
3418 """
3419 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003420
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003421 def scan(self, *args):
3422 """Internal function."""
3423 return self._getints(
3424 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003425
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003426 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003427 """Records x and the current view in the spinbox window;
3428
3429 used in conjunction with later scan dragto commands.
3430 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003431 press in the widget. It returns an empty string.
3432 """
3433 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003434
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003435 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003436 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003437 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003438
3439 It then adjusts the view left or right by 10 times the
3440 difference in x-coordinates. This command is typically
3441 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003442 produce the effect of dragging the spinbox at high speed
3443 through the window. The return value is an empty string.
3444 """
3445 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003446
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003447 def selection(self, *args):
3448 """Internal function."""
3449 return self._getints(
3450 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003451
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003452 def selection_adjust(self, index):
3453 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003454 given by index,
3455
3456 Then adjust that end of the selection to be at index
3457 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003458 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003459 select to commands. If the selection isn't currently in
3460 the spinbox, then a new selection is created to include
3461 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003462 anchor point, inclusive. Returns an empty string.
3463 """
3464 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003465
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003466 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003467 """Clear the selection
3468
3469 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003470 command has no effect. Returns an empty string.
3471 """
3472 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003473
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003474 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003475 """Sets or gets the currently selected element.
3476
3477 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003478 displayed depressed
3479 """
3480 return self.selection("element", element)
3481
3482###########################################################################
3483
3484class LabelFrame(Widget):
3485 """labelframe widget."""
3486 def __init__(self, master=None, cnf={}, **kw):
3487 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003488
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003489 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003490
3491 borderwidth, cursor, font, foreground,
3492 highlightbackground, highlightcolor,
3493 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003494 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003495
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003496 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003497
3498 background, class, colormap, container,
3499 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003500 visual, width
3501 """
3502 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003503
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003504########################################################################
3505
3506class PanedWindow(Widget):
3507 """panedwindow widget."""
3508 def __init__(self, master=None, cnf={}, **kw):
3509 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003510
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003511 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003512
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003513 background, borderwidth, cursor, height,
3514 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003515
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003516 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003517
3518 handlepad, handlesize, opaqueresize,
3519 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003520 sashwidth, showhandle,
3521 """
3522 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3523
3524 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003525 """Add a child widget to the panedwindow in a new pane.
3526
3527 The child argument is the name of the child widget
3528 followed by pairs of arguments that specify how to
3529 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003530 accepted by the configure subcommand.
3531 """
3532 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003533
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003534 def remove(self, child):
3535 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003536
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003537 All geometry management options for child will be forgotten.
3538 """
3539 self.tk.call(self._w, 'forget', child)
3540 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003541
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003542 def identify(self, x, y):
3543 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003544
3545 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003546 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003547 handle, and a word indicating whether it is over a sash
3548 or a handle, such as {0 sash} or {2 handle}. If the point
3549 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003550 an empty list.
3551 """
3552 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003553
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003554 def proxy(self, *args):
3555 """Internal function."""
3556 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003557 self.tk.call((self._w, 'proxy') + args)) or ()
3558
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003559 def proxy_coord(self):
3560 """Return the x and y pair of the most recent proxy location
3561 """
3562 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003563
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003564 def proxy_forget(self):
3565 """Remove the proxy from the display.
3566 """
3567 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003568
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003569 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003570 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003571 """
3572 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003573
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003574 def sash(self, *args):
3575 """Internal function."""
3576 return self._getints(
3577 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003578
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003579 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003580 """Return the current x and y pair for the sash given by index.
3581
3582 Index must be an integer between 0 and 1 less than the
3583 number of panes in the panedwindow. The coordinates given are
3584 those of the top left corner of the region containing the sash.
3585 pathName sash dragto index x y This command computes the
3586 difference between the given coordinates and the coordinates
3587 given to the last sash coord command for the given sash. It then
3588 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003589 empty string.
3590 """
3591 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003592
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003593 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003594 """Records x and y for the sash given by index;
3595
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003596 Used in conjunction with later dragto commands to move the sash.
3597 """
3598 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003599
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003600 def sash_place(self, index, x, y):
3601 """Place the sash given by index at the given coordinates
3602 """
3603 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003604
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003605 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003606 """Query a management option for window.
3607
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003608 Option may be any value allowed by the paneconfigure subcommand
3609 """
3610 return self.tk.call(
3611 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003612
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003613 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003614 """Query or modify the management options for window.
3615
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003616 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003617 of the available options for pathName. If option is
3618 specified with no value, then the command returns a list
3619 describing the one named option (this list will be identical
3620 to the corresponding sublist of the value returned if no
3621 option is specified). If one or more option-value pairs are
3622 specified, then the command modifies the given widget
3623 option(s) to have the given value(s); in this case the
3624 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003625 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003626
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003627 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003628 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003629 should be the name of a window already managed by pathName.
3630 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003631 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003632 should be the name of a window already managed by pathName.
3633 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003634 Specify a height for the window. The height will be the
3635 outer dimension of the window including its border, if
3636 any. If size is an empty string, or if -height is not
3637 specified, then the height requested internally by the
3638 window will be used initially; the height may later be
3639 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003640 Size may be any value accepted by Tk_GetPixels.
3641 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003642 Specifies that the size of the window cannot be made
3643 less than n. This constraint only affects the size of
3644 the widget in the paned dimension -- the x dimension
3645 for horizontal panedwindows, the y dimension for
3646 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003647 Tk_GetPixels.
3648 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003649 Specifies a non-negative value indicating how much
3650 extra space to leave on each side of the window in
3651 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003652 accepted by Tk_GetPixels.
3653 pady n
3654 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003655 extra space to leave on each side of the window in
3656 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003657 accepted by Tk_GetPixels.
3658 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003659 If a window's pane is larger than the requested
3660 dimensions of the window, this option may be used
3661 to position (or stretch) the window within its pane.
3662 Style is a string that contains zero or more of the
3663 characters n, s, e or w. The string can optionally
3664 contains spaces or commas, but they are ignored. Each
3665 letter refers to a side (north, south, east, or west)
3666 that the window will "stick" to. If both n and s
3667 (or e and w) are specified, the window will be
3668 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003669 its cavity.
3670 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003671 Specify a width for the window. The width will be
3672 the outer dimension of the window including its
3673 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003674 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003675 internally by the window will be used initially; the
3676 width may later be adjusted by the movement of sashes
3677 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003678 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003679
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003680 """
3681 if cnf is None and not kw:
3682 cnf = {}
3683 for x in self.tk.split(
3684 self.tk.call(self._w,
3685 'paneconfigure', tagOrId)):
3686 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3687 return cnf
3688 if type(cnf) == StringType and not kw:
3689 x = self.tk.split(self.tk.call(
3690 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3691 return (x[0][1:],) + x[1:]
3692 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3693 self._options(cnf, kw))
3694 paneconfig = paneconfigure
3695
3696 def panes(self):
3697 """Returns an ordered list of the child panes."""
3698 return self.tk.call(self._w, 'panes')
3699
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003700######################################################################
3701# Extensions:
3702
3703class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003704 def __init__(self, master=None, cnf={}, **kw):
3705 Widget.__init__(self, master, 'studbutton', cnf, kw)
3706 self.bind('<Any-Enter>', self.tkButtonEnter)
3707 self.bind('<Any-Leave>', self.tkButtonLeave)
3708 self.bind('<1>', self.tkButtonDown)
3709 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003710
3711class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003712 def __init__(self, master=None, cnf={}, **kw):
3713 Widget.__init__(self, master, 'tributton', cnf, kw)
3714 self.bind('<Any-Enter>', self.tkButtonEnter)
3715 self.bind('<Any-Leave>', self.tkButtonLeave)
3716 self.bind('<1>', self.tkButtonDown)
3717 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3718 self['fg'] = self['bg']
3719 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003720
Guido van Rossumc417ef81996-08-21 23:38:59 +00003721######################################################################
3722# Test:
3723
3724def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003725 root = Tk()
3726 text = "This is Tcl/Tk version %s" % TclVersion
3727 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003728 try:
3729 text = text + unicode("\nThis should be a cedilla: \347",
3730 "iso-8859-1")
3731 except NameError:
3732 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003733 label = Label(root, text=text)
3734 label.pack()
3735 test = Button(root, text="Click me!",
3736 command=lambda root=root: root.test.configure(
3737 text="[%s]" % root.test['text']))
3738 test.pack()
3739 root.test = test
3740 quit = Button(root, text="QUIT", command=root.destroy)
3741 quit.pack()
3742 # The following three commands are needed so the window pops
3743 # up on top on Windows...
3744 root.iconify()
3745 root.update()
3746 root.deiconify()
3747 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003748
3749if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003750 _test()