blob: 11dae120d4d250567411e44810ec037f415c63c7 [file] [log] [blame]
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001"""Wrapper functions for Tcl/Tk.
2
3Tkinter provides classes which allow the display, positioning and
4control of widgets. Toplevel widgets are Tk and Toplevel. Other
5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00006Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
Raymond Hettingerff41c482003-04-06 09:01:11 +00007LabelFrame and PanedWindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00008
Raymond Hettingerff41c482003-04-06 09:01:11 +00009Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
Martin v. Löwis2ec36272002-10-13 10:22:08 +000011under Tk.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000012
13Widgets are positioned with one of the geometry managers Place, Pack
14or Grid. These managers can be called with methods place, pack, grid
15available in every Widget.
16
Guido van Rossuma0adb922001-09-01 18:29:55 +000017Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000019
20Example (Hello, World):
21import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25frame.pack(fill=BOTH,expand=1)
26label = Tkinter.Label(frame, text="Hello, World")
27label.pack(fill=X, expand=1)
28button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
29button.pack(side=BOTTOM)
30tk.mainloop()
31"""
Guido van Rossum2dcf5291994-07-06 09:23:20 +000032
Guido van Rossum37dcab11996-05-16 16:00:19 +000033__version__ = "$Revision$"
34
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import sys
36if sys.platform == "win32":
Fredrik Lundh06d28152000-08-09 18:03:12 +000037 import FixTk # Attempt to configure Tcl/Tk without requiring PATH
Guido van Rossumf8d579c1999-01-04 18:06:45 +000038import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000039tkinter = _tkinter # b/w compat for export
40TclError = _tkinter.TclError
Guido van Rossum7e9394a1995-03-17 16:21:33 +000041from types import *
Guido van Rossuma5773dd1995-09-07 19:22:00 +000042from Tkconstants import *
Guido van Rossumf0c891a1998-04-29 21:43:36 +000043try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000044 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000045except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000046 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000047
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000048wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000049
Eric S. Raymondfc170b12001-02-09 11:51:27 +000050TkVersion = float(_tkinter.TK_VERSION)
51TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000052
Guido van Rossumd6615ab1997-08-05 02:35:01 +000053READABLE = _tkinter.READABLE
54WRITABLE = _tkinter.WRITABLE
55EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000056
57# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
58try: _tkinter.createfilehandler
59except AttributeError: _tkinter.createfilehandler = None
60try: _tkinter.deletefilehandler
61except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000062
63
Guido van Rossum2dcf5291994-07-06 09:23:20 +000064def _flatten(tuple):
Fredrik Lundh06d28152000-08-09 18:03:12 +000065 """Internal function."""
66 res = ()
67 for item in tuple:
68 if type(item) in (TupleType, ListType):
69 res = res + _flatten(item)
70 elif item is not None:
71 res = res + (item,)
72 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000073
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000074try: _flatten = _tkinter._flatten
75except AttributeError: pass
76
Guido van Rossum2dcf5291994-07-06 09:23:20 +000077def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000078 """Internal function."""
79 if type(cnfs) is DictionaryType:
80 return cnfs
81 elif type(cnfs) in (NoneType, StringType):
82 return cnfs
83 else:
84 cnf = {}
85 for c in _flatten(cnfs):
86 try:
87 cnf.update(c)
88 except (AttributeError, TypeError), msg:
89 print "_cnfmerge: fallback due to:", msg
90 for k, v in c.items():
91 cnf[k] = v
92 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000093
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000094try: _cnfmerge = _tkinter._cnfmerge
95except AttributeError: pass
96
Guido van Rossum2dcf5291994-07-06 09:23:20 +000097class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000099
Fredrik Lundh06d28152000-08-09 18:03:12 +0000100 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000101
Fredrik Lundh06d28152000-08-09 18:03:12 +0000102 KeyPress, KeyRelease - for keyboard events
103 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
104 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
105 Colormap, Gravity, Reparent, Property, Destroy, Activate,
106 Deactivate - for window events.
107
108 If a callback function for one of these events is registered
109 using bind, bind_all, bind_class, or tag_bind, the callback is
110 called with an Event as first argument. It will have the
111 following attributes (in braces are the event types for which
112 the attribute is valid):
113
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000114 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000115 num - mouse button pressed (ButtonPress, ButtonRelease)
116 focus - whether the window has the focus (Enter, Leave)
117 height - height of the exposed window (Configure, Expose)
118 width - width of the exposed window (Configure, Expose)
119 keycode - keycode of the pressed key (KeyPress, KeyRelease)
120 state - state of the event as a number (ButtonPress, ButtonRelease,
121 Enter, KeyPress, KeyRelease,
122 Leave, Motion)
123 state - state as a string (Visibility)
124 time - when the event occurred
125 x - x-position of the mouse
126 y - y-position of the mouse
127 x_root - x-position of the mouse on the screen
128 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
129 y_root - y-position of the mouse on the screen
130 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
131 char - pressed character (KeyPress, KeyRelease)
132 send_event - see X/Windows documentation
133 keysym - keysym of the the event as a string (KeyPress, KeyRelease)
134 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
135 type - type of the event as a number
136 widget - widget in which the event occurred
137 delta - delta of wheel movement (MouseWheel)
138 """
139 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000140
Guido van Rossumc4570481998-03-20 20:45:49 +0000141_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000142_default_root = None
143
Guido van Rossumc4570481998-03-20 20:45:49 +0000144def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000145 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000146
Fredrik Lundh06d28152000-08-09 18:03:12 +0000147 Call this function to inhibit that the first instance of
148 Tk is used for windows without an explicit parent window.
149 """
150 global _support_default_root
151 _support_default_root = 0
152 global _default_root
153 _default_root = None
154 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000155
Guido van Rossum45853db1994-06-20 12:19:19 +0000156def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000157 """Internal function."""
158 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000159
Guido van Rossum97aeca11994-07-07 13:12:12 +0000160def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000161 """Internal function. Calling it will throw the exception SystemExit."""
162 raise SystemExit, code
Guido van Rossum97aeca11994-07-07 13:12:12 +0000163
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000164_varnum = 0
165class Variable:
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 = ""
171 def __init__(self, master=None):
172 """Construct a variable with an optional MASTER as master widget.
173 The variable is named PY_VAR_number in Tcl.
174 """
175 global _varnum
176 if not master:
177 master = _default_root
178 self._master = master
179 self._tk = master.tk
180 self._name = 'PY_VAR' + `_varnum`
181 _varnum = _varnum + 1
182 self.set(self._default)
183 def __del__(self):
184 """Unset the variable in Tcl."""
185 self._tk.globalunsetvar(self._name)
186 def __str__(self):
187 """Return the name of the variable in Tcl."""
188 return self._name
189 def set(self, value):
190 """Set the variable to VALUE."""
191 return self._tk.globalsetvar(self._name, value)
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000192 def get(self):
193 """Return value of variable."""
194 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000195 def trace_variable(self, mode, callback):
196 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000197
Fredrik Lundh06d28152000-08-09 18:03:12 +0000198 MODE is one of "r", "w", "u" for read, write, undefine.
199 CALLBACK must be a function which is called when
200 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000201
Fredrik Lundh06d28152000-08-09 18:03:12 +0000202 Return the name of the callback.
203 """
204 cbname = self._master._register(callback)
205 self._tk.call("trace", "variable", self._name, mode, cbname)
206 return cbname
207 trace = trace_variable
208 def trace_vdelete(self, mode, cbname):
209 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000210
Fredrik Lundh06d28152000-08-09 18:03:12 +0000211 MODE is one of "r", "w", "u" for read, write, undefine.
212 CBNAME is the name of the callback returned from trace_variable or trace.
213 """
214 self._tk.call("trace", "vdelete", self._name, mode, cbname)
215 self._master.deletecommand(cbname)
216 def trace_vinfo(self):
217 """Return all trace callback information."""
218 return map(self._tk.split, self._tk.splitlist(
219 self._tk.call("trace", "vinfo", self._name)))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000220
221class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000222 """Value holder for strings variables."""
223 _default = ""
224 def __init__(self, master=None):
225 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000226
Fredrik Lundh06d28152000-08-09 18:03:12 +0000227 MASTER can be given as master widget."""
228 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000229
Fredrik Lundh06d28152000-08-09 18:03:12 +0000230 def get(self):
231 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000232 value = self._tk.globalgetvar(self._name)
233 if isinstance(value, basestring):
234 return value
235 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000236
237class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000238 """Value holder for integer variables."""
239 _default = 0
240 def __init__(self, master=None):
241 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000242
Fredrik Lundh06d28152000-08-09 18:03:12 +0000243 MASTER can be given as master widget."""
244 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000245
Martin v. Löwis70c3dda2003-01-22 09:17:38 +0000246 def set(self, value):
247 """Set the variable to value, converting booleans to integers."""
248 if isinstance(value, bool):
249 value = int(value)
250 return Variable.set(self, value)
251
Fredrik Lundh06d28152000-08-09 18:03:12 +0000252 def get(self):
253 """Return the value of the variable as an integer."""
254 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000255
256class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000257 """Value holder for float variables."""
258 _default = 0.0
259 def __init__(self, master=None):
260 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000261
Fredrik Lundh06d28152000-08-09 18:03:12 +0000262 MASTER can be given as a master widget."""
263 Variable.__init__(self, master)
264
265 def get(self):
266 """Return the value of the variable as a float."""
267 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000268
269class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000270 """Value holder for boolean variables."""
271 _default = "false"
272 def __init__(self, master=None):
273 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000274
Fredrik Lundh06d28152000-08-09 18:03:12 +0000275 MASTER can be given as a master widget."""
276 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000277
Fredrik Lundh06d28152000-08-09 18:03:12 +0000278 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000279 """Return the value of the variable as a bool."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000280 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000281
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000282def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000283 """Run the main loop of Tcl."""
284 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000285
Guido van Rossum0132f691998-04-30 17:50:36 +0000286getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000287
Guido van Rossum0132f691998-04-30 17:50:36 +0000288getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000289
290def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000291 """Convert true and false to integer values 1 and 0."""
292 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000293
Guido van Rossum368e06b1997-11-07 20:38:49 +0000294# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000295class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000296 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000297
Fredrik Lundh06d28152000-08-09 18:03:12 +0000298 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000299
Fredrik Lundh06d28152000-08-09 18:03:12 +0000300 # XXX font command?
301 _tclCommands = None
302 def destroy(self):
303 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000304
Fredrik Lundh06d28152000-08-09 18:03:12 +0000305 Delete all Tcl commands created for
306 this widget in the Tcl interpreter."""
307 if self._tclCommands is not None:
308 for name in self._tclCommands:
309 #print '- Tkinter: deleted command', name
310 self.tk.deletecommand(name)
311 self._tclCommands = None
312 def deletecommand(self, name):
313 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000314
Fredrik Lundh06d28152000-08-09 18:03:12 +0000315 Delete the Tcl command provided in NAME."""
316 #print '- Tkinter: deleted command', name
317 self.tk.deletecommand(name)
318 try:
319 self._tclCommands.remove(name)
320 except ValueError:
321 pass
322 def tk_strictMotif(self, boolean=None):
323 """Set Tcl internal variable, whether the look and feel
324 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000325
Fredrik Lundh06d28152000-08-09 18:03:12 +0000326 A parameter of 1 means adhere to Motif (e.g. no color
327 change if mouse passes over slider).
328 Returns the set value."""
329 return self.tk.getboolean(self.tk.call(
330 'set', 'tk_strictMotif', boolean))
331 def tk_bisque(self):
332 """Change the color scheme to light brown as used in Tk 3.6 and before."""
333 self.tk.call('tk_bisque')
334 def tk_setPalette(self, *args, **kw):
335 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000336
Fredrik Lundh06d28152000-08-09 18:03:12 +0000337 A single color as argument will cause that all colors of Tk
338 widget elements are derived from this.
339 Alternatively several keyword parameters and its associated
340 colors can be given. The following keywords are valid:
341 activeBackground, foreground, selectColor,
342 activeForeground, highlightBackground, selectBackground,
343 background, highlightColor, selectForeground,
344 disabledForeground, insertBackground, troughColor."""
345 self.tk.call(('tk_setPalette',)
346 + _flatten(args) + _flatten(kw.items()))
347 def tk_menuBar(self, *args):
348 """Do not use. Needed in Tk 3.6 and earlier."""
349 pass # obsolete since Tk 4.0
350 def wait_variable(self, name='PY_VAR'):
351 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000352
Fredrik Lundh06d28152000-08-09 18:03:12 +0000353 A parameter of type IntVar, StringVar, DoubleVar or
354 BooleanVar must be given."""
355 self.tk.call('tkwait', 'variable', name)
356 waitvar = wait_variable # XXX b/w compat
357 def wait_window(self, window=None):
358 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000359
Fredrik Lundh06d28152000-08-09 18:03:12 +0000360 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000361 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000362 window = self
363 self.tk.call('tkwait', 'window', window._w)
364 def wait_visibility(self, window=None):
365 """Wait until the visibility of a WIDGET changes
366 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000367
Fredrik Lundh06d28152000-08-09 18:03:12 +0000368 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000369 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000370 window = self
371 self.tk.call('tkwait', 'visibility', window._w)
372 def setvar(self, name='PY_VAR', value='1'):
373 """Set Tcl variable NAME to VALUE."""
374 self.tk.setvar(name, value)
375 def getvar(self, name='PY_VAR'):
376 """Return value of Tcl variable NAME."""
377 return self.tk.getvar(name)
378 getint = int
379 getdouble = float
380 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000381 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000382 return self.tk.getboolean(s)
383 def focus_set(self):
384 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000385
Fredrik Lundh06d28152000-08-09 18:03:12 +0000386 If the application currently does not have the focus
387 this widget will get the focus if the application gets
388 the focus through the window manager."""
389 self.tk.call('focus', self._w)
390 focus = focus_set # XXX b/w compat?
391 def focus_force(self):
392 """Direct input focus to this widget even if the
393 application does not have the focus. Use with
394 caution!"""
395 self.tk.call('focus', '-force', self._w)
396 def focus_get(self):
397 """Return the widget which has currently the focus in the
398 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000399
Fredrik Lundh06d28152000-08-09 18:03:12 +0000400 Use focus_displayof to allow working with several
401 displays. Return None if application does not have
402 the focus."""
403 name = self.tk.call('focus')
404 if name == 'none' or not name: return None
405 return self._nametowidget(name)
406 def focus_displayof(self):
407 """Return the widget which has currently the focus on the
408 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000409
Fredrik Lundh06d28152000-08-09 18:03:12 +0000410 Return None if the application does not have the focus."""
411 name = self.tk.call('focus', '-displayof', self._w)
412 if name == 'none' or not name: return None
413 return self._nametowidget(name)
414 def focus_lastfor(self):
415 """Return the widget which would have the focus if top level
416 for this widget gets the focus from the window manager."""
417 name = self.tk.call('focus', '-lastfor', self._w)
418 if name == 'none' or not name: return None
419 return self._nametowidget(name)
420 def tk_focusFollowsMouse(self):
421 """The widget under mouse will get automatically focus. Can not
422 be disabled easily."""
423 self.tk.call('tk_focusFollowsMouse')
424 def tk_focusNext(self):
425 """Return the next widget in the focus order which follows
426 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000427
Fredrik Lundh06d28152000-08-09 18:03:12 +0000428 The focus order first goes to the next child, then to
429 the children of the child recursively and then to the
430 next sibling which is higher in the stacking order. A
431 widget is omitted if it has the takefocus resource set
432 to 0."""
433 name = self.tk.call('tk_focusNext', self._w)
434 if not name: return None
435 return self._nametowidget(name)
436 def tk_focusPrev(self):
437 """Return previous widget in the focus order. See tk_focusNext for details."""
438 name = self.tk.call('tk_focusPrev', self._w)
439 if not name: return None
440 return self._nametowidget(name)
441 def after(self, ms, func=None, *args):
442 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000443
Fredrik Lundh06d28152000-08-09 18:03:12 +0000444 MS specifies the time in milliseconds. FUNC gives the
445 function which shall be called. Additional parameters
446 are given as parameters to the function call. Return
447 identifier to cancel scheduling with after_cancel."""
448 if not func:
449 # I'd rather use time.sleep(ms*0.001)
450 self.tk.call('after', ms)
451 else:
452 # XXX Disgusting hack to clean up after calling func
453 tmp = []
454 def callit(func=func, args=args, self=self, tmp=tmp):
455 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000456 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000457 finally:
458 try:
459 self.deletecommand(tmp[0])
460 except TclError:
461 pass
462 name = self._register(callit)
463 tmp.append(name)
464 return self.tk.call('after', ms, name)
465 def after_idle(self, func, *args):
466 """Call FUNC once if the Tcl main loop has no event to
467 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000468
Fredrik Lundh06d28152000-08-09 18:03:12 +0000469 Return an identifier to cancel the scheduling with
470 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000471 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000472 def after_cancel(self, id):
473 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000474
Fredrik Lundh06d28152000-08-09 18:03:12 +0000475 Identifier returned by after or after_idle must be
476 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000477 try:
478 (script, type) = self.tk.splitlist(
479 self.tk.call('after', 'info', id))
480 self.deletecommand(script)
481 except TclError:
482 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000483 self.tk.call('after', 'cancel', id)
484 def bell(self, displayof=0):
485 """Ring a display's bell."""
486 self.tk.call(('bell',) + self._displayof(displayof))
487 # Clipboard handling:
488 def clipboard_clear(self, **kw):
489 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000490
Fredrik Lundh06d28152000-08-09 18:03:12 +0000491 A widget specified for the optional displayof keyword
492 argument specifies the target display."""
493 if not kw.has_key('displayof'): kw['displayof'] = self._w
494 self.tk.call(('clipboard', 'clear') + self._options(kw))
495 def clipboard_append(self, string, **kw):
496 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000497
Fredrik Lundh06d28152000-08-09 18:03:12 +0000498 A widget specified at the optional displayof keyword
499 argument specifies the target display. The clipboard
500 can be retrieved with selection_get."""
501 if not kw.has_key('displayof'): kw['displayof'] = self._w
502 self.tk.call(('clipboard', 'append') + self._options(kw)
503 + ('--', string))
504 # XXX grab current w/o window argument
505 def grab_current(self):
506 """Return widget which has currently the grab in this application
507 or None."""
508 name = self.tk.call('grab', 'current', self._w)
509 if not name: return None
510 return self._nametowidget(name)
511 def grab_release(self):
512 """Release grab for this widget if currently set."""
513 self.tk.call('grab', 'release', self._w)
514 def grab_set(self):
515 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000516
Fredrik Lundh06d28152000-08-09 18:03:12 +0000517 A grab directs all events to this and descendant
518 widgets in the application."""
519 self.tk.call('grab', 'set', self._w)
520 def grab_set_global(self):
521 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000522
Fredrik Lundh06d28152000-08-09 18:03:12 +0000523 A global grab directs all events to this and
524 descendant widgets on the display. Use with caution -
525 other applications do not get events anymore."""
526 self.tk.call('grab', 'set', '-global', self._w)
527 def grab_status(self):
528 """Return None, "local" or "global" if this widget has
529 no, a local or a global grab."""
530 status = self.tk.call('grab', 'status', self._w)
531 if status == 'none': status = None
532 return status
533 def lower(self, belowThis=None):
534 """Lower this widget in the stacking order."""
535 self.tk.call('lower', self._w, belowThis)
536 def option_add(self, pattern, value, priority = None):
537 """Set a VALUE (second parameter) for an option
538 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000539
Fredrik Lundh06d28152000-08-09 18:03:12 +0000540 An optional third parameter gives the numeric priority
541 (defaults to 80)."""
542 self.tk.call('option', 'add', pattern, value, priority)
543 def option_clear(self):
544 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000545
Fredrik Lundh06d28152000-08-09 18:03:12 +0000546 It will be reloaded if option_add is called."""
547 self.tk.call('option', 'clear')
548 def option_get(self, name, className):
549 """Return the value for an option NAME for this widget
550 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000551
Fredrik Lundh06d28152000-08-09 18:03:12 +0000552 Values with higher priority override lower values."""
553 return self.tk.call('option', 'get', self._w, name, className)
554 def option_readfile(self, fileName, priority = None):
555 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000556
Fredrik Lundh06d28152000-08-09 18:03:12 +0000557 An optional second parameter gives the numeric
558 priority."""
559 self.tk.call('option', 'readfile', fileName, priority)
560 def selection_clear(self, **kw):
561 """Clear the current X selection."""
562 if not kw.has_key('displayof'): kw['displayof'] = self._w
563 self.tk.call(('selection', 'clear') + self._options(kw))
564 def selection_get(self, **kw):
565 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000566
Fredrik Lundh06d28152000-08-09 18:03:12 +0000567 A keyword parameter selection specifies the name of
568 the selection and defaults to PRIMARY. A keyword
569 parameter displayof specifies a widget on the display
570 to use."""
571 if not kw.has_key('displayof'): kw['displayof'] = self._w
572 return self.tk.call(('selection', 'get') + self._options(kw))
573 def selection_handle(self, command, **kw):
574 """Specify a function COMMAND to call if the X
575 selection owned by this widget is queried by another
576 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000577
Fredrik Lundh06d28152000-08-09 18:03:12 +0000578 This function must return the contents of the
579 selection. The function will be called with the
580 arguments OFFSET and LENGTH which allows the chunking
581 of very long selections. The following keyword
582 parameters can be provided:
583 selection - name of the selection (default PRIMARY),
584 type - type of the selection (e.g. STRING, FILE_NAME)."""
585 name = self._register(command)
586 self.tk.call(('selection', 'handle') + self._options(kw)
587 + (self._w, name))
588 def selection_own(self, **kw):
589 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000590
Fredrik Lundh06d28152000-08-09 18:03:12 +0000591 A keyword parameter selection specifies the name of
592 the selection (default PRIMARY)."""
593 self.tk.call(('selection', 'own') +
594 self._options(kw) + (self._w,))
595 def selection_own_get(self, **kw):
596 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000597
Fredrik Lundh06d28152000-08-09 18:03:12 +0000598 The following keyword parameter can
599 be provided:
600 selection - name of the selection (default PRIMARY),
601 type - type of the selection (e.g. STRING, FILE_NAME)."""
602 if not kw.has_key('displayof'): kw['displayof'] = self._w
603 name = self.tk.call(('selection', 'own') + self._options(kw))
604 if not name: return None
605 return self._nametowidget(name)
606 def send(self, interp, cmd, *args):
607 """Send Tcl command CMD to different interpreter INTERP to be executed."""
608 return self.tk.call(('send', interp, cmd) + args)
609 def lower(self, belowThis=None):
610 """Lower this widget in the stacking order."""
611 self.tk.call('lower', self._w, belowThis)
612 def tkraise(self, aboveThis=None):
613 """Raise this widget in the stacking order."""
614 self.tk.call('raise', self._w, aboveThis)
615 lift = tkraise
616 def colormodel(self, value=None):
617 """Useless. Not implemented in Tk."""
618 return self.tk.call('tk', 'colormodel', self._w, value)
619 def winfo_atom(self, name, displayof=0):
620 """Return integer which represents atom NAME."""
621 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
622 return getint(self.tk.call(args))
623 def winfo_atomname(self, id, displayof=0):
624 """Return name of atom with identifier ID."""
625 args = ('winfo', 'atomname') \
626 + self._displayof(displayof) + (id,)
627 return self.tk.call(args)
628 def winfo_cells(self):
629 """Return number of cells in the colormap for this widget."""
630 return getint(
631 self.tk.call('winfo', 'cells', self._w))
632 def winfo_children(self):
633 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000634 result = []
635 for child in self.tk.splitlist(
636 self.tk.call('winfo', 'children', self._w)):
637 try:
638 # Tcl sometimes returns extra windows, e.g. for
639 # menus; those need to be skipped
640 result.append(self._nametowidget(child))
641 except KeyError:
642 pass
643 return result
644
Fredrik Lundh06d28152000-08-09 18:03:12 +0000645 def winfo_class(self):
646 """Return window class name of this widget."""
647 return self.tk.call('winfo', 'class', self._w)
648 def winfo_colormapfull(self):
649 """Return true if at the last color request the colormap was full."""
650 return self.tk.getboolean(
651 self.tk.call('winfo', 'colormapfull', self._w))
652 def winfo_containing(self, rootX, rootY, displayof=0):
653 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
654 args = ('winfo', 'containing') \
655 + self._displayof(displayof) + (rootX, rootY)
656 name = self.tk.call(args)
657 if not name: return None
658 return self._nametowidget(name)
659 def winfo_depth(self):
660 """Return the number of bits per pixel."""
661 return getint(self.tk.call('winfo', 'depth', self._w))
662 def winfo_exists(self):
663 """Return true if this widget exists."""
664 return getint(
665 self.tk.call('winfo', 'exists', self._w))
666 def winfo_fpixels(self, number):
667 """Return the number of pixels for the given distance NUMBER
668 (e.g. "3c") as float."""
669 return getdouble(self.tk.call(
670 'winfo', 'fpixels', self._w, number))
671 def winfo_geometry(self):
672 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
673 return self.tk.call('winfo', 'geometry', self._w)
674 def winfo_height(self):
675 """Return height of this widget."""
676 return getint(
677 self.tk.call('winfo', 'height', self._w))
678 def winfo_id(self):
679 """Return identifier ID for this widget."""
680 return self.tk.getint(
681 self.tk.call('winfo', 'id', self._w))
682 def winfo_interps(self, displayof=0):
683 """Return the name of all Tcl interpreters for this display."""
684 args = ('winfo', 'interps') + self._displayof(displayof)
685 return self.tk.splitlist(self.tk.call(args))
686 def winfo_ismapped(self):
687 """Return true if this widget is mapped."""
688 return getint(
689 self.tk.call('winfo', 'ismapped', self._w))
690 def winfo_manager(self):
691 """Return the window mananger name for this widget."""
692 return self.tk.call('winfo', 'manager', self._w)
693 def winfo_name(self):
694 """Return the name of this widget."""
695 return self.tk.call('winfo', 'name', self._w)
696 def winfo_parent(self):
697 """Return the name of the parent of this widget."""
698 return self.tk.call('winfo', 'parent', self._w)
699 def winfo_pathname(self, id, displayof=0):
700 """Return the pathname of the widget given by ID."""
701 args = ('winfo', 'pathname') \
702 + self._displayof(displayof) + (id,)
703 return self.tk.call(args)
704 def winfo_pixels(self, number):
705 """Rounded integer value of winfo_fpixels."""
706 return getint(
707 self.tk.call('winfo', 'pixels', self._w, number))
708 def winfo_pointerx(self):
709 """Return the x coordinate of the pointer on the root window."""
710 return getint(
711 self.tk.call('winfo', 'pointerx', self._w))
712 def winfo_pointerxy(self):
713 """Return a tuple of x and y coordinates of the pointer on the root window."""
714 return self._getints(
715 self.tk.call('winfo', 'pointerxy', self._w))
716 def winfo_pointery(self):
717 """Return the y coordinate of the pointer on the root window."""
718 return getint(
719 self.tk.call('winfo', 'pointery', self._w))
720 def winfo_reqheight(self):
721 """Return requested height of this widget."""
722 return getint(
723 self.tk.call('winfo', 'reqheight', self._w))
724 def winfo_reqwidth(self):
725 """Return requested width of this widget."""
726 return getint(
727 self.tk.call('winfo', 'reqwidth', self._w))
728 def winfo_rgb(self, color):
729 """Return tuple of decimal values for red, green, blue for
730 COLOR in this widget."""
731 return self._getints(
732 self.tk.call('winfo', 'rgb', self._w, color))
733 def winfo_rootx(self):
734 """Return x coordinate of upper left corner of this widget on the
735 root window."""
736 return getint(
737 self.tk.call('winfo', 'rootx', self._w))
738 def winfo_rooty(self):
739 """Return y coordinate of upper left corner of this widget on the
740 root window."""
741 return getint(
742 self.tk.call('winfo', 'rooty', self._w))
743 def winfo_screen(self):
744 """Return the screen name of this widget."""
745 return self.tk.call('winfo', 'screen', self._w)
746 def winfo_screencells(self):
747 """Return the number of the cells in the colormap of the screen
748 of this widget."""
749 return getint(
750 self.tk.call('winfo', 'screencells', self._w))
751 def winfo_screendepth(self):
752 """Return the number of bits per pixel of the root window of the
753 screen of this widget."""
754 return getint(
755 self.tk.call('winfo', 'screendepth', self._w))
756 def winfo_screenheight(self):
757 """Return the number of pixels of the height of the screen of this widget
758 in pixel."""
759 return getint(
760 self.tk.call('winfo', 'screenheight', self._w))
761 def winfo_screenmmheight(self):
762 """Return the number of pixels of the height of the screen of
763 this widget in mm."""
764 return getint(
765 self.tk.call('winfo', 'screenmmheight', self._w))
766 def winfo_screenmmwidth(self):
767 """Return the number of pixels of the width of the screen of
768 this widget in mm."""
769 return getint(
770 self.tk.call('winfo', 'screenmmwidth', self._w))
771 def winfo_screenvisual(self):
772 """Return one of the strings directcolor, grayscale, pseudocolor,
773 staticcolor, staticgray, or truecolor for the default
774 colormodel of this screen."""
775 return self.tk.call('winfo', 'screenvisual', self._w)
776 def winfo_screenwidth(self):
777 """Return the number of pixels of the width of the screen of
778 this widget in pixel."""
779 return getint(
780 self.tk.call('winfo', 'screenwidth', self._w))
781 def winfo_server(self):
782 """Return information of the X-Server of the screen of this widget in
783 the form "XmajorRminor vendor vendorVersion"."""
784 return self.tk.call('winfo', 'server', self._w)
785 def winfo_toplevel(self):
786 """Return the toplevel widget of this widget."""
787 return self._nametowidget(self.tk.call(
788 'winfo', 'toplevel', self._w))
789 def winfo_viewable(self):
790 """Return true if the widget and all its higher ancestors are mapped."""
791 return getint(
792 self.tk.call('winfo', 'viewable', self._w))
793 def winfo_visual(self):
794 """Return one of the strings directcolor, grayscale, pseudocolor,
795 staticcolor, staticgray, or truecolor for the
796 colormodel of this widget."""
797 return self.tk.call('winfo', 'visual', self._w)
798 def winfo_visualid(self):
799 """Return the X identifier for the visual for this widget."""
800 return self.tk.call('winfo', 'visualid', self._w)
801 def winfo_visualsavailable(self, includeids=0):
802 """Return a list of all visuals available for the screen
803 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000804
Fredrik Lundh06d28152000-08-09 18:03:12 +0000805 Each item in the list consists of a visual name (see winfo_visual), a
806 depth and if INCLUDEIDS=1 is given also the X identifier."""
807 data = self.tk.split(
808 self.tk.call('winfo', 'visualsavailable', self._w,
809 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000810 if type(data) is StringType:
811 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000812 return map(self.__winfo_parseitem, data)
813 def __winfo_parseitem(self, t):
814 """Internal function."""
815 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
816 def __winfo_getint(self, x):
817 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000818 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000819 def winfo_vrootheight(self):
820 """Return the height of the virtual root window associated with this
821 widget in pixels. If there is no virtual root window return the
822 height of the screen."""
823 return getint(
824 self.tk.call('winfo', 'vrootheight', self._w))
825 def winfo_vrootwidth(self):
826 """Return the width of the virtual root window associated with this
827 widget in pixel. If there is no virtual root window return the
828 width of the screen."""
829 return getint(
830 self.tk.call('winfo', 'vrootwidth', self._w))
831 def winfo_vrootx(self):
832 """Return the x offset of the virtual root relative to the root
833 window of the screen of this widget."""
834 return getint(
835 self.tk.call('winfo', 'vrootx', self._w))
836 def winfo_vrooty(self):
837 """Return the y offset of the virtual root relative to the root
838 window of the screen of this widget."""
839 return getint(
840 self.tk.call('winfo', 'vrooty', self._w))
841 def winfo_width(self):
842 """Return the width of this widget."""
843 return getint(
844 self.tk.call('winfo', 'width', self._w))
845 def winfo_x(self):
846 """Return the x coordinate of the upper left corner of this widget
847 in the parent."""
848 return getint(
849 self.tk.call('winfo', 'x', self._w))
850 def winfo_y(self):
851 """Return the y coordinate of the upper left corner of this widget
852 in the parent."""
853 return getint(
854 self.tk.call('winfo', 'y', self._w))
855 def update(self):
856 """Enter event loop until all pending events have been processed by Tcl."""
857 self.tk.call('update')
858 def update_idletasks(self):
859 """Enter event loop until all idle callbacks have been called. This
860 will update the display of windows but not process events caused by
861 the user."""
862 self.tk.call('update', 'idletasks')
863 def bindtags(self, tagList=None):
864 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000865
Fredrik Lundh06d28152000-08-09 18:03:12 +0000866 With no argument return the list of all bindtags associated with
867 this widget. With a list of strings as argument the bindtags are
868 set to this list. The bindtags determine in which order events are
869 processed (see bind)."""
870 if tagList is None:
871 return self.tk.splitlist(
872 self.tk.call('bindtags', self._w))
873 else:
874 self.tk.call('bindtags', self._w, tagList)
875 def _bind(self, what, sequence, func, add, needcleanup=1):
876 """Internal function."""
877 if type(func) is StringType:
878 self.tk.call(what + (sequence, func))
879 elif func:
880 funcid = self._register(func, self._substitute,
881 needcleanup)
882 cmd = ('%sif {"[%s %s]" == "break"} break\n'
883 %
884 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000885 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000886 self.tk.call(what + (sequence, cmd))
887 return funcid
888 elif sequence:
889 return self.tk.call(what + (sequence,))
890 else:
891 return self.tk.splitlist(self.tk.call(what))
892 def bind(self, sequence=None, func=None, add=None):
893 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000894
Fredrik Lundh06d28152000-08-09 18:03:12 +0000895 SEQUENCE is a string of concatenated event
896 patterns. An event pattern is of the form
897 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
898 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
899 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
900 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
901 Mod1, M1. TYPE is one of Activate, Enter, Map,
902 ButtonPress, Button, Expose, Motion, ButtonRelease
903 FocusIn, MouseWheel, Circulate, FocusOut, Property,
904 Colormap, Gravity Reparent, Configure, KeyPress, Key,
905 Unmap, Deactivate, KeyRelease Visibility, Destroy,
906 Leave and DETAIL is the button number for ButtonPress,
907 ButtonRelease and DETAIL is the Keysym for KeyPress and
908 KeyRelease. Examples are
909 <Control-Button-1> for pressing Control and mouse button 1 or
910 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
911 An event pattern can also be a virtual event of the form
912 <<AString>> where AString can be arbitrary. This
913 event can be generated by event_generate.
914 If events are concatenated they must appear shortly
915 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000916
Fredrik Lundh06d28152000-08-09 18:03:12 +0000917 FUNC will be called if the event sequence occurs with an
918 instance of Event as argument. If the return value of FUNC is
919 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000920
Fredrik Lundh06d28152000-08-09 18:03:12 +0000921 An additional boolean parameter ADD specifies whether FUNC will
922 be called additionally to the other bound function or whether
923 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000924
Fredrik Lundh06d28152000-08-09 18:03:12 +0000925 Bind will return an identifier to allow deletion of the bound function with
926 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000927
Fredrik Lundh06d28152000-08-09 18:03:12 +0000928 If FUNC or SEQUENCE is omitted the bound function or list
929 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000930
Fredrik Lundh06d28152000-08-09 18:03:12 +0000931 return self._bind(('bind', self._w), sequence, func, add)
932 def unbind(self, sequence, funcid=None):
933 """Unbind for this widget for event SEQUENCE the
934 function identified with FUNCID."""
935 self.tk.call('bind', self._w, sequence, '')
936 if funcid:
937 self.deletecommand(funcid)
938 def bind_all(self, sequence=None, func=None, add=None):
939 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
940 An additional boolean parameter ADD specifies whether FUNC will
941 be called additionally to the other bound function or whether
942 it will replace the previous function. See bind for the return value."""
943 return self._bind(('bind', 'all'), sequence, func, add, 0)
944 def unbind_all(self, sequence):
945 """Unbind for all widgets for event SEQUENCE all functions."""
946 self.tk.call('bind', 'all' , sequence, '')
947 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000948
Fredrik Lundh06d28152000-08-09 18:03:12 +0000949 """Bind to widgets with bindtag CLASSNAME at event
950 SEQUENCE a call of function FUNC. An additional
951 boolean parameter ADD specifies whether FUNC will be
952 called additionally to the other bound function or
953 whether it will replace the previous function. See bind for
954 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000955
Fredrik Lundh06d28152000-08-09 18:03:12 +0000956 return self._bind(('bind', className), sequence, func, add, 0)
957 def unbind_class(self, className, sequence):
958 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
959 all functions."""
960 self.tk.call('bind', className , sequence, '')
961 def mainloop(self, n=0):
962 """Call the mainloop of Tk."""
963 self.tk.mainloop(n)
964 def quit(self):
965 """Quit the Tcl interpreter. All widgets will be destroyed."""
966 self.tk.quit()
967 def _getints(self, string):
968 """Internal function."""
969 if string:
970 return tuple(map(getint, self.tk.splitlist(string)))
971 def _getdoubles(self, string):
972 """Internal function."""
973 if string:
974 return tuple(map(getdouble, self.tk.splitlist(string)))
975 def _getboolean(self, string):
976 """Internal function."""
977 if string:
978 return self.tk.getboolean(string)
979 def _displayof(self, displayof):
980 """Internal function."""
981 if displayof:
982 return ('-displayof', displayof)
983 if displayof is None:
984 return ('-displayof', self._w)
985 return ()
986 def _options(self, cnf, kw = None):
987 """Internal function."""
988 if kw:
989 cnf = _cnfmerge((cnf, kw))
990 else:
991 cnf = _cnfmerge(cnf)
992 res = ()
993 for k, v in cnf.items():
994 if v is not None:
995 if k[-1] == '_': k = k[:-1]
996 if callable(v):
997 v = self._register(v)
998 res = res + ('-'+k, v)
999 return res
1000 def nametowidget(self, name):
1001 """Return the Tkinter instance of a widget identified by
1002 its Tcl name NAME."""
1003 w = self
1004 if name[0] == '.':
1005 w = w._root()
1006 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001007 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +00001008 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001009 if i >= 0:
1010 name, tail = name[:i], name[i+1:]
1011 else:
1012 tail = ''
1013 w = w.children[name]
1014 name = tail
1015 return w
1016 _nametowidget = nametowidget
1017 def _register(self, func, subst=None, needcleanup=1):
1018 """Return a newly created Tcl function. If this
1019 function is called, the Python function FUNC will
1020 be executed. An optional function SUBST can
1021 be given which will be executed before FUNC."""
1022 f = CallWrapper(func, subst, self).__call__
1023 name = `id(f)`
1024 try:
1025 func = func.im_func
1026 except AttributeError:
1027 pass
1028 try:
1029 name = name + func.__name__
1030 except AttributeError:
1031 pass
1032 self.tk.createcommand(name, f)
1033 if needcleanup:
1034 if self._tclCommands is None:
1035 self._tclCommands = []
1036 self._tclCommands.append(name)
1037 #print '+ Tkinter created command', name
1038 return name
1039 register = _register
1040 def _root(self):
1041 """Internal function."""
1042 w = self
1043 while w.master: w = w.master
1044 return w
1045 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1046 '%s', '%t', '%w', '%x', '%y',
1047 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001048 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001049 def _substitute(self, *args):
1050 """Internal function."""
1051 if len(args) != len(self._subst_format): return args
1052 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001053
Fredrik Lundh06d28152000-08-09 18:03:12 +00001054 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001055 def getint_event(s):
1056 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1057 try:
1058 return int(s)
1059 except ValueError:
1060 return s
1061
Fredrik Lundh06d28152000-08-09 18:03:12 +00001062 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1063 # Missing: (a, c, d, m, o, v, B, R)
1064 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001065 # serial field: valid vor all events
1066 # number of button: ButtonPress and ButtonRelease events only
1067 # height field: Configure, ConfigureRequest, Create,
1068 # ResizeRequest, and Expose events only
1069 # keycode field: KeyPress and KeyRelease events only
1070 # time field: "valid for events that contain a time field"
1071 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1072 # and Expose events only
1073 # x field: "valid for events that contain a x field"
1074 # y field: "valid for events that contain a y field"
1075 # keysym as decimal: KeyPress and KeyRelease events only
1076 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1077 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001078 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001079 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001080 try: e.focus = getboolean(f)
1081 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001082 e.height = getint_event(h)
1083 e.keycode = getint_event(k)
1084 e.state = getint_event(s)
1085 e.time = getint_event(t)
1086 e.width = getint_event(w)
1087 e.x = getint_event(x)
1088 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001089 e.char = A
1090 try: e.send_event = getboolean(E)
1091 except TclError: pass
1092 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001093 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001094 e.type = T
1095 try:
1096 e.widget = self._nametowidget(W)
1097 except KeyError:
1098 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001099 e.x_root = getint_event(X)
1100 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001101 try:
1102 e.delta = getint(D)
1103 except ValueError:
1104 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001105 return (e,)
1106 def _report_exception(self):
1107 """Internal function."""
1108 import sys
1109 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1110 root = self._root()
1111 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001112 def _configure(self, cmd, cnf, kw):
1113 """Internal function."""
1114 if kw:
1115 cnf = _cnfmerge((cnf, kw))
1116 elif cnf:
1117 cnf = _cnfmerge(cnf)
1118 if cnf is None:
1119 cnf = {}
1120 for x in self.tk.split(
1121 self.tk.call(_flatten((self._w, cmd)))):
1122 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1123 return cnf
1124 if type(cnf) is StringType:
1125 x = self.tk.split(
1126 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1127 return (x[0][1:],) + x[1:]
1128 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001129 # These used to be defined in Widget:
1130 def configure(self, cnf=None, **kw):
1131 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001132
Fredrik Lundh06d28152000-08-09 18:03:12 +00001133 The values for resources are specified as keyword
1134 arguments. To get an overview about
1135 the allowed keyword arguments call the method keys.
1136 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001137 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001138 config = configure
1139 def cget(self, key):
1140 """Return the resource value for a KEY given as string."""
1141 return self.tk.call(self._w, 'cget', '-' + key)
1142 __getitem__ = cget
1143 def __setitem__(self, key, value):
1144 self.configure({key: value})
1145 def keys(self):
1146 """Return a list of all resource names of this widget."""
1147 return map(lambda x: x[0][1:],
1148 self.tk.split(self.tk.call(self._w, 'configure')))
1149 def __str__(self):
1150 """Return the window path name of this widget."""
1151 return self._w
1152 # Pack methods that apply to the master
1153 _noarg_ = ['_noarg_']
1154 def pack_propagate(self, flag=_noarg_):
1155 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001156
Fredrik Lundh06d28152000-08-09 18:03:12 +00001157 A boolean argument specifies whether the geometry information
1158 of the slaves will determine the size of this widget. If no argument
1159 is given the current setting will be returned.
1160 """
1161 if flag is Misc._noarg_:
1162 return self._getboolean(self.tk.call(
1163 'pack', 'propagate', self._w))
1164 else:
1165 self.tk.call('pack', 'propagate', self._w, flag)
1166 propagate = pack_propagate
1167 def pack_slaves(self):
1168 """Return a list of all slaves of this widget
1169 in its packing order."""
1170 return map(self._nametowidget,
1171 self.tk.splitlist(
1172 self.tk.call('pack', 'slaves', self._w)))
1173 slaves = pack_slaves
1174 # Place method that applies to the master
1175 def place_slaves(self):
1176 """Return a list of all slaves of this widget
1177 in its packing order."""
1178 return map(self._nametowidget,
1179 self.tk.splitlist(
1180 self.tk.call(
1181 'place', 'slaves', self._w)))
1182 # Grid methods that apply to the master
1183 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1184 """Return a tuple of integer coordinates for the bounding
1185 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001186
Fredrik Lundh06d28152000-08-09 18:03:12 +00001187 If COLUMN, ROW is given the bounding box applies from
1188 the cell with row and column 0 to the specified
1189 cell. If COL2 and ROW2 are given the bounding box
1190 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001191
Fredrik Lundh06d28152000-08-09 18:03:12 +00001192 The returned integers specify the offset of the upper left
1193 corner in the master widget and the width and height.
1194 """
1195 args = ('grid', 'bbox', self._w)
1196 if column is not None and row is not None:
1197 args = args + (column, row)
1198 if col2 is not None and row2 is not None:
1199 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001200 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001201
Fredrik Lundh06d28152000-08-09 18:03:12 +00001202 bbox = grid_bbox
1203 def _grid_configure(self, command, index, cnf, kw):
1204 """Internal function."""
1205 if type(cnf) is StringType and not kw:
1206 if cnf[-1:] == '_':
1207 cnf = cnf[:-1]
1208 if cnf[:1] != '-':
1209 cnf = '-'+cnf
1210 options = (cnf,)
1211 else:
1212 options = self._options(cnf, kw)
1213 if not options:
1214 res = self.tk.call('grid',
1215 command, self._w, index)
1216 words = self.tk.splitlist(res)
1217 dict = {}
1218 for i in range(0, len(words), 2):
1219 key = words[i][1:]
1220 value = words[i+1]
1221 if not value:
1222 value = None
1223 elif '.' in value:
1224 value = getdouble(value)
1225 else:
1226 value = getint(value)
1227 dict[key] = value
1228 return dict
1229 res = self.tk.call(
1230 ('grid', command, self._w, index)
1231 + options)
1232 if len(options) == 1:
1233 if not res: return None
1234 # In Tk 7.5, -width can be a float
1235 if '.' in res: return getdouble(res)
1236 return getint(res)
1237 def grid_columnconfigure(self, index, cnf={}, **kw):
1238 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001239
Fredrik Lundh06d28152000-08-09 18:03:12 +00001240 Valid resources are minsize (minimum size of the column),
1241 weight (how much does additional space propagate to this column)
1242 and pad (how much space to let additionally)."""
1243 return self._grid_configure('columnconfigure', index, cnf, kw)
1244 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001245 def grid_location(self, x, y):
1246 """Return a tuple of column and row which identify the cell
1247 at which the pixel at position X and Y inside the master
1248 widget is located."""
1249 return self._getints(
1250 self.tk.call(
1251 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001252 def grid_propagate(self, flag=_noarg_):
1253 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001254
Fredrik Lundh06d28152000-08-09 18:03:12 +00001255 A boolean argument specifies whether the geometry information
1256 of the slaves will determine the size of this widget. If no argument
1257 is given, the current setting will be returned.
1258 """
1259 if flag is Misc._noarg_:
1260 return self._getboolean(self.tk.call(
1261 'grid', 'propagate', self._w))
1262 else:
1263 self.tk.call('grid', 'propagate', self._w, flag)
1264 def grid_rowconfigure(self, index, cnf={}, **kw):
1265 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001266
Fredrik Lundh06d28152000-08-09 18:03:12 +00001267 Valid resources are minsize (minimum size of the row),
1268 weight (how much does additional space propagate to this row)
1269 and pad (how much space to let additionally)."""
1270 return self._grid_configure('rowconfigure', index, cnf, kw)
1271 rowconfigure = grid_rowconfigure
1272 def grid_size(self):
1273 """Return a tuple of the number of column and rows in the grid."""
1274 return self._getints(
1275 self.tk.call('grid', 'size', self._w)) or None
1276 size = grid_size
1277 def grid_slaves(self, row=None, column=None):
1278 """Return a list of all slaves of this widget
1279 in its packing order."""
1280 args = ()
1281 if row is not None:
1282 args = args + ('-row', row)
1283 if column is not None:
1284 args = args + ('-column', column)
1285 return map(self._nametowidget,
1286 self.tk.splitlist(self.tk.call(
1287 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001288
Fredrik Lundh06d28152000-08-09 18:03:12 +00001289 # Support for the "event" command, new in Tk 4.2.
1290 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001291
Fredrik Lundh06d28152000-08-09 18:03:12 +00001292 def event_add(self, virtual, *sequences):
1293 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1294 to an event SEQUENCE such that the virtual event is triggered
1295 whenever SEQUENCE occurs."""
1296 args = ('event', 'add', virtual) + sequences
1297 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001298
Fredrik Lundh06d28152000-08-09 18:03:12 +00001299 def event_delete(self, virtual, *sequences):
1300 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1301 args = ('event', 'delete', virtual) + sequences
1302 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001303
Fredrik Lundh06d28152000-08-09 18:03:12 +00001304 def event_generate(self, sequence, **kw):
1305 """Generate an event SEQUENCE. Additional
1306 keyword arguments specify parameter of the event
1307 (e.g. x, y, rootx, rooty)."""
1308 args = ('event', 'generate', self._w, sequence)
1309 for k, v in kw.items():
1310 args = args + ('-%s' % k, str(v))
1311 self.tk.call(args)
1312
1313 def event_info(self, virtual=None):
1314 """Return a list of all virtual events or the information
1315 about the SEQUENCE bound to the virtual event VIRTUAL."""
1316 return self.tk.splitlist(
1317 self.tk.call('event', 'info', virtual))
1318
1319 # Image related commands
1320
1321 def image_names(self):
1322 """Return a list of all existing image names."""
1323 return self.tk.call('image', 'names')
1324
1325 def image_types(self):
1326 """Return a list of all available image types (e.g. phote bitmap)."""
1327 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001328
Guido van Rossum80f8be81997-12-02 19:51:39 +00001329
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001330class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001331 """Internal class. Stores function to call when some user
1332 defined Tcl function is called e.g. after an event occurred."""
1333 def __init__(self, func, subst, widget):
1334 """Store FUNC, SUBST and WIDGET as members."""
1335 self.func = func
1336 self.subst = subst
1337 self.widget = widget
1338 def __call__(self, *args):
1339 """Apply first function SUBST to arguments, than FUNC."""
1340 try:
1341 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001342 args = self.subst(*args)
1343 return self.func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001344 except SystemExit, msg:
1345 raise SystemExit, msg
1346 except:
1347 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001348
Guido van Rossume365a591998-05-01 19:48:20 +00001349
Guido van Rossum18468821994-06-20 07:49:28 +00001350class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001351 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001352
Fredrik Lundh06d28152000-08-09 18:03:12 +00001353 def wm_aspect(self,
1354 minNumer=None, minDenom=None,
1355 maxNumer=None, maxDenom=None):
1356 """Instruct the window manager to set the aspect ratio (width/height)
1357 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1358 of the actual values if no argument is given."""
1359 return self._getints(
1360 self.tk.call('wm', 'aspect', self._w,
1361 minNumer, minDenom,
1362 maxNumer, maxDenom))
1363 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001364
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001365 def wm_attributes(self, *args):
1366 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001367
1368 The first form returns a list of the platform specific flags and
1369 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001370 option. The third form sets one or more of the values. The values
1371 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001372
1373 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001374 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001375 to toolwindow (as defined in the MSDN). -topmost gets or sets
1376 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001377 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001378
1379 On Macintosh, XXXXX
1380
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001381 On Unix, there are currently no special attribute values.
1382 """
1383 args = ('wm', 'attributes', self._w) + args
1384 return self.tk.call(args)
1385 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001386
Fredrik Lundh06d28152000-08-09 18:03:12 +00001387 def wm_client(self, name=None):
1388 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1389 current value."""
1390 return self.tk.call('wm', 'client', self._w, name)
1391 client = wm_client
1392 def wm_colormapwindows(self, *wlist):
1393 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1394 of this widget. This list contains windows whose colormaps differ from their
1395 parents. Return current list of widgets if WLIST is empty."""
1396 if len(wlist) > 1:
1397 wlist = (wlist,) # Tk needs a list of windows here
1398 args = ('wm', 'colormapwindows', self._w) + wlist
1399 return map(self._nametowidget, self.tk.call(args))
1400 colormapwindows = wm_colormapwindows
1401 def wm_command(self, value=None):
1402 """Store VALUE in WM_COMMAND property. It is the command
1403 which shall be used to invoke the application. Return current
1404 command if VALUE is None."""
1405 return self.tk.call('wm', 'command', self._w, value)
1406 command = wm_command
1407 def wm_deiconify(self):
1408 """Deiconify this widget. If it was never mapped it will not be mapped.
1409 On Windows it will raise this widget and give it the focus."""
1410 return self.tk.call('wm', 'deiconify', self._w)
1411 deiconify = wm_deiconify
1412 def wm_focusmodel(self, model=None):
1413 """Set focus model to MODEL. "active" means that this widget will claim
1414 the focus itself, "passive" means that the window manager shall give
1415 the focus. Return current focus model if MODEL is None."""
1416 return self.tk.call('wm', 'focusmodel', self._w, model)
1417 focusmodel = wm_focusmodel
1418 def wm_frame(self):
1419 """Return identifier for decorative frame of this widget if present."""
1420 return self.tk.call('wm', 'frame', self._w)
1421 frame = wm_frame
1422 def wm_geometry(self, newGeometry=None):
1423 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1424 current value if None is given."""
1425 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1426 geometry = wm_geometry
1427 def wm_grid(self,
1428 baseWidth=None, baseHeight=None,
1429 widthInc=None, heightInc=None):
1430 """Instruct the window manager that this widget shall only be
1431 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1432 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1433 number of grid units requested in Tk_GeometryRequest."""
1434 return self._getints(self.tk.call(
1435 'wm', 'grid', self._w,
1436 baseWidth, baseHeight, widthInc, heightInc))
1437 grid = wm_grid
1438 def wm_group(self, pathName=None):
1439 """Set the group leader widgets for related widgets to PATHNAME. Return
1440 the group leader of this widget if None is given."""
1441 return self.tk.call('wm', 'group', self._w, pathName)
1442 group = wm_group
1443 def wm_iconbitmap(self, bitmap=None):
1444 """Set bitmap for the iconified widget to BITMAP. Return
1445 the bitmap if None is given."""
1446 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1447 iconbitmap = wm_iconbitmap
1448 def wm_iconify(self):
1449 """Display widget as icon."""
1450 return self.tk.call('wm', 'iconify', self._w)
1451 iconify = wm_iconify
1452 def wm_iconmask(self, bitmap=None):
1453 """Set mask for the icon bitmap of this widget. Return the
1454 mask if None is given."""
1455 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1456 iconmask = wm_iconmask
1457 def wm_iconname(self, newName=None):
1458 """Set the name of the icon for this widget. Return the name if
1459 None is given."""
1460 return self.tk.call('wm', 'iconname', self._w, newName)
1461 iconname = wm_iconname
1462 def wm_iconposition(self, x=None, y=None):
1463 """Set the position of the icon of this widget to X and Y. Return
1464 a tuple of the current values of X and X if None is given."""
1465 return self._getints(self.tk.call(
1466 'wm', 'iconposition', self._w, x, y))
1467 iconposition = wm_iconposition
1468 def wm_iconwindow(self, pathName=None):
1469 """Set widget PATHNAME to be displayed instead of icon. Return the current
1470 value if None is given."""
1471 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1472 iconwindow = wm_iconwindow
1473 def wm_maxsize(self, width=None, height=None):
1474 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1475 the values are given in grid units. Return the current values if None
1476 is given."""
1477 return self._getints(self.tk.call(
1478 'wm', 'maxsize', self._w, width, height))
1479 maxsize = wm_maxsize
1480 def wm_minsize(self, width=None, height=None):
1481 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1482 the values are given in grid units. Return the current values if None
1483 is given."""
1484 return self._getints(self.tk.call(
1485 'wm', 'minsize', self._w, width, height))
1486 minsize = wm_minsize
1487 def wm_overrideredirect(self, boolean=None):
1488 """Instruct the window manager to ignore this widget
1489 if BOOLEAN is given with 1. Return the current value if None
1490 is given."""
1491 return self._getboolean(self.tk.call(
1492 'wm', 'overrideredirect', self._w, boolean))
1493 overrideredirect = wm_overrideredirect
1494 def wm_positionfrom(self, who=None):
1495 """Instruct the window manager that the position of this widget shall
1496 be defined by the user if WHO is "user", and by its own policy if WHO is
1497 "program"."""
1498 return self.tk.call('wm', 'positionfrom', self._w, who)
1499 positionfrom = wm_positionfrom
1500 def wm_protocol(self, name=None, func=None):
1501 """Bind function FUNC to command NAME for this widget.
1502 Return the function bound to NAME if None is given. NAME could be
1503 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1504 if callable(func):
1505 command = self._register(func)
1506 else:
1507 command = func
1508 return self.tk.call(
1509 'wm', 'protocol', self._w, name, command)
1510 protocol = wm_protocol
1511 def wm_resizable(self, width=None, height=None):
1512 """Instruct the window manager whether this width can be resized
1513 in WIDTH or HEIGHT. Both values are boolean values."""
1514 return self.tk.call('wm', 'resizable', self._w, width, height)
1515 resizable = wm_resizable
1516 def wm_sizefrom(self, who=None):
1517 """Instruct the window manager that the size of this widget shall
1518 be defined by the user if WHO is "user", and by its own policy if WHO is
1519 "program"."""
1520 return self.tk.call('wm', 'sizefrom', self._w, who)
1521 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001522 def wm_state(self, newstate=None):
1523 """Query or set the state of this widget as one of normal, icon,
1524 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1525 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001526 state = wm_state
1527 def wm_title(self, string=None):
1528 """Set the title of this widget."""
1529 return self.tk.call('wm', 'title', self._w, string)
1530 title = wm_title
1531 def wm_transient(self, master=None):
1532 """Instruct the window manager that this widget is transient
1533 with regard to widget MASTER."""
1534 return self.tk.call('wm', 'transient', self._w, master)
1535 transient = wm_transient
1536 def wm_withdraw(self):
1537 """Withdraw this widget from the screen such that it is unmapped
1538 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1539 return self.tk.call('wm', 'withdraw', self._w)
1540 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001541
Guido van Rossum18468821994-06-20 07:49:28 +00001542
1543class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001544 """Toplevel widget of Tk which represents mostly the main window
1545 of an appliation. It has an associated Tcl interpreter."""
1546 _w = '.'
1547 def __init__(self, screenName=None, baseName=None, className='Tk'):
1548 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1549 be created. BASENAME will be used for the identification of the profile file (see
1550 readprofile).
1551 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1552 is the name of the widget class."""
1553 global _default_root
1554 self.master = None
1555 self.children = {}
1556 if baseName is None:
1557 import sys, os
1558 baseName = os.path.basename(sys.argv[0])
1559 baseName, ext = os.path.splitext(baseName)
1560 if ext not in ('.py', '.pyc', '.pyo'):
1561 baseName = baseName + ext
1562 self.tk = _tkinter.create(screenName, baseName, className)
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001563 self.tk.wantobjects(wantobjects)
Jack Jansenbe92af02001-08-23 13:25:59 +00001564 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001565 # Disable event scanning except for Command-Period
1566 _MacOS.SchedParams(1, 0)
1567 # Work around nasty MacTk bug
1568 # XXX Is this one still needed?
1569 self.update()
1570 # Version sanity checks
1571 tk_version = self.tk.getvar('tk_version')
1572 if tk_version != _tkinter.TK_VERSION:
1573 raise RuntimeError, \
1574 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1575 % (_tkinter.TK_VERSION, tk_version)
Martin v. Löwis54895972003-05-24 11:37:15 +00001576 # Under unknown circumstances, tcl_version gets coerced to float
1577 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001578 if tcl_version != _tkinter.TCL_VERSION:
1579 raise RuntimeError, \
1580 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1581 % (_tkinter.TCL_VERSION, tcl_version)
1582 if TkVersion < 4.0:
1583 raise RuntimeError, \
1584 "Tk 4.0 or higher is required; found Tk %s" \
1585 % str(TkVersion)
1586 self.tk.createcommand('tkerror', _tkerror)
1587 self.tk.createcommand('exit', _exit)
1588 self.readprofile(baseName, className)
1589 if _support_default_root and not _default_root:
1590 _default_root = self
1591 self.protocol("WM_DELETE_WINDOW", self.destroy)
1592 def destroy(self):
1593 """Destroy this and all descendants widgets. This will
1594 end the application of this Tcl interpreter."""
1595 for c in self.children.values(): c.destroy()
1596 self.tk.call('destroy', self._w)
1597 Misc.destroy(self)
1598 global _default_root
1599 if _support_default_root and _default_root is self:
1600 _default_root = None
1601 def readprofile(self, baseName, className):
1602 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1603 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1604 such a file exists in the home directory."""
1605 import os
1606 if os.environ.has_key('HOME'): home = os.environ['HOME']
1607 else: home = os.curdir
1608 class_tcl = os.path.join(home, '.%s.tcl' % className)
1609 class_py = os.path.join(home, '.%s.py' % className)
1610 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1611 base_py = os.path.join(home, '.%s.py' % baseName)
1612 dir = {'self': self}
1613 exec 'from Tkinter import *' in dir
1614 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001615 self.tk.call('source', class_tcl)
1616 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001617 execfile(class_py, dir)
1618 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001619 self.tk.call('source', base_tcl)
1620 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001621 execfile(base_py, dir)
1622 def report_callback_exception(self, exc, val, tb):
1623 """Internal function. It reports exception on sys.stderr."""
1624 import traceback, sys
1625 sys.stderr.write("Exception in Tkinter callback\n")
1626 sys.last_type = exc
1627 sys.last_value = val
1628 sys.last_traceback = tb
1629 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001630
Guido van Rossum368e06b1997-11-07 20:38:49 +00001631# Ideally, the classes Pack, Place and Grid disappear, the
1632# pack/place/grid methods are defined on the Widget class, and
1633# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1634# ...), with pack(), place() and grid() being short for
1635# pack_configure(), place_configure() and grid_columnconfigure(), and
1636# forget() being short for pack_forget(). As a practical matter, I'm
1637# afraid that there is too much code out there that may be using the
1638# Pack, Place or Grid class, so I leave them intact -- but only as
1639# backwards compatibility features. Also note that those methods that
1640# take a master as argument (e.g. pack_propagate) have been moved to
1641# the Misc class (which now incorporates all methods common between
1642# toplevel and interior widgets). Again, for compatibility, these are
1643# copied into the Pack, Place or Grid class.
1644
Guido van Rossum18468821994-06-20 07:49:28 +00001645class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001646 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001647
Fredrik Lundh06d28152000-08-09 18:03:12 +00001648 Base class to use the methods pack_* in every widget."""
1649 def pack_configure(self, cnf={}, **kw):
1650 """Pack a widget in the parent widget. Use as options:
1651 after=widget - pack it after you have packed widget
1652 anchor=NSEW (or subset) - position widget according to
1653 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001654 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001655 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001656 fill=NONE or X or Y or BOTH - fill widget if widget grows
1657 in=master - use master to contain this widget
1658 ipadx=amount - add internal padding in x direction
1659 ipady=amount - add internal padding in y direction
1660 padx=amount - add padding in x direction
1661 pady=amount - add padding in y direction
1662 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1663 """
1664 self.tk.call(
1665 ('pack', 'configure', self._w)
1666 + self._options(cnf, kw))
1667 pack = configure = config = pack_configure
1668 def pack_forget(self):
1669 """Unmap this widget and do not use it for the packing order."""
1670 self.tk.call('pack', 'forget', self._w)
1671 forget = pack_forget
1672 def pack_info(self):
1673 """Return information about the packing options
1674 for this widget."""
1675 words = self.tk.splitlist(
1676 self.tk.call('pack', 'info', self._w))
1677 dict = {}
1678 for i in range(0, len(words), 2):
1679 key = words[i][1:]
1680 value = words[i+1]
1681 if value[:1] == '.':
1682 value = self._nametowidget(value)
1683 dict[key] = value
1684 return dict
1685 info = pack_info
1686 propagate = pack_propagate = Misc.pack_propagate
1687 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001688
1689class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001690 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001691
Fredrik Lundh06d28152000-08-09 18:03:12 +00001692 Base class to use the methods place_* in every widget."""
1693 def place_configure(self, cnf={}, **kw):
1694 """Place a widget in the parent widget. Use as options:
1695 in=master - master relative to which the widget is placed.
1696 x=amount - locate anchor of this widget at position x of master
1697 y=amount - locate anchor of this widget at position y of master
1698 relx=amount - locate anchor of this widget between 0.0 and 1.0
1699 relative to width of master (1.0 is right edge)
1700 rely=amount - locate anchor of this widget between 0.0 and 1.0
1701 relative to height of master (1.0 is bottom edge)
1702 anchor=NSEW (or subset) - position anchor according to given direction
1703 width=amount - width of this widget in pixel
1704 height=amount - height of this widget in pixel
1705 relwidth=amount - width of this widget between 0.0 and 1.0
1706 relative to width of master (1.0 is the same width
1707 as the master)
1708 relheight=amount - height of this widget between 0.0 and 1.0
1709 relative to height of master (1.0 is the same
1710 height as the master)
1711 bordermode="inside" or "outside" - whether to take border width of master widget
1712 into account
1713 """
1714 for k in ['in_']:
1715 if kw.has_key(k):
1716 kw[k[:-1]] = kw[k]
1717 del kw[k]
1718 self.tk.call(
1719 ('place', 'configure', self._w)
1720 + self._options(cnf, kw))
1721 place = configure = config = place_configure
1722 def place_forget(self):
1723 """Unmap this widget."""
1724 self.tk.call('place', 'forget', self._w)
1725 forget = place_forget
1726 def place_info(self):
1727 """Return information about the placing options
1728 for this widget."""
1729 words = self.tk.splitlist(
1730 self.tk.call('place', 'info', self._w))
1731 dict = {}
1732 for i in range(0, len(words), 2):
1733 key = words[i][1:]
1734 value = words[i+1]
1735 if value[:1] == '.':
1736 value = self._nametowidget(value)
1737 dict[key] = value
1738 return dict
1739 info = place_info
1740 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001741
Guido van Rossum37dcab11996-05-16 16:00:19 +00001742class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001743 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001744
Fredrik Lundh06d28152000-08-09 18:03:12 +00001745 Base class to use the methods grid_* in every widget."""
1746 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1747 def grid_configure(self, cnf={}, **kw):
1748 """Position a widget in the parent widget in a grid. Use as options:
1749 column=number - use cell identified with given column (starting with 0)
1750 columnspan=number - this widget will span several columns
1751 in=master - use master to contain this widget
1752 ipadx=amount - add internal padding in x direction
1753 ipady=amount - add internal padding in y direction
1754 padx=amount - add padding in x direction
1755 pady=amount - add padding in y direction
1756 row=number - use cell identified with given row (starting with 0)
1757 rowspan=number - this widget will span several rows
1758 sticky=NSEW - if cell is larger on which sides will this
1759 widget stick to the cell boundary
1760 """
1761 self.tk.call(
1762 ('grid', 'configure', self._w)
1763 + self._options(cnf, kw))
1764 grid = configure = config = grid_configure
1765 bbox = grid_bbox = Misc.grid_bbox
1766 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1767 def grid_forget(self):
1768 """Unmap this widget."""
1769 self.tk.call('grid', 'forget', self._w)
1770 forget = grid_forget
1771 def grid_remove(self):
1772 """Unmap this widget but remember the grid options."""
1773 self.tk.call('grid', 'remove', self._w)
1774 def grid_info(self):
1775 """Return information about the options
1776 for positioning this widget in a grid."""
1777 words = self.tk.splitlist(
1778 self.tk.call('grid', 'info', self._w))
1779 dict = {}
1780 for i in range(0, len(words), 2):
1781 key = words[i][1:]
1782 value = words[i+1]
1783 if value[:1] == '.':
1784 value = self._nametowidget(value)
1785 dict[key] = value
1786 return dict
1787 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001788 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001789 propagate = grid_propagate = Misc.grid_propagate
1790 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1791 size = grid_size = Misc.grid_size
1792 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001793
Guido van Rossum368e06b1997-11-07 20:38:49 +00001794class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001795 """Internal class."""
1796 def _setup(self, master, cnf):
1797 """Internal function. Sets up information about children."""
1798 if _support_default_root:
1799 global _default_root
1800 if not master:
1801 if not _default_root:
1802 _default_root = Tk()
1803 master = _default_root
1804 self.master = master
1805 self.tk = master.tk
1806 name = None
1807 if cnf.has_key('name'):
1808 name = cnf['name']
1809 del cnf['name']
1810 if not name:
1811 name = `id(self)`
1812 self._name = name
1813 if master._w=='.':
1814 self._w = '.' + name
1815 else:
1816 self._w = master._w + '.' + name
1817 self.children = {}
1818 if self.master.children.has_key(self._name):
1819 self.master.children[self._name].destroy()
1820 self.master.children[self._name] = self
1821 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1822 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1823 and appropriate options."""
1824 if kw:
1825 cnf = _cnfmerge((cnf, kw))
1826 self.widgetName = widgetName
1827 BaseWidget._setup(self, master, cnf)
1828 classes = []
1829 for k in cnf.keys():
1830 if type(k) is ClassType:
1831 classes.append((k, cnf[k]))
1832 del cnf[k]
1833 self.tk.call(
1834 (widgetName, self._w) + extra + self._options(cnf))
1835 for k, v in classes:
1836 k.configure(self, v)
1837 def destroy(self):
1838 """Destroy this and all descendants widgets."""
1839 for c in self.children.values(): c.destroy()
1840 if self.master.children.has_key(self._name):
1841 del self.master.children[self._name]
1842 self.tk.call('destroy', self._w)
1843 Misc.destroy(self)
1844 def _do(self, name, args=()):
1845 # XXX Obsolete -- better use self.tk.call directly!
1846 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001847
Guido van Rossum368e06b1997-11-07 20:38:49 +00001848class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001849 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001850
Fredrik Lundh06d28152000-08-09 18:03:12 +00001851 Base class for a widget which can be positioned with the geometry managers
1852 Pack, Place or Grid."""
1853 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001854
1855class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001856 """Toplevel widget, e.g. for dialogs."""
1857 def __init__(self, master=None, cnf={}, **kw):
1858 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001859
Fredrik Lundh06d28152000-08-09 18:03:12 +00001860 Valid resource names: background, bd, bg, borderwidth, class,
1861 colormap, container, cursor, height, highlightbackground,
1862 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1863 use, visual, width."""
1864 if kw:
1865 cnf = _cnfmerge((cnf, kw))
1866 extra = ()
1867 for wmkey in ['screen', 'class_', 'class', 'visual',
1868 'colormap']:
1869 if cnf.has_key(wmkey):
1870 val = cnf[wmkey]
1871 # TBD: a hack needed because some keys
1872 # are not valid as keyword arguments
1873 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1874 else: opt = '-'+wmkey
1875 extra = extra + (opt, val)
1876 del cnf[wmkey]
1877 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1878 root = self._root()
1879 self.iconname(root.iconname())
1880 self.title(root.title())
1881 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001882
1883class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001884 """Button widget."""
1885 def __init__(self, master=None, cnf={}, **kw):
1886 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001887
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001888 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001889
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001890 activebackground, activeforeground, anchor,
1891 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001892 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001893 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001894 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001895 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001896 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001897 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001898
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001899 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001900
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001901 command, compound, default, height,
1902 overrelief, state, width
1903 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001904 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001905
Fredrik Lundh06d28152000-08-09 18:03:12 +00001906 def tkButtonEnter(self, *dummy):
1907 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001908
Fredrik Lundh06d28152000-08-09 18:03:12 +00001909 def tkButtonLeave(self, *dummy):
1910 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001911
Fredrik Lundh06d28152000-08-09 18:03:12 +00001912 def tkButtonDown(self, *dummy):
1913 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001914
Fredrik Lundh06d28152000-08-09 18:03:12 +00001915 def tkButtonUp(self, *dummy):
1916 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001917
Fredrik Lundh06d28152000-08-09 18:03:12 +00001918 def tkButtonInvoke(self, *dummy):
1919 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001920
Fredrik Lundh06d28152000-08-09 18:03:12 +00001921 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001922 """Flash the button.
1923
1924 This is accomplished by redisplaying
1925 the button several times, alternating between active and
1926 normal colors. At the end of the flash the button is left
1927 in the same normal/active state as when the command was
1928 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001929 disabled.
1930 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001931 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00001932
Fredrik Lundh06d28152000-08-09 18:03:12 +00001933 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001934 """Invoke the command associated with the button.
1935
1936 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001937 or an empty string if there is no command associated with
1938 the button. This command is ignored if the button's state
1939 is disabled.
1940 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001941 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001942
1943# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001944# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001945def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001946 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001947def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001948 s = 'insert'
1949 for a in args:
1950 if a: s = s + (' ' + a)
1951 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001952def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001953 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001954def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001955 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001956def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001957 if y is None:
1958 return '@' + `x`
1959 else:
1960 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001961
1962class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001963 """Canvas widget to display graphical elements like lines or text."""
1964 def __init__(self, master=None, cnf={}, **kw):
1965 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001966
Fredrik Lundh06d28152000-08-09 18:03:12 +00001967 Valid resource names: background, bd, bg, borderwidth, closeenough,
1968 confine, cursor, height, highlightbackground, highlightcolor,
1969 highlightthickness, insertbackground, insertborderwidth,
1970 insertofftime, insertontime, insertwidth, offset, relief,
1971 scrollregion, selectbackground, selectborderwidth, selectforeground,
1972 state, takefocus, width, xscrollcommand, xscrollincrement,
1973 yscrollcommand, yscrollincrement."""
1974 Widget.__init__(self, master, 'canvas', cnf, kw)
1975 def addtag(self, *args):
1976 """Internal function."""
1977 self.tk.call((self._w, 'addtag') + args)
1978 def addtag_above(self, newtag, tagOrId):
1979 """Add tag NEWTAG to all items above TAGORID."""
1980 self.addtag(newtag, 'above', tagOrId)
1981 def addtag_all(self, newtag):
1982 """Add tag NEWTAG to all items."""
1983 self.addtag(newtag, 'all')
1984 def addtag_below(self, newtag, tagOrId):
1985 """Add tag NEWTAG to all items below TAGORID."""
1986 self.addtag(newtag, 'below', tagOrId)
1987 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1988 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1989 If several match take the top-most.
1990 All items closer than HALO are considered overlapping (all are
1991 closests). If START is specified the next below this tag is taken."""
1992 self.addtag(newtag, 'closest', x, y, halo, start)
1993 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1994 """Add tag NEWTAG to all items in the rectangle defined
1995 by X1,Y1,X2,Y2."""
1996 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1997 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1998 """Add tag NEWTAG to all items which overlap the rectangle
1999 defined by X1,Y1,X2,Y2."""
2000 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2001 def addtag_withtag(self, newtag, tagOrId):
2002 """Add tag NEWTAG to all items with TAGORID."""
2003 self.addtag(newtag, 'withtag', tagOrId)
2004 def bbox(self, *args):
2005 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2006 which encloses all items with tags specified as arguments."""
2007 return self._getints(
2008 self.tk.call((self._w, 'bbox') + args)) or None
2009 def tag_unbind(self, tagOrId, sequence, funcid=None):
2010 """Unbind for all items with TAGORID for event SEQUENCE the
2011 function identified with FUNCID."""
2012 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2013 if funcid:
2014 self.deletecommand(funcid)
2015 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2016 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002017
Fredrik Lundh06d28152000-08-09 18:03:12 +00002018 An additional boolean parameter ADD specifies whether FUNC will be
2019 called additionally to the other bound function or whether it will
2020 replace the previous function. See bind for the return value."""
2021 return self._bind((self._w, 'bind', tagOrId),
2022 sequence, func, add)
2023 def canvasx(self, screenx, gridspacing=None):
2024 """Return the canvas x coordinate of pixel position SCREENX rounded
2025 to nearest multiple of GRIDSPACING units."""
2026 return getdouble(self.tk.call(
2027 self._w, 'canvasx', screenx, gridspacing))
2028 def canvasy(self, screeny, gridspacing=None):
2029 """Return the canvas y coordinate of pixel position SCREENY rounded
2030 to nearest multiple of GRIDSPACING units."""
2031 return getdouble(self.tk.call(
2032 self._w, 'canvasy', screeny, gridspacing))
2033 def coords(self, *args):
2034 """Return a list of coordinates for the item given in ARGS."""
2035 # XXX Should use _flatten on args
2036 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002037 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002038 self.tk.call((self._w, 'coords') + args)))
2039 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2040 """Internal function."""
2041 args = _flatten(args)
2042 cnf = args[-1]
2043 if type(cnf) in (DictionaryType, TupleType):
2044 args = args[:-1]
2045 else:
2046 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002047 return getint(self.tk.call(
2048 self._w, 'create', itemType,
2049 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002050 def create_arc(self, *args, **kw):
2051 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2052 return self._create('arc', args, kw)
2053 def create_bitmap(self, *args, **kw):
2054 """Create bitmap with coordinates x1,y1."""
2055 return self._create('bitmap', args, kw)
2056 def create_image(self, *args, **kw):
2057 """Create image item with coordinates x1,y1."""
2058 return self._create('image', args, kw)
2059 def create_line(self, *args, **kw):
2060 """Create line with coordinates x1,y1,...,xn,yn."""
2061 return self._create('line', args, kw)
2062 def create_oval(self, *args, **kw):
2063 """Create oval with coordinates x1,y1,x2,y2."""
2064 return self._create('oval', args, kw)
2065 def create_polygon(self, *args, **kw):
2066 """Create polygon with coordinates x1,y1,...,xn,yn."""
2067 return self._create('polygon', args, kw)
2068 def create_rectangle(self, *args, **kw):
2069 """Create rectangle with coordinates x1,y1,x2,y2."""
2070 return self._create('rectangle', args, kw)
2071 def create_text(self, *args, **kw):
2072 """Create text with coordinates x1,y1."""
2073 return self._create('text', args, kw)
2074 def create_window(self, *args, **kw):
2075 """Create window with coordinates x1,y1,x2,y2."""
2076 return self._create('window', args, kw)
2077 def dchars(self, *args):
2078 """Delete characters of text items identified by tag or id in ARGS (possibly
2079 several times) from FIRST to LAST character (including)."""
2080 self.tk.call((self._w, 'dchars') + args)
2081 def delete(self, *args):
2082 """Delete items identified by all tag or ids contained in ARGS."""
2083 self.tk.call((self._w, 'delete') + args)
2084 def dtag(self, *args):
2085 """Delete tag or id given as last arguments in ARGS from items
2086 identified by first argument in ARGS."""
2087 self.tk.call((self._w, 'dtag') + args)
2088 def find(self, *args):
2089 """Internal function."""
2090 return self._getints(
2091 self.tk.call((self._w, 'find') + args)) or ()
2092 def find_above(self, tagOrId):
2093 """Return items above TAGORID."""
2094 return self.find('above', tagOrId)
2095 def find_all(self):
2096 """Return all items."""
2097 return self.find('all')
2098 def find_below(self, tagOrId):
2099 """Return all items below TAGORID."""
2100 return self.find('below', tagOrId)
2101 def find_closest(self, x, y, halo=None, start=None):
2102 """Return item which is closest to pixel at X, Y.
2103 If several match take the top-most.
2104 All items closer than HALO are considered overlapping (all are
2105 closests). If START is specified the next below this tag is taken."""
2106 return self.find('closest', x, y, halo, start)
2107 def find_enclosed(self, x1, y1, x2, y2):
2108 """Return all items in rectangle defined
2109 by X1,Y1,X2,Y2."""
2110 return self.find('enclosed', x1, y1, x2, y2)
2111 def find_overlapping(self, x1, y1, x2, y2):
2112 """Return all items which overlap the rectangle
2113 defined by X1,Y1,X2,Y2."""
2114 return self.find('overlapping', x1, y1, x2, y2)
2115 def find_withtag(self, tagOrId):
2116 """Return all items with TAGORID."""
2117 return self.find('withtag', tagOrId)
2118 def focus(self, *args):
2119 """Set focus to the first item specified in ARGS."""
2120 return self.tk.call((self._w, 'focus') + args)
2121 def gettags(self, *args):
2122 """Return tags associated with the first item specified in ARGS."""
2123 return self.tk.splitlist(
2124 self.tk.call((self._w, 'gettags') + args))
2125 def icursor(self, *args):
2126 """Set cursor at position POS in the item identified by TAGORID.
2127 In ARGS TAGORID must be first."""
2128 self.tk.call((self._w, 'icursor') + args)
2129 def index(self, *args):
2130 """Return position of cursor as integer in item specified in ARGS."""
2131 return getint(self.tk.call((self._w, 'index') + args))
2132 def insert(self, *args):
2133 """Insert TEXT in item TAGORID at position POS. ARGS must
2134 be TAGORID POS TEXT."""
2135 self.tk.call((self._w, 'insert') + args)
2136 def itemcget(self, tagOrId, option):
2137 """Return the resource value for an OPTION for item TAGORID."""
2138 return self.tk.call(
2139 (self._w, 'itemcget') + (tagOrId, '-'+option))
2140 def itemconfigure(self, tagOrId, cnf=None, **kw):
2141 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002142
Fredrik Lundh06d28152000-08-09 18:03:12 +00002143 The values for resources are specified as keyword
2144 arguments. To get an overview about
2145 the allowed keyword arguments call the method without arguments.
2146 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002147 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002148 itemconfig = itemconfigure
2149 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2150 # so the preferred name for them is tag_lower, tag_raise
2151 # (similar to tag_bind, and similar to the Text widget);
2152 # unfortunately can't delete the old ones yet (maybe in 1.6)
2153 def tag_lower(self, *args):
2154 """Lower an item TAGORID given in ARGS
2155 (optional below another item)."""
2156 self.tk.call((self._w, 'lower') + args)
2157 lower = tag_lower
2158 def move(self, *args):
2159 """Move an item TAGORID given in ARGS."""
2160 self.tk.call((self._w, 'move') + args)
2161 def postscript(self, cnf={}, **kw):
2162 """Print the contents of the canvas to a postscript
2163 file. Valid options: colormap, colormode, file, fontmap,
2164 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2165 rotate, witdh, x, y."""
2166 return self.tk.call((self._w, 'postscript') +
2167 self._options(cnf, kw))
2168 def tag_raise(self, *args):
2169 """Raise an item TAGORID given in ARGS
2170 (optional above another item)."""
2171 self.tk.call((self._w, 'raise') + args)
2172 lift = tkraise = tag_raise
2173 def scale(self, *args):
2174 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2175 self.tk.call((self._w, 'scale') + args)
2176 def scan_mark(self, x, y):
2177 """Remember the current X, Y coordinates."""
2178 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002179 def scan_dragto(self, x, y, gain=10):
2180 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002181 difference between X and Y and the coordinates given in
2182 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002183 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002184 def select_adjust(self, tagOrId, index):
2185 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2186 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2187 def select_clear(self):
2188 """Clear the selection if it is in this widget."""
2189 self.tk.call(self._w, 'select', 'clear')
2190 def select_from(self, tagOrId, index):
2191 """Set the fixed end of a selection in item TAGORID to INDEX."""
2192 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2193 def select_item(self):
2194 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002195 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002196 def select_to(self, tagOrId, index):
2197 """Set the variable end of a selection in item TAGORID to INDEX."""
2198 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2199 def type(self, tagOrId):
2200 """Return the type of the item TAGORID."""
2201 return self.tk.call(self._w, 'type', tagOrId) or None
2202 def xview(self, *args):
2203 """Query and change horizontal position of the view."""
2204 if not args:
2205 return self._getdoubles(self.tk.call(self._w, 'xview'))
2206 self.tk.call((self._w, 'xview') + args)
2207 def xview_moveto(self, fraction):
2208 """Adjusts the view in the window so that FRACTION of the
2209 total width of the canvas is off-screen to the left."""
2210 self.tk.call(self._w, 'xview', 'moveto', fraction)
2211 def xview_scroll(self, number, what):
2212 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2213 self.tk.call(self._w, 'xview', 'scroll', number, what)
2214 def yview(self, *args):
2215 """Query and change vertical position of the view."""
2216 if not args:
2217 return self._getdoubles(self.tk.call(self._w, 'yview'))
2218 self.tk.call((self._w, 'yview') + args)
2219 def yview_moveto(self, fraction):
2220 """Adjusts the view in the window so that FRACTION of the
2221 total height of the canvas is off-screen to the top."""
2222 self.tk.call(self._w, 'yview', 'moveto', fraction)
2223 def yview_scroll(self, number, what):
2224 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2225 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002226
2227class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002228 """Checkbutton widget which is either in on- or off-state."""
2229 def __init__(self, master=None, cnf={}, **kw):
2230 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002231
Fredrik Lundh06d28152000-08-09 18:03:12 +00002232 Valid resource names: activebackground, activeforeground, anchor,
2233 background, bd, bg, bitmap, borderwidth, command, cursor,
2234 disabledforeground, fg, font, foreground, height,
2235 highlightbackground, highlightcolor, highlightthickness, image,
2236 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2237 selectcolor, selectimage, state, takefocus, text, textvariable,
2238 underline, variable, width, wraplength."""
2239 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2240 def deselect(self):
2241 """Put the button in off-state."""
2242 self.tk.call(self._w, 'deselect')
2243 def flash(self):
2244 """Flash the button."""
2245 self.tk.call(self._w, 'flash')
2246 def invoke(self):
2247 """Toggle the button and invoke a command if given as resource."""
2248 return self.tk.call(self._w, 'invoke')
2249 def select(self):
2250 """Put the button in on-state."""
2251 self.tk.call(self._w, 'select')
2252 def toggle(self):
2253 """Toggle the button."""
2254 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002255
2256class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002257 """Entry widget which allows to display simple text."""
2258 def __init__(self, master=None, cnf={}, **kw):
2259 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002260
Fredrik Lundh06d28152000-08-09 18:03:12 +00002261 Valid resource names: background, bd, bg, borderwidth, cursor,
2262 exportselection, fg, font, foreground, highlightbackground,
2263 highlightcolor, highlightthickness, insertbackground,
2264 insertborderwidth, insertofftime, insertontime, insertwidth,
2265 invalidcommand, invcmd, justify, relief, selectbackground,
2266 selectborderwidth, selectforeground, show, state, takefocus,
2267 textvariable, validate, validatecommand, vcmd, width,
2268 xscrollcommand."""
2269 Widget.__init__(self, master, 'entry', cnf, kw)
2270 def delete(self, first, last=None):
2271 """Delete text from FIRST to LAST (not included)."""
2272 self.tk.call(self._w, 'delete', first, last)
2273 def get(self):
2274 """Return the text."""
2275 return self.tk.call(self._w, 'get')
2276 def icursor(self, index):
2277 """Insert cursor at INDEX."""
2278 self.tk.call(self._w, 'icursor', index)
2279 def index(self, index):
2280 """Return position of cursor."""
2281 return getint(self.tk.call(
2282 self._w, 'index', index))
2283 def insert(self, index, string):
2284 """Insert STRING at INDEX."""
2285 self.tk.call(self._w, 'insert', index, string)
2286 def scan_mark(self, x):
2287 """Remember the current X, Y coordinates."""
2288 self.tk.call(self._w, 'scan', 'mark', x)
2289 def scan_dragto(self, x):
2290 """Adjust the view of the canvas to 10 times the
2291 difference between X and Y and the coordinates given in
2292 scan_mark."""
2293 self.tk.call(self._w, 'scan', 'dragto', x)
2294 def selection_adjust(self, index):
2295 """Adjust the end of the selection near the cursor to INDEX."""
2296 self.tk.call(self._w, 'selection', 'adjust', index)
2297 select_adjust = selection_adjust
2298 def selection_clear(self):
2299 """Clear the selection if it is in this widget."""
2300 self.tk.call(self._w, 'selection', 'clear')
2301 select_clear = selection_clear
2302 def selection_from(self, index):
2303 """Set the fixed end of a selection to INDEX."""
2304 self.tk.call(self._w, 'selection', 'from', index)
2305 select_from = selection_from
2306 def selection_present(self):
2307 """Return whether the widget has the selection."""
2308 return self.tk.getboolean(
2309 self.tk.call(self._w, 'selection', 'present'))
2310 select_present = selection_present
2311 def selection_range(self, start, end):
2312 """Set the selection from START to END (not included)."""
2313 self.tk.call(self._w, 'selection', 'range', start, end)
2314 select_range = selection_range
2315 def selection_to(self, index):
2316 """Set the variable end of a selection to INDEX."""
2317 self.tk.call(self._w, 'selection', 'to', index)
2318 select_to = selection_to
2319 def xview(self, index):
2320 """Query and change horizontal position of the view."""
2321 self.tk.call(self._w, 'xview', index)
2322 def xview_moveto(self, fraction):
2323 """Adjust the view in the window so that FRACTION of the
2324 total width of the entry is off-screen to the left."""
2325 self.tk.call(self._w, 'xview', 'moveto', fraction)
2326 def xview_scroll(self, number, what):
2327 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2328 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002329
2330class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002331 """Frame widget which may contain other widgets and can have a 3D border."""
2332 def __init__(self, master=None, cnf={}, **kw):
2333 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002334
Fredrik Lundh06d28152000-08-09 18:03:12 +00002335 Valid resource names: background, bd, bg, borderwidth, class,
2336 colormap, container, cursor, height, highlightbackground,
2337 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2338 cnf = _cnfmerge((cnf, kw))
2339 extra = ()
2340 if cnf.has_key('class_'):
2341 extra = ('-class', cnf['class_'])
2342 del cnf['class_']
2343 elif cnf.has_key('class'):
2344 extra = ('-class', cnf['class'])
2345 del cnf['class']
2346 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002347
2348class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002349 """Label widget which can display text and bitmaps."""
2350 def __init__(self, master=None, cnf={}, **kw):
2351 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002352
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002353 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002354
2355 activebackground, activeforeground, anchor,
2356 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002357 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002358 highlightbackground, highlightcolor,
2359 highlightthickness, image, justify,
2360 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002361 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002362
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002363 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002364
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002365 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002366
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002367 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002368 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002369
Guido van Rossum18468821994-06-20 07:49:28 +00002370class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002371 """Listbox widget which can display a list of strings."""
2372 def __init__(self, master=None, cnf={}, **kw):
2373 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002374
Fredrik Lundh06d28152000-08-09 18:03:12 +00002375 Valid resource names: background, bd, bg, borderwidth, cursor,
2376 exportselection, fg, font, foreground, height, highlightbackground,
2377 highlightcolor, highlightthickness, relief, selectbackground,
2378 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2379 width, xscrollcommand, yscrollcommand, listvariable."""
2380 Widget.__init__(self, master, 'listbox', cnf, kw)
2381 def activate(self, index):
2382 """Activate item identified by INDEX."""
2383 self.tk.call(self._w, 'activate', index)
2384 def bbox(self, *args):
2385 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2386 which encloses the item identified by index in ARGS."""
2387 return self._getints(
2388 self.tk.call((self._w, 'bbox') + args)) or None
2389 def curselection(self):
2390 """Return list of indices of currently selected item."""
2391 # XXX Ought to apply self._getints()...
2392 return self.tk.splitlist(self.tk.call(
2393 self._w, 'curselection'))
2394 def delete(self, first, last=None):
2395 """Delete items from FIRST to LAST (not included)."""
2396 self.tk.call(self._w, 'delete', first, last)
2397 def get(self, first, last=None):
2398 """Get list of items from FIRST to LAST (not included)."""
2399 if last:
2400 return self.tk.splitlist(self.tk.call(
2401 self._w, 'get', first, last))
2402 else:
2403 return self.tk.call(self._w, 'get', first)
2404 def index(self, index):
2405 """Return index of item identified with INDEX."""
2406 i = self.tk.call(self._w, 'index', index)
2407 if i == 'none': return None
2408 return getint(i)
2409 def insert(self, index, *elements):
2410 """Insert ELEMENTS at INDEX."""
2411 self.tk.call((self._w, 'insert', index) + elements)
2412 def nearest(self, y):
2413 """Get index of item which is nearest to y coordinate Y."""
2414 return getint(self.tk.call(
2415 self._w, 'nearest', y))
2416 def scan_mark(self, x, y):
2417 """Remember the current X, Y coordinates."""
2418 self.tk.call(self._w, 'scan', 'mark', x, y)
2419 def scan_dragto(self, x, y):
2420 """Adjust the view of the listbox to 10 times the
2421 difference between X and Y and the coordinates given in
2422 scan_mark."""
2423 self.tk.call(self._w, 'scan', 'dragto', x, y)
2424 def see(self, index):
2425 """Scroll such that INDEX is visible."""
2426 self.tk.call(self._w, 'see', index)
2427 def selection_anchor(self, index):
2428 """Set the fixed end oft the selection to INDEX."""
2429 self.tk.call(self._w, 'selection', 'anchor', index)
2430 select_anchor = selection_anchor
2431 def selection_clear(self, first, last=None):
2432 """Clear the selection from FIRST to LAST (not included)."""
2433 self.tk.call(self._w,
2434 'selection', 'clear', first, last)
2435 select_clear = selection_clear
2436 def selection_includes(self, index):
2437 """Return 1 if INDEX is part of the selection."""
2438 return self.tk.getboolean(self.tk.call(
2439 self._w, 'selection', 'includes', index))
2440 select_includes = selection_includes
2441 def selection_set(self, first, last=None):
2442 """Set the selection from FIRST to LAST (not included) without
2443 changing the currently selected elements."""
2444 self.tk.call(self._w, 'selection', 'set', first, last)
2445 select_set = selection_set
2446 def size(self):
2447 """Return the number of elements in the listbox."""
2448 return getint(self.tk.call(self._w, 'size'))
2449 def xview(self, *what):
2450 """Query and change horizontal position of the view."""
2451 if not what:
2452 return self._getdoubles(self.tk.call(self._w, 'xview'))
2453 self.tk.call((self._w, 'xview') + what)
2454 def xview_moveto(self, fraction):
2455 """Adjust the view in the window so that FRACTION of the
2456 total width of the entry is off-screen to the left."""
2457 self.tk.call(self._w, 'xview', 'moveto', fraction)
2458 def xview_scroll(self, number, what):
2459 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2460 self.tk.call(self._w, 'xview', 'scroll', number, what)
2461 def yview(self, *what):
2462 """Query and change vertical position of the view."""
2463 if not what:
2464 return self._getdoubles(self.tk.call(self._w, 'yview'))
2465 self.tk.call((self._w, 'yview') + what)
2466 def yview_moveto(self, fraction):
2467 """Adjust the view in the window so that FRACTION of the
2468 total width of the entry is off-screen to the top."""
2469 self.tk.call(self._w, 'yview', 'moveto', fraction)
2470 def yview_scroll(self, number, what):
2471 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2472 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002473 def itemcget(self, index, option):
2474 """Return the resource value for an ITEM and an OPTION."""
2475 return self.tk.call(
2476 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002477 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002478 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002479
2480 The values for resources are specified as keyword arguments.
2481 To get an overview about the allowed keyword arguments
2482 call the method without arguments.
2483 Valid resource names: background, bg, foreground, fg,
2484 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002485 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002486 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002487
2488class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002489 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2490 def __init__(self, master=None, cnf={}, **kw):
2491 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002492
Fredrik Lundh06d28152000-08-09 18:03:12 +00002493 Valid resource names: activebackground, activeborderwidth,
2494 activeforeground, background, bd, bg, borderwidth, cursor,
2495 disabledforeground, fg, font, foreground, postcommand, relief,
2496 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2497 Widget.__init__(self, master, 'menu', cnf, kw)
2498 def tk_bindForTraversal(self):
2499 pass # obsolete since Tk 4.0
2500 def tk_mbPost(self):
2501 self.tk.call('tk_mbPost', self._w)
2502 def tk_mbUnpost(self):
2503 self.tk.call('tk_mbUnpost')
2504 def tk_traverseToMenu(self, char):
2505 self.tk.call('tk_traverseToMenu', self._w, char)
2506 def tk_traverseWithinMenu(self, char):
2507 self.tk.call('tk_traverseWithinMenu', self._w, char)
2508 def tk_getMenuButtons(self):
2509 return self.tk.call('tk_getMenuButtons', self._w)
2510 def tk_nextMenu(self, count):
2511 self.tk.call('tk_nextMenu', count)
2512 def tk_nextMenuEntry(self, count):
2513 self.tk.call('tk_nextMenuEntry', count)
2514 def tk_invokeMenu(self):
2515 self.tk.call('tk_invokeMenu', self._w)
2516 def tk_firstMenu(self):
2517 self.tk.call('tk_firstMenu', self._w)
2518 def tk_mbButtonDown(self):
2519 self.tk.call('tk_mbButtonDown', self._w)
2520 def tk_popup(self, x, y, entry=""):
2521 """Post the menu at position X,Y with entry ENTRY."""
2522 self.tk.call('tk_popup', self._w, x, y, entry)
2523 def activate(self, index):
2524 """Activate entry at INDEX."""
2525 self.tk.call(self._w, 'activate', index)
2526 def add(self, itemType, cnf={}, **kw):
2527 """Internal function."""
2528 self.tk.call((self._w, 'add', itemType) +
2529 self._options(cnf, kw))
2530 def add_cascade(self, cnf={}, **kw):
2531 """Add hierarchical menu item."""
2532 self.add('cascade', cnf or kw)
2533 def add_checkbutton(self, cnf={}, **kw):
2534 """Add checkbutton menu item."""
2535 self.add('checkbutton', cnf or kw)
2536 def add_command(self, cnf={}, **kw):
2537 """Add command menu item."""
2538 self.add('command', cnf or kw)
2539 def add_radiobutton(self, cnf={}, **kw):
2540 """Addd radio menu item."""
2541 self.add('radiobutton', cnf or kw)
2542 def add_separator(self, cnf={}, **kw):
2543 """Add separator."""
2544 self.add('separator', cnf or kw)
2545 def insert(self, index, itemType, cnf={}, **kw):
2546 """Internal function."""
2547 self.tk.call((self._w, 'insert', index, itemType) +
2548 self._options(cnf, kw))
2549 def insert_cascade(self, index, cnf={}, **kw):
2550 """Add hierarchical menu item at INDEX."""
2551 self.insert(index, 'cascade', cnf or kw)
2552 def insert_checkbutton(self, index, cnf={}, **kw):
2553 """Add checkbutton menu item at INDEX."""
2554 self.insert(index, 'checkbutton', cnf or kw)
2555 def insert_command(self, index, cnf={}, **kw):
2556 """Add command menu item at INDEX."""
2557 self.insert(index, 'command', cnf or kw)
2558 def insert_radiobutton(self, index, cnf={}, **kw):
2559 """Addd radio menu item at INDEX."""
2560 self.insert(index, 'radiobutton', cnf or kw)
2561 def insert_separator(self, index, cnf={}, **kw):
2562 """Add separator at INDEX."""
2563 self.insert(index, 'separator', cnf or kw)
2564 def delete(self, index1, index2=None):
2565 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2566 self.tk.call(self._w, 'delete', index1, index2)
2567 def entrycget(self, index, option):
2568 """Return the resource value of an menu item for OPTION at INDEX."""
2569 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2570 def entryconfigure(self, index, cnf=None, **kw):
2571 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002572 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002573 entryconfig = entryconfigure
2574 def index(self, index):
2575 """Return the index of a menu item identified by INDEX."""
2576 i = self.tk.call(self._w, 'index', index)
2577 if i == 'none': return None
2578 return getint(i)
2579 def invoke(self, index):
2580 """Invoke a menu item identified by INDEX and execute
2581 the associated command."""
2582 return self.tk.call(self._w, 'invoke', index)
2583 def post(self, x, y):
2584 """Display a menu at position X,Y."""
2585 self.tk.call(self._w, 'post', x, y)
2586 def type(self, index):
2587 """Return the type of the menu item at INDEX."""
2588 return self.tk.call(self._w, 'type', index)
2589 def unpost(self):
2590 """Unmap a menu."""
2591 self.tk.call(self._w, 'unpost')
2592 def yposition(self, index):
2593 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2594 return getint(self.tk.call(
2595 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002596
2597class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002598 """Menubutton widget, obsolete since Tk8.0."""
2599 def __init__(self, master=None, cnf={}, **kw):
2600 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002601
2602class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002603 """Message widget to display multiline text. Obsolete since Label does it too."""
2604 def __init__(self, master=None, cnf={}, **kw):
2605 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002606
2607class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002608 """Radiobutton widget which shows only one of several buttons in on-state."""
2609 def __init__(self, master=None, cnf={}, **kw):
2610 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002611
Fredrik Lundh06d28152000-08-09 18:03:12 +00002612 Valid resource names: activebackground, activeforeground, anchor,
2613 background, bd, bg, bitmap, borderwidth, command, cursor,
2614 disabledforeground, fg, font, foreground, height,
2615 highlightbackground, highlightcolor, highlightthickness, image,
2616 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2617 state, takefocus, text, textvariable, underline, value, variable,
2618 width, wraplength."""
2619 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2620 def deselect(self):
2621 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002622
Fredrik Lundh06d28152000-08-09 18:03:12 +00002623 self.tk.call(self._w, 'deselect')
2624 def flash(self):
2625 """Flash the button."""
2626 self.tk.call(self._w, 'flash')
2627 def invoke(self):
2628 """Toggle the button and invoke a command if given as resource."""
2629 return self.tk.call(self._w, 'invoke')
2630 def select(self):
2631 """Put the button in on-state."""
2632 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002633
2634class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002635 """Scale widget which can display a numerical scale."""
2636 def __init__(self, master=None, cnf={}, **kw):
2637 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002638
Fredrik Lundh06d28152000-08-09 18:03:12 +00002639 Valid resource names: activebackground, background, bigincrement, bd,
2640 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2641 highlightbackground, highlightcolor, highlightthickness, label,
2642 length, orient, relief, repeatdelay, repeatinterval, resolution,
2643 showvalue, sliderlength, sliderrelief, state, takefocus,
2644 tickinterval, to, troughcolor, variable, width."""
2645 Widget.__init__(self, master, 'scale', cnf, kw)
2646 def get(self):
2647 """Get the current value as integer or float."""
2648 value = self.tk.call(self._w, 'get')
2649 try:
2650 return getint(value)
2651 except ValueError:
2652 return getdouble(value)
2653 def set(self, value):
2654 """Set the value to VALUE."""
2655 self.tk.call(self._w, 'set', value)
2656 def coords(self, value=None):
2657 """Return a tuple (X,Y) of the point along the centerline of the
2658 trough that corresponds to VALUE or the current value if None is
2659 given."""
2660
2661 return self._getints(self.tk.call(self._w, 'coords', value))
2662 def identify(self, x, y):
2663 """Return where the point X,Y lies. Valid return values are "slider",
2664 "though1" and "though2"."""
2665 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002666
2667class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002668 """Scrollbar widget which displays a slider at a certain position."""
2669 def __init__(self, master=None, cnf={}, **kw):
2670 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002671
Fredrik Lundh06d28152000-08-09 18:03:12 +00002672 Valid resource names: activebackground, activerelief,
2673 background, bd, bg, borderwidth, command, cursor,
2674 elementborderwidth, highlightbackground,
2675 highlightcolor, highlightthickness, jump, orient,
2676 relief, repeatdelay, repeatinterval, takefocus,
2677 troughcolor, width."""
2678 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2679 def activate(self, index):
2680 """Display the element at INDEX with activebackground and activerelief.
2681 INDEX can be "arrow1","slider" or "arrow2"."""
2682 self.tk.call(self._w, 'activate', index)
2683 def delta(self, deltax, deltay):
2684 """Return the fractional change of the scrollbar setting if it
2685 would be moved by DELTAX or DELTAY pixels."""
2686 return getdouble(
2687 self.tk.call(self._w, 'delta', deltax, deltay))
2688 def fraction(self, x, y):
2689 """Return the fractional value which corresponds to a slider
2690 position of X,Y."""
2691 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2692 def identify(self, x, y):
2693 """Return the element under position X,Y as one of
2694 "arrow1","slider","arrow2" or ""."""
2695 return self.tk.call(self._w, 'identify', x, y)
2696 def get(self):
2697 """Return the current fractional values (upper and lower end)
2698 of the slider position."""
2699 return self._getdoubles(self.tk.call(self._w, 'get'))
2700 def set(self, *args):
2701 """Set the fractional values of the slider position (upper and
2702 lower ends as value between 0 and 1)."""
2703 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002704
2705
2706
Guido van Rossum18468821994-06-20 07:49:28 +00002707class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002708 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002709 def __init__(self, master=None, cnf={}, **kw):
2710 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002711
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002712 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002713
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002714 background, borderwidth, cursor,
2715 exportselection, font, foreground,
2716 highlightbackground, highlightcolor,
2717 highlightthickness, insertbackground,
2718 insertborderwidth, insertofftime,
2719 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002720 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002721 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002722 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002723 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002724
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002725 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002726
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002727 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002728 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002729 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002730
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002731 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002732 Widget.__init__(self, master, 'text', cnf, kw)
2733 def bbox(self, *args):
2734 """Return a tuple of (x,y,width,height) which gives the bounding
2735 box of the visible part of the character at the index in ARGS."""
2736 return self._getints(
2737 self.tk.call((self._w, 'bbox') + args)) or None
2738 def tk_textSelectTo(self, index):
2739 self.tk.call('tk_textSelectTo', self._w, index)
2740 def tk_textBackspace(self):
2741 self.tk.call('tk_textBackspace', self._w)
2742 def tk_textIndexCloser(self, a, b, c):
2743 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2744 def tk_textResetAnchor(self, index):
2745 self.tk.call('tk_textResetAnchor', self._w, index)
2746 def compare(self, index1, op, index2):
2747 """Return whether between index INDEX1 and index INDEX2 the
2748 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2749 return self.tk.getboolean(self.tk.call(
2750 self._w, 'compare', index1, op, index2))
2751 def debug(self, boolean=None):
2752 """Turn on the internal consistency checks of the B-Tree inside the text
2753 widget according to BOOLEAN."""
2754 return self.tk.getboolean(self.tk.call(
2755 self._w, 'debug', boolean))
2756 def delete(self, index1, index2=None):
2757 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2758 self.tk.call(self._w, 'delete', index1, index2)
2759 def dlineinfo(self, index):
2760 """Return tuple (x,y,width,height,baseline) giving the bounding box
2761 and baseline position of the visible part of the line containing
2762 the character at INDEX."""
2763 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002764 def dump(self, index1, index2=None, command=None, **kw):
2765 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002766
Guido van Rossum256705b2002-04-23 13:29:43 +00002767 The type of contents returned in filtered based on the keyword
2768 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2769 given and true, then the corresponding items are returned. The result
2770 is a list of triples of the form (key, value, index). If none of the
2771 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002772
Guido van Rossum256705b2002-04-23 13:29:43 +00002773 If the 'command' argument is given, it is called once for each element
2774 of the list of triples, with the values of each triple serving as the
2775 arguments to the function. In this case the list is not returned."""
2776 args = []
2777 func_name = None
2778 result = None
2779 if not command:
2780 # Never call the dump command without the -command flag, since the
2781 # output could involve Tcl quoting and would be a pain to parse
2782 # right. Instead just set the command to build a list of triples
2783 # as if we had done the parsing.
2784 result = []
2785 def append_triple(key, value, index, result=result):
2786 result.append((key, value, index))
2787 command = append_triple
2788 try:
2789 if not isinstance(command, str):
2790 func_name = command = self._register(command)
2791 args += ["-command", command]
2792 for key in kw:
2793 if kw[key]: args.append("-" + key)
2794 args.append(index1)
2795 if index2:
2796 args.append(index2)
2797 self.tk.call(self._w, "dump", *args)
2798 return result
2799 finally:
2800 if func_name:
2801 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002802
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002803 ## new in tk8.4
2804 def edit(self, *args):
2805 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002806
2807 This method controls the undo mechanism and
2808 the modified flag. The exact behavior of the
2809 command depends on the option argument that
2810 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002811 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002812
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002813 edit_modified, edit_redo, edit_reset, edit_separator
2814 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002815
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002816 """
2817 return self._getints(
2818 self.tk.call((self._w, 'edit') + args)) or ()
2819
2820 def edit_modified(self, arg=None):
2821 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002822
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002823 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002824 flag of the widget. The insert, delete, edit undo and
2825 edit redo commands or the user can set or clear the
2826 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002827 modified flag of the widget to arg.
2828 """
2829 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002830
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002831 def edit_redo(self):
2832 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002833
2834 When the undo option is true, reapplies the last
2835 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002836 then. Generates an error when the redo stack is empty.
2837 Does nothing when the undo option is false.
2838 """
2839 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002840
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002841 def edit_reset(self):
2842 """Clears the undo and redo stacks
2843 """
2844 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002845
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002846 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002847 """Inserts a separator (boundary) on the undo stack.
2848
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002849 Does nothing when the undo option is false
2850 """
2851 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002852
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002853 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002854 """Undoes the last edit action
2855
2856 If the undo option is true. An edit action is defined
2857 as all the insert and delete commands that are recorded
2858 on the undo stack in between two separators. Generates
2859 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002860 when the undo option is false
2861 """
2862 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002863
Fredrik Lundh06d28152000-08-09 18:03:12 +00002864 def get(self, index1, index2=None):
2865 """Return the text from INDEX1 to INDEX2 (not included)."""
2866 return self.tk.call(self._w, 'get', index1, index2)
2867 # (Image commands are new in 8.0)
2868 def image_cget(self, index, option):
2869 """Return the value of OPTION of an embedded image at INDEX."""
2870 if option[:1] != "-":
2871 option = "-" + option
2872 if option[-1:] == "_":
2873 option = option[:-1]
2874 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002875 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002876 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002877 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002878 def image_create(self, index, cnf={}, **kw):
2879 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002880 return self.tk.call(
2881 self._w, "image", "create", index,
2882 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002883 def image_names(self):
2884 """Return all names of embedded images in this widget."""
2885 return self.tk.call(self._w, "image", "names")
2886 def index(self, index):
2887 """Return the index in the form line.char for INDEX."""
2888 return self.tk.call(self._w, 'index', index)
2889 def insert(self, index, chars, *args):
2890 """Insert CHARS before the characters at INDEX. An additional
2891 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2892 self.tk.call((self._w, 'insert', index, chars) + args)
2893 def mark_gravity(self, markName, direction=None):
2894 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2895 Return the current value if None is given for DIRECTION."""
2896 return self.tk.call(
2897 (self._w, 'mark', 'gravity', markName, direction))
2898 def mark_names(self):
2899 """Return all mark names."""
2900 return self.tk.splitlist(self.tk.call(
2901 self._w, 'mark', 'names'))
2902 def mark_set(self, markName, index):
2903 """Set mark MARKNAME before the character at INDEX."""
2904 self.tk.call(self._w, 'mark', 'set', markName, index)
2905 def mark_unset(self, *markNames):
2906 """Delete all marks in MARKNAMES."""
2907 self.tk.call((self._w, 'mark', 'unset') + markNames)
2908 def mark_next(self, index):
2909 """Return the name of the next mark after INDEX."""
2910 return self.tk.call(self._w, 'mark', 'next', index) or None
2911 def mark_previous(self, index):
2912 """Return the name of the previous mark before INDEX."""
2913 return self.tk.call(self._w, 'mark', 'previous', index) or None
2914 def scan_mark(self, x, y):
2915 """Remember the current X, Y coordinates."""
2916 self.tk.call(self._w, 'scan', 'mark', x, y)
2917 def scan_dragto(self, x, y):
2918 """Adjust the view of the text to 10 times the
2919 difference between X and Y and the coordinates given in
2920 scan_mark."""
2921 self.tk.call(self._w, 'scan', 'dragto', x, y)
2922 def search(self, pattern, index, stopindex=None,
2923 forwards=None, backwards=None, exact=None,
2924 regexp=None, nocase=None, count=None):
2925 """Search PATTERN beginning from INDEX until STOPINDEX.
2926 Return the index of the first character of a match or an empty string."""
2927 args = [self._w, 'search']
2928 if forwards: args.append('-forwards')
2929 if backwards: args.append('-backwards')
2930 if exact: args.append('-exact')
2931 if regexp: args.append('-regexp')
2932 if nocase: args.append('-nocase')
2933 if count: args.append('-count'); args.append(count)
2934 if pattern[0] == '-': args.append('--')
2935 args.append(pattern)
2936 args.append(index)
2937 if stopindex: args.append(stopindex)
2938 return self.tk.call(tuple(args))
2939 def see(self, index):
2940 """Scroll such that the character at INDEX is visible."""
2941 self.tk.call(self._w, 'see', index)
2942 def tag_add(self, tagName, index1, *args):
2943 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2944 Additional pairs of indices may follow in ARGS."""
2945 self.tk.call(
2946 (self._w, 'tag', 'add', tagName, index1) + args)
2947 def tag_unbind(self, tagName, sequence, funcid=None):
2948 """Unbind for all characters with TAGNAME for event SEQUENCE the
2949 function identified with FUNCID."""
2950 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2951 if funcid:
2952 self.deletecommand(funcid)
2953 def tag_bind(self, tagName, sequence, func, add=None):
2954 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002955
Fredrik Lundh06d28152000-08-09 18:03:12 +00002956 An additional boolean parameter ADD specifies whether FUNC will be
2957 called additionally to the other bound function or whether it will
2958 replace the previous function. See bind for the return value."""
2959 return self._bind((self._w, 'tag', 'bind', tagName),
2960 sequence, func, add)
2961 def tag_cget(self, tagName, option):
2962 """Return the value of OPTION for tag TAGNAME."""
2963 if option[:1] != '-':
2964 option = '-' + option
2965 if option[-1:] == '_':
2966 option = option[:-1]
2967 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002968 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002969 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002970 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002971 tag_config = tag_configure
2972 def tag_delete(self, *tagNames):
2973 """Delete all tags in TAGNAMES."""
2974 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2975 def tag_lower(self, tagName, belowThis=None):
2976 """Change the priority of tag TAGNAME such that it is lower
2977 than the priority of BELOWTHIS."""
2978 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2979 def tag_names(self, index=None):
2980 """Return a list of all tag names."""
2981 return self.tk.splitlist(
2982 self.tk.call(self._w, 'tag', 'names', index))
2983 def tag_nextrange(self, tagName, index1, index2=None):
2984 """Return a list of start and end index for the first sequence of
2985 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2986 The text is searched forward from INDEX1."""
2987 return self.tk.splitlist(self.tk.call(
2988 self._w, 'tag', 'nextrange', tagName, index1, index2))
2989 def tag_prevrange(self, tagName, index1, index2=None):
2990 """Return a list of start and end index for the first sequence of
2991 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2992 The text is searched backwards from INDEX1."""
2993 return self.tk.splitlist(self.tk.call(
2994 self._w, 'tag', 'prevrange', tagName, index1, index2))
2995 def tag_raise(self, tagName, aboveThis=None):
2996 """Change the priority of tag TAGNAME such that it is higher
2997 than the priority of ABOVETHIS."""
2998 self.tk.call(
2999 self._w, 'tag', 'raise', tagName, aboveThis)
3000 def tag_ranges(self, tagName):
3001 """Return a list of ranges of text which have tag TAGNAME."""
3002 return self.tk.splitlist(self.tk.call(
3003 self._w, 'tag', 'ranges', tagName))
3004 def tag_remove(self, tagName, index1, index2=None):
3005 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3006 self.tk.call(
3007 self._w, 'tag', 'remove', tagName, index1, index2)
3008 def window_cget(self, index, option):
3009 """Return the value of OPTION of an embedded window at INDEX."""
3010 if option[:1] != '-':
3011 option = '-' + option
3012 if option[-1:] == '_':
3013 option = option[:-1]
3014 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003015 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003016 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003017 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003018 window_config = window_configure
3019 def window_create(self, index, cnf={}, **kw):
3020 """Create a window at INDEX."""
3021 self.tk.call(
3022 (self._w, 'window', 'create', index)
3023 + self._options(cnf, kw))
3024 def window_names(self):
3025 """Return all names of embedded windows in this widget."""
3026 return self.tk.splitlist(
3027 self.tk.call(self._w, 'window', 'names'))
3028 def xview(self, *what):
3029 """Query and change horizontal position of the view."""
3030 if not what:
3031 return self._getdoubles(self.tk.call(self._w, 'xview'))
3032 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003033 def xview_moveto(self, fraction):
3034 """Adjusts the view in the window so that FRACTION of the
3035 total width of the canvas is off-screen to the left."""
3036 self.tk.call(self._w, 'xview', 'moveto', fraction)
3037 def xview_scroll(self, number, what):
3038 """Shift the x-view according to NUMBER which is measured
3039 in "units" or "pages" (WHAT)."""
3040 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003041 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003042 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003043 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003044 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003045 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003046 def yview_moveto(self, fraction):
3047 """Adjusts the view in the window so that FRACTION of the
3048 total height of the canvas is off-screen to the top."""
3049 self.tk.call(self._w, 'yview', 'moveto', fraction)
3050 def yview_scroll(self, number, what):
3051 """Shift the y-view according to NUMBER which is measured
3052 in "units" or "pages" (WHAT)."""
3053 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003054 def yview_pickplace(self, *what):
3055 """Obsolete function, use see."""
3056 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003057
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003058
Guido van Rossum28574b51996-10-21 15:16:51 +00003059class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003060 """Internal class. It wraps the command in the widget OptionMenu."""
3061 def __init__(self, var, value, callback=None):
3062 self.__value = value
3063 self.__var = var
3064 self.__callback = callback
3065 def __call__(self, *args):
3066 self.__var.set(self.__value)
3067 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003068 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003069
3070class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003071 """OptionMenu which allows the user to select a value from a menu."""
3072 def __init__(self, master, variable, value, *values, **kwargs):
3073 """Construct an optionmenu widget with the parent MASTER, with
3074 the resource textvariable set to VARIABLE, the initially selected
3075 value VALUE, the other menu values VALUES and an additional
3076 keyword argument command."""
3077 kw = {"borderwidth": 2, "textvariable": variable,
3078 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3079 "highlightthickness": 2}
3080 Widget.__init__(self, master, "menubutton", kw)
3081 self.widgetName = 'tk_optionMenu'
3082 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3083 self.menuname = menu._w
3084 # 'command' is the only supported keyword
3085 callback = kwargs.get('command')
3086 if kwargs.has_key('command'):
3087 del kwargs['command']
3088 if kwargs:
3089 raise TclError, 'unknown option -'+kwargs.keys()[0]
3090 menu.add_command(label=value,
3091 command=_setit(variable, value, callback))
3092 for v in values:
3093 menu.add_command(label=v,
3094 command=_setit(variable, v, callback))
3095 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003096
Fredrik Lundh06d28152000-08-09 18:03:12 +00003097 def __getitem__(self, name):
3098 if name == 'menu':
3099 return self.__menu
3100 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003101
Fredrik Lundh06d28152000-08-09 18:03:12 +00003102 def destroy(self):
3103 """Destroy this widget and the associated menu."""
3104 Menubutton.destroy(self)
3105 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003106
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003107class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003108 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003109 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003110 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3111 self.name = None
3112 if not master:
3113 master = _default_root
3114 if not master:
3115 raise RuntimeError, 'Too early to create image'
3116 self.tk = master.tk
3117 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003118 Image._last_id += 1
3119 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003120 # The following is needed for systems where id(x)
3121 # can return a negative number, such as Linux/m68k:
3122 if name[0] == '-': name = '_' + name[1:]
3123 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3124 elif kw: cnf = kw
3125 options = ()
3126 for k, v in cnf.items():
3127 if callable(v):
3128 v = self._register(v)
3129 options = options + ('-'+k, v)
3130 self.tk.call(('image', 'create', imgtype, name,) + options)
3131 self.name = name
3132 def __str__(self): return self.name
3133 def __del__(self):
3134 if self.name:
3135 try:
3136 self.tk.call('image', 'delete', self.name)
3137 except TclError:
3138 # May happen if the root was destroyed
3139 pass
3140 def __setitem__(self, key, value):
3141 self.tk.call(self.name, 'configure', '-'+key, value)
3142 def __getitem__(self, key):
3143 return self.tk.call(self.name, 'configure', '-'+key)
3144 def configure(self, **kw):
3145 """Configure the image."""
3146 res = ()
3147 for k, v in _cnfmerge(kw).items():
3148 if v is not None:
3149 if k[-1] == '_': k = k[:-1]
3150 if callable(v):
3151 v = self._register(v)
3152 res = res + ('-'+k, v)
3153 self.tk.call((self.name, 'config') + res)
3154 config = configure
3155 def height(self):
3156 """Return the height of the image."""
3157 return getint(
3158 self.tk.call('image', 'height', self.name))
3159 def type(self):
3160 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3161 return self.tk.call('image', 'type', self.name)
3162 def width(self):
3163 """Return the width of the image."""
3164 return getint(
3165 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003166
3167class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003168 """Widget which can display colored images in GIF, PPM/PGM format."""
3169 def __init__(self, name=None, cnf={}, master=None, **kw):
3170 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003171
Fredrik Lundh06d28152000-08-09 18:03:12 +00003172 Valid resource names: data, format, file, gamma, height, palette,
3173 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003174 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003175 def blank(self):
3176 """Display a transparent image."""
3177 self.tk.call(self.name, 'blank')
3178 def cget(self, option):
3179 """Return the value of OPTION."""
3180 return self.tk.call(self.name, 'cget', '-' + option)
3181 # XXX config
3182 def __getitem__(self, key):
3183 return self.tk.call(self.name, 'cget', '-' + key)
3184 # XXX copy -from, -to, ...?
3185 def copy(self):
3186 """Return a new PhotoImage with the same image as this widget."""
3187 destImage = PhotoImage()
3188 self.tk.call(destImage, 'copy', self.name)
3189 return destImage
3190 def zoom(self,x,y=''):
3191 """Return a new PhotoImage with the same image as this widget
3192 but zoom it with X and Y."""
3193 destImage = PhotoImage()
3194 if y=='': y=x
3195 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3196 return destImage
3197 def subsample(self,x,y=''):
3198 """Return a new PhotoImage based on the same image as this widget
3199 but use only every Xth or Yth pixel."""
3200 destImage = PhotoImage()
3201 if y=='': y=x
3202 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3203 return destImage
3204 def get(self, x, y):
3205 """Return the color (red, green, blue) of the pixel at X,Y."""
3206 return self.tk.call(self.name, 'get', x, y)
3207 def put(self, data, to=None):
3208 """Put row formated colors to image starting from
3209 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3210 args = (self.name, 'put', data)
3211 if to:
3212 if to[0] == '-to':
3213 to = to[1:]
3214 args = args + ('-to',) + tuple(to)
3215 self.tk.call(args)
3216 # XXX read
3217 def write(self, filename, format=None, from_coords=None):
3218 """Write image to file FILENAME in FORMAT starting from
3219 position FROM_COORDS."""
3220 args = (self.name, 'write', filename)
3221 if format:
3222 args = args + ('-format', format)
3223 if from_coords:
3224 args = args + ('-from',) + tuple(from_coords)
3225 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003226
3227class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003228 """Widget which can display a bitmap."""
3229 def __init__(self, name=None, cnf={}, master=None, **kw):
3230 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003231
Fredrik Lundh06d28152000-08-09 18:03:12 +00003232 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003233 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003234
3235def image_names(): return _default_root.tk.call('image', 'names')
3236def image_types(): return _default_root.tk.call('image', 'types')
3237
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003238
3239class Spinbox(Widget):
3240 """spinbox widget."""
3241 def __init__(self, master=None, cnf={}, **kw):
3242 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003243
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003244 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003245
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003246 activebackground, background, borderwidth,
3247 cursor, exportselection, font, foreground,
3248 highlightbackground, highlightcolor,
3249 highlightthickness, insertbackground,
3250 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003251 insertontime, insertwidth, justify, relief,
3252 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003253 selectbackground, selectborderwidth
3254 selectforeground, takefocus, textvariable
3255 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003256
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003257 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003258
3259 buttonbackground, buttoncursor,
3260 buttondownrelief, buttonuprelief,
3261 command, disabledbackground,
3262 disabledforeground, format, from,
3263 invalidcommand, increment,
3264 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003265 validate, validatecommand values,
3266 width, wrap,
3267 """
3268 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003269
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003270 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003271 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3272 rectangle which encloses the character given by index.
3273
3274 The first two elements of the list give the x and y
3275 coordinates of the upper-left corner of the screen
3276 area covered by the character (in pixels relative
3277 to the widget) and the last two elements give the
3278 width and height of the character, in pixels. The
3279 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003280 visible area of the window.
3281 """
3282 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003283
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003284 def delete(self, first, last=None):
3285 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003286
3287 First is the index of the first character to delete,
3288 and last is the index of the character just after
3289 the last one to delete. If last isn't specified it
3290 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003291 deleted. This command returns an empty string.
3292 """
3293 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003294
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003295 def get(self):
3296 """Returns the spinbox's string"""
3297 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003298
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003299 def icursor(self, index):
3300 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003301
3302 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003303 the character given by index. Returns an empty string
3304 """
3305 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003306
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003307 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003308 """Returns the name of the widget at position x, y
3309
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003310 Return value is one of: none, buttondown, buttonup, entry
3311 """
3312 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003313
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003314 def index(self, index):
3315 """Returns the numerical index corresponding to index
3316 """
3317 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003318
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003319 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003320 """Insert string s at index
3321
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003322 Returns an empty string.
3323 """
3324 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003325
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003326 def invoke(self, element):
3327 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003328
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003329 The element could be buttondown or buttonup
3330 triggering the action associated with it.
3331 """
3332 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003333
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003334 def scan(self, *args):
3335 """Internal function."""
3336 return self._getints(
3337 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003338
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003339 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003340 """Records x and the current view in the spinbox window;
3341
3342 used in conjunction with later scan dragto commands.
3343 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003344 press in the widget. It returns an empty string.
3345 """
3346 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003347
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003348 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003349 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003350 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003351
3352 It then adjusts the view left or right by 10 times the
3353 difference in x-coordinates. This command is typically
3354 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003355 produce the effect of dragging the spinbox at high speed
3356 through the window. The return value is an empty string.
3357 """
3358 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003359
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003360 def selection(self, *args):
3361 """Internal function."""
3362 return self._getints(
3363 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003364
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003365 def selection_adjust(self, index):
3366 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003367 given by index,
3368
3369 Then adjust that end of the selection to be at index
3370 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003371 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003372 select to commands. If the selection isn't currently in
3373 the spinbox, then a new selection is created to include
3374 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003375 anchor point, inclusive. Returns an empty string.
3376 """
3377 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003378
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003379 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003380 """Clear the selection
3381
3382 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003383 command has no effect. Returns an empty string.
3384 """
3385 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003386
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003387 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003388 """Sets or gets the currently selected element.
3389
3390 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003391 displayed depressed
3392 """
3393 return self.selection("element", element)
3394
3395###########################################################################
3396
3397class LabelFrame(Widget):
3398 """labelframe widget."""
3399 def __init__(self, master=None, cnf={}, **kw):
3400 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003401
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003402 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003403
3404 borderwidth, cursor, font, foreground,
3405 highlightbackground, highlightcolor,
3406 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003407 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003408
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003409 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003410
3411 background, class, colormap, container,
3412 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003413 visual, width
3414 """
3415 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003416
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003417########################################################################
3418
3419class PanedWindow(Widget):
3420 """panedwindow widget."""
3421 def __init__(self, master=None, cnf={}, **kw):
3422 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003423
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003424 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003425
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003426 background, borderwidth, cursor, height,
3427 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003428
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003429 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003430
3431 handlepad, handlesize, opaqueresize,
3432 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003433 sashwidth, showhandle,
3434 """
3435 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3436
3437 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003438 """Add a child widget to the panedwindow in a new pane.
3439
3440 The child argument is the name of the child widget
3441 followed by pairs of arguments that specify how to
3442 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003443 accepted by the configure subcommand.
3444 """
3445 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003446
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003447 def remove(self, child):
3448 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003449
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003450 All geometry management options for child will be forgotten.
3451 """
3452 self.tk.call(self._w, 'forget', child)
3453 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003454
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003455 def identify(self, x, y):
3456 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003457
3458 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003459 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003460 handle, and a word indicating whether it is over a sash
3461 or a handle, such as {0 sash} or {2 handle}. If the point
3462 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003463 an empty list.
3464 """
3465 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003466
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003467 def proxy(self, *args):
3468 """Internal function."""
3469 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003470 self.tk.call((self._w, 'proxy') + args)) or ()
3471
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003472 def proxy_coord(self):
3473 """Return the x and y pair of the most recent proxy location
3474 """
3475 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003476
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003477 def proxy_forget(self):
3478 """Remove the proxy from the display.
3479 """
3480 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003481
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003482 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003483 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003484 """
3485 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003486
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003487 def sash(self, *args):
3488 """Internal function."""
3489 return self._getints(
3490 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003491
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003492 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003493 """Return the current x and y pair for the sash given by index.
3494
3495 Index must be an integer between 0 and 1 less than the
3496 number of panes in the panedwindow. The coordinates given are
3497 those of the top left corner of the region containing the sash.
3498 pathName sash dragto index x y This command computes the
3499 difference between the given coordinates and the coordinates
3500 given to the last sash coord command for the given sash. It then
3501 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003502 empty string.
3503 """
3504 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003505
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003506 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003507 """Records x and y for the sash given by index;
3508
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003509 Used in conjunction with later dragto commands to move the sash.
3510 """
3511 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003512
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003513 def sash_place(self, index, x, y):
3514 """Place the sash given by index at the given coordinates
3515 """
3516 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003517
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003518 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003519 """Query a management option for window.
3520
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003521 Option may be any value allowed by the paneconfigure subcommand
3522 """
3523 return self.tk.call(
3524 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003525
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003526 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003527 """Query or modify the management options for window.
3528
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003529 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003530 of the available options for pathName. If option is
3531 specified with no value, then the command returns a list
3532 describing the one named option (this list will be identical
3533 to the corresponding sublist of the value returned if no
3534 option is specified). If one or more option-value pairs are
3535 specified, then the command modifies the given widget
3536 option(s) to have the given value(s); in this case the
3537 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003538 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003539
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003540 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003541 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003542 should be the name of a window already managed by pathName.
3543 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003544 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003545 should be the name of a window already managed by pathName.
3546 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003547 Specify a height for the window. The height will be the
3548 outer dimension of the window including its border, if
3549 any. If size is an empty string, or if -height is not
3550 specified, then the height requested internally by the
3551 window will be used initially; the height may later be
3552 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003553 Size may be any value accepted by Tk_GetPixels.
3554 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003555 Specifies that the size of the window cannot be made
3556 less than n. This constraint only affects the size of
3557 the widget in the paned dimension -- the x dimension
3558 for horizontal panedwindows, the y dimension for
3559 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003560 Tk_GetPixels.
3561 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003562 Specifies a non-negative value indicating how much
3563 extra space to leave on each side of the window in
3564 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003565 accepted by Tk_GetPixels.
3566 pady n
3567 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003568 extra space to leave on each side of the window in
3569 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003570 accepted by Tk_GetPixels.
3571 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003572 If a window's pane is larger than the requested
3573 dimensions of the window, this option may be used
3574 to position (or stretch) the window within its pane.
3575 Style is a string that contains zero or more of the
3576 characters n, s, e or w. The string can optionally
3577 contains spaces or commas, but they are ignored. Each
3578 letter refers to a side (north, south, east, or west)
3579 that the window will "stick" to. If both n and s
3580 (or e and w) are specified, the window will be
3581 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003582 its cavity.
3583 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003584 Specify a width for the window. The width will be
3585 the outer dimension of the window including its
3586 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003587 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003588 internally by the window will be used initially; the
3589 width may later be adjusted by the movement of sashes
3590 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003591 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003592
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003593 """
3594 if cnf is None and not kw:
3595 cnf = {}
3596 for x in self.tk.split(
3597 self.tk.call(self._w,
3598 'paneconfigure', tagOrId)):
3599 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3600 return cnf
3601 if type(cnf) == StringType and not kw:
3602 x = self.tk.split(self.tk.call(
3603 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3604 return (x[0][1:],) + x[1:]
3605 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3606 self._options(cnf, kw))
3607 paneconfig = paneconfigure
3608
3609 def panes(self):
3610 """Returns an ordered list of the child panes."""
3611 return self.tk.call(self._w, 'panes')
3612
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003613######################################################################
3614# Extensions:
3615
3616class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003617 def __init__(self, master=None, cnf={}, **kw):
3618 Widget.__init__(self, master, 'studbutton', cnf, kw)
3619 self.bind('<Any-Enter>', self.tkButtonEnter)
3620 self.bind('<Any-Leave>', self.tkButtonLeave)
3621 self.bind('<1>', self.tkButtonDown)
3622 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003623
3624class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003625 def __init__(self, master=None, cnf={}, **kw):
3626 Widget.__init__(self, master, 'tributton', cnf, kw)
3627 self.bind('<Any-Enter>', self.tkButtonEnter)
3628 self.bind('<Any-Leave>', self.tkButtonLeave)
3629 self.bind('<1>', self.tkButtonDown)
3630 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3631 self['fg'] = self['bg']
3632 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003633
Guido van Rossumc417ef81996-08-21 23:38:59 +00003634######################################################################
3635# Test:
3636
3637def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003638 root = Tk()
3639 text = "This is Tcl/Tk version %s" % TclVersion
3640 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003641 try:
3642 text = text + unicode("\nThis should be a cedilla: \347",
3643 "iso-8859-1")
3644 except NameError:
3645 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003646 label = Label(root, text=text)
3647 label.pack()
3648 test = Button(root, text="Click me!",
3649 command=lambda root=root: root.test.configure(
3650 text="[%s]" % root.test['text']))
3651 test.pack()
3652 root.test = test
3653 quit = Button(root, text="QUIT", command=root.destroy)
3654 quit.pack()
3655 # The following three commands are needed so the window pops
3656 # up on top on Windows...
3657 root.iconify()
3658 root.update()
3659 root.deiconify()
3660 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003661
3662if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003663 _test()