blob: 2025ba84b8d3dd9785a89a38aaec8adc1b03b7f2 [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."""
477 self.tk.call('after', 'cancel', id)
478 def bell(self, displayof=0):
479 """Ring a display's bell."""
480 self.tk.call(('bell',) + self._displayof(displayof))
481 # Clipboard handling:
482 def clipboard_clear(self, **kw):
483 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000484
Fredrik Lundh06d28152000-08-09 18:03:12 +0000485 A widget specified for the optional displayof keyword
486 argument specifies the target display."""
487 if not kw.has_key('displayof'): kw['displayof'] = self._w
488 self.tk.call(('clipboard', 'clear') + self._options(kw))
489 def clipboard_append(self, string, **kw):
490 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000491
Fredrik Lundh06d28152000-08-09 18:03:12 +0000492 A widget specified at the optional displayof keyword
493 argument specifies the target display. The clipboard
494 can be retrieved with selection_get."""
495 if not kw.has_key('displayof'): kw['displayof'] = self._w
496 self.tk.call(('clipboard', 'append') + self._options(kw)
497 + ('--', string))
498 # XXX grab current w/o window argument
499 def grab_current(self):
500 """Return widget which has currently the grab in this application
501 or None."""
502 name = self.tk.call('grab', 'current', self._w)
503 if not name: return None
504 return self._nametowidget(name)
505 def grab_release(self):
506 """Release grab for this widget if currently set."""
507 self.tk.call('grab', 'release', self._w)
508 def grab_set(self):
509 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000510
Fredrik Lundh06d28152000-08-09 18:03:12 +0000511 A grab directs all events to this and descendant
512 widgets in the application."""
513 self.tk.call('grab', 'set', self._w)
514 def grab_set_global(self):
515 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000516
Fredrik Lundh06d28152000-08-09 18:03:12 +0000517 A global grab directs all events to this and
518 descendant widgets on the display. Use with caution -
519 other applications do not get events anymore."""
520 self.tk.call('grab', 'set', '-global', self._w)
521 def grab_status(self):
522 """Return None, "local" or "global" if this widget has
523 no, a local or a global grab."""
524 status = self.tk.call('grab', 'status', self._w)
525 if status == 'none': status = None
526 return status
527 def lower(self, belowThis=None):
528 """Lower this widget in the stacking order."""
529 self.tk.call('lower', self._w, belowThis)
530 def option_add(self, pattern, value, priority = None):
531 """Set a VALUE (second parameter) for an option
532 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000533
Fredrik Lundh06d28152000-08-09 18:03:12 +0000534 An optional third parameter gives the numeric priority
535 (defaults to 80)."""
536 self.tk.call('option', 'add', pattern, value, priority)
537 def option_clear(self):
538 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000539
Fredrik Lundh06d28152000-08-09 18:03:12 +0000540 It will be reloaded if option_add is called."""
541 self.tk.call('option', 'clear')
542 def option_get(self, name, className):
543 """Return the value for an option NAME for this widget
544 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000545
Fredrik Lundh06d28152000-08-09 18:03:12 +0000546 Values with higher priority override lower values."""
547 return self.tk.call('option', 'get', self._w, name, className)
548 def option_readfile(self, fileName, priority = None):
549 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000550
Fredrik Lundh06d28152000-08-09 18:03:12 +0000551 An optional second parameter gives the numeric
552 priority."""
553 self.tk.call('option', 'readfile', fileName, priority)
554 def selection_clear(self, **kw):
555 """Clear the current X selection."""
556 if not kw.has_key('displayof'): kw['displayof'] = self._w
557 self.tk.call(('selection', 'clear') + self._options(kw))
558 def selection_get(self, **kw):
559 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000560
Fredrik Lundh06d28152000-08-09 18:03:12 +0000561 A keyword parameter selection specifies the name of
562 the selection and defaults to PRIMARY. A keyword
563 parameter displayof specifies a widget on the display
564 to use."""
565 if not kw.has_key('displayof'): kw['displayof'] = self._w
566 return self.tk.call(('selection', 'get') + self._options(kw))
567 def selection_handle(self, command, **kw):
568 """Specify a function COMMAND to call if the X
569 selection owned by this widget is queried by another
570 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000571
Fredrik Lundh06d28152000-08-09 18:03:12 +0000572 This function must return the contents of the
573 selection. The function will be called with the
574 arguments OFFSET and LENGTH which allows the chunking
575 of very long selections. The following keyword
576 parameters can be provided:
577 selection - name of the selection (default PRIMARY),
578 type - type of the selection (e.g. STRING, FILE_NAME)."""
579 name = self._register(command)
580 self.tk.call(('selection', 'handle') + self._options(kw)
581 + (self._w, name))
582 def selection_own(self, **kw):
583 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000584
Fredrik Lundh06d28152000-08-09 18:03:12 +0000585 A keyword parameter selection specifies the name of
586 the selection (default PRIMARY)."""
587 self.tk.call(('selection', 'own') +
588 self._options(kw) + (self._w,))
589 def selection_own_get(self, **kw):
590 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000591
Fredrik Lundh06d28152000-08-09 18:03:12 +0000592 The following keyword parameter can
593 be provided:
594 selection - name of the selection (default PRIMARY),
595 type - type of the selection (e.g. STRING, FILE_NAME)."""
596 if not kw.has_key('displayof'): kw['displayof'] = self._w
597 name = self.tk.call(('selection', 'own') + self._options(kw))
598 if not name: return None
599 return self._nametowidget(name)
600 def send(self, interp, cmd, *args):
601 """Send Tcl command CMD to different interpreter INTERP to be executed."""
602 return self.tk.call(('send', interp, cmd) + args)
603 def lower(self, belowThis=None):
604 """Lower this widget in the stacking order."""
605 self.tk.call('lower', self._w, belowThis)
606 def tkraise(self, aboveThis=None):
607 """Raise this widget in the stacking order."""
608 self.tk.call('raise', self._w, aboveThis)
609 lift = tkraise
610 def colormodel(self, value=None):
611 """Useless. Not implemented in Tk."""
612 return self.tk.call('tk', 'colormodel', self._w, value)
613 def winfo_atom(self, name, displayof=0):
614 """Return integer which represents atom NAME."""
615 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
616 return getint(self.tk.call(args))
617 def winfo_atomname(self, id, displayof=0):
618 """Return name of atom with identifier ID."""
619 args = ('winfo', 'atomname') \
620 + self._displayof(displayof) + (id,)
621 return self.tk.call(args)
622 def winfo_cells(self):
623 """Return number of cells in the colormap for this widget."""
624 return getint(
625 self.tk.call('winfo', 'cells', self._w))
626 def winfo_children(self):
627 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000628 result = []
629 for child in self.tk.splitlist(
630 self.tk.call('winfo', 'children', self._w)):
631 try:
632 # Tcl sometimes returns extra windows, e.g. for
633 # menus; those need to be skipped
634 result.append(self._nametowidget(child))
635 except KeyError:
636 pass
637 return result
638
Fredrik Lundh06d28152000-08-09 18:03:12 +0000639 def winfo_class(self):
640 """Return window class name of this widget."""
641 return self.tk.call('winfo', 'class', self._w)
642 def winfo_colormapfull(self):
643 """Return true if at the last color request the colormap was full."""
644 return self.tk.getboolean(
645 self.tk.call('winfo', 'colormapfull', self._w))
646 def winfo_containing(self, rootX, rootY, displayof=0):
647 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
648 args = ('winfo', 'containing') \
649 + self._displayof(displayof) + (rootX, rootY)
650 name = self.tk.call(args)
651 if not name: return None
652 return self._nametowidget(name)
653 def winfo_depth(self):
654 """Return the number of bits per pixel."""
655 return getint(self.tk.call('winfo', 'depth', self._w))
656 def winfo_exists(self):
657 """Return true if this widget exists."""
658 return getint(
659 self.tk.call('winfo', 'exists', self._w))
660 def winfo_fpixels(self, number):
661 """Return the number of pixels for the given distance NUMBER
662 (e.g. "3c") as float."""
663 return getdouble(self.tk.call(
664 'winfo', 'fpixels', self._w, number))
665 def winfo_geometry(self):
666 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
667 return self.tk.call('winfo', 'geometry', self._w)
668 def winfo_height(self):
669 """Return height of this widget."""
670 return getint(
671 self.tk.call('winfo', 'height', self._w))
672 def winfo_id(self):
673 """Return identifier ID for this widget."""
674 return self.tk.getint(
675 self.tk.call('winfo', 'id', self._w))
676 def winfo_interps(self, displayof=0):
677 """Return the name of all Tcl interpreters for this display."""
678 args = ('winfo', 'interps') + self._displayof(displayof)
679 return self.tk.splitlist(self.tk.call(args))
680 def winfo_ismapped(self):
681 """Return true if this widget is mapped."""
682 return getint(
683 self.tk.call('winfo', 'ismapped', self._w))
684 def winfo_manager(self):
685 """Return the window mananger name for this widget."""
686 return self.tk.call('winfo', 'manager', self._w)
687 def winfo_name(self):
688 """Return the name of this widget."""
689 return self.tk.call('winfo', 'name', self._w)
690 def winfo_parent(self):
691 """Return the name of the parent of this widget."""
692 return self.tk.call('winfo', 'parent', self._w)
693 def winfo_pathname(self, id, displayof=0):
694 """Return the pathname of the widget given by ID."""
695 args = ('winfo', 'pathname') \
696 + self._displayof(displayof) + (id,)
697 return self.tk.call(args)
698 def winfo_pixels(self, number):
699 """Rounded integer value of winfo_fpixels."""
700 return getint(
701 self.tk.call('winfo', 'pixels', self._w, number))
702 def winfo_pointerx(self):
703 """Return the x coordinate of the pointer on the root window."""
704 return getint(
705 self.tk.call('winfo', 'pointerx', self._w))
706 def winfo_pointerxy(self):
707 """Return a tuple of x and y coordinates of the pointer on the root window."""
708 return self._getints(
709 self.tk.call('winfo', 'pointerxy', self._w))
710 def winfo_pointery(self):
711 """Return the y coordinate of the pointer on the root window."""
712 return getint(
713 self.tk.call('winfo', 'pointery', self._w))
714 def winfo_reqheight(self):
715 """Return requested height of this widget."""
716 return getint(
717 self.tk.call('winfo', 'reqheight', self._w))
718 def winfo_reqwidth(self):
719 """Return requested width of this widget."""
720 return getint(
721 self.tk.call('winfo', 'reqwidth', self._w))
722 def winfo_rgb(self, color):
723 """Return tuple of decimal values for red, green, blue for
724 COLOR in this widget."""
725 return self._getints(
726 self.tk.call('winfo', 'rgb', self._w, color))
727 def winfo_rootx(self):
728 """Return x coordinate of upper left corner of this widget on the
729 root window."""
730 return getint(
731 self.tk.call('winfo', 'rootx', self._w))
732 def winfo_rooty(self):
733 """Return y coordinate of upper left corner of this widget on the
734 root window."""
735 return getint(
736 self.tk.call('winfo', 'rooty', self._w))
737 def winfo_screen(self):
738 """Return the screen name of this widget."""
739 return self.tk.call('winfo', 'screen', self._w)
740 def winfo_screencells(self):
741 """Return the number of the cells in the colormap of the screen
742 of this widget."""
743 return getint(
744 self.tk.call('winfo', 'screencells', self._w))
745 def winfo_screendepth(self):
746 """Return the number of bits per pixel of the root window of the
747 screen of this widget."""
748 return getint(
749 self.tk.call('winfo', 'screendepth', self._w))
750 def winfo_screenheight(self):
751 """Return the number of pixels of the height of the screen of this widget
752 in pixel."""
753 return getint(
754 self.tk.call('winfo', 'screenheight', self._w))
755 def winfo_screenmmheight(self):
756 """Return the number of pixels of the height of the screen of
757 this widget in mm."""
758 return getint(
759 self.tk.call('winfo', 'screenmmheight', self._w))
760 def winfo_screenmmwidth(self):
761 """Return the number of pixels of the width of the screen of
762 this widget in mm."""
763 return getint(
764 self.tk.call('winfo', 'screenmmwidth', self._w))
765 def winfo_screenvisual(self):
766 """Return one of the strings directcolor, grayscale, pseudocolor,
767 staticcolor, staticgray, or truecolor for the default
768 colormodel of this screen."""
769 return self.tk.call('winfo', 'screenvisual', self._w)
770 def winfo_screenwidth(self):
771 """Return the number of pixels of the width of the screen of
772 this widget in pixel."""
773 return getint(
774 self.tk.call('winfo', 'screenwidth', self._w))
775 def winfo_server(self):
776 """Return information of the X-Server of the screen of this widget in
777 the form "XmajorRminor vendor vendorVersion"."""
778 return self.tk.call('winfo', 'server', self._w)
779 def winfo_toplevel(self):
780 """Return the toplevel widget of this widget."""
781 return self._nametowidget(self.tk.call(
782 'winfo', 'toplevel', self._w))
783 def winfo_viewable(self):
784 """Return true if the widget and all its higher ancestors are mapped."""
785 return getint(
786 self.tk.call('winfo', 'viewable', self._w))
787 def winfo_visual(self):
788 """Return one of the strings directcolor, grayscale, pseudocolor,
789 staticcolor, staticgray, or truecolor for the
790 colormodel of this widget."""
791 return self.tk.call('winfo', 'visual', self._w)
792 def winfo_visualid(self):
793 """Return the X identifier for the visual for this widget."""
794 return self.tk.call('winfo', 'visualid', self._w)
795 def winfo_visualsavailable(self, includeids=0):
796 """Return a list of all visuals available for the screen
797 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000798
Fredrik Lundh06d28152000-08-09 18:03:12 +0000799 Each item in the list consists of a visual name (see winfo_visual), a
800 depth and if INCLUDEIDS=1 is given also the X identifier."""
801 data = self.tk.split(
802 self.tk.call('winfo', 'visualsavailable', self._w,
803 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000804 if type(data) is StringType:
805 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000806 return map(self.__winfo_parseitem, data)
807 def __winfo_parseitem(self, t):
808 """Internal function."""
809 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
810 def __winfo_getint(self, x):
811 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000812 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000813 def winfo_vrootheight(self):
814 """Return the height of the virtual root window associated with this
815 widget in pixels. If there is no virtual root window return the
816 height of the screen."""
817 return getint(
818 self.tk.call('winfo', 'vrootheight', self._w))
819 def winfo_vrootwidth(self):
820 """Return the width of the virtual root window associated with this
821 widget in pixel. If there is no virtual root window return the
822 width of the screen."""
823 return getint(
824 self.tk.call('winfo', 'vrootwidth', self._w))
825 def winfo_vrootx(self):
826 """Return the x offset of the virtual root relative to the root
827 window of the screen of this widget."""
828 return getint(
829 self.tk.call('winfo', 'vrootx', self._w))
830 def winfo_vrooty(self):
831 """Return the y offset of the virtual root relative to the root
832 window of the screen of this widget."""
833 return getint(
834 self.tk.call('winfo', 'vrooty', self._w))
835 def winfo_width(self):
836 """Return the width of this widget."""
837 return getint(
838 self.tk.call('winfo', 'width', self._w))
839 def winfo_x(self):
840 """Return the x coordinate of the upper left corner of this widget
841 in the parent."""
842 return getint(
843 self.tk.call('winfo', 'x', self._w))
844 def winfo_y(self):
845 """Return the y coordinate of the upper left corner of this widget
846 in the parent."""
847 return getint(
848 self.tk.call('winfo', 'y', self._w))
849 def update(self):
850 """Enter event loop until all pending events have been processed by Tcl."""
851 self.tk.call('update')
852 def update_idletasks(self):
853 """Enter event loop until all idle callbacks have been called. This
854 will update the display of windows but not process events caused by
855 the user."""
856 self.tk.call('update', 'idletasks')
857 def bindtags(self, tagList=None):
858 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000859
Fredrik Lundh06d28152000-08-09 18:03:12 +0000860 With no argument return the list of all bindtags associated with
861 this widget. With a list of strings as argument the bindtags are
862 set to this list. The bindtags determine in which order events are
863 processed (see bind)."""
864 if tagList is None:
865 return self.tk.splitlist(
866 self.tk.call('bindtags', self._w))
867 else:
868 self.tk.call('bindtags', self._w, tagList)
869 def _bind(self, what, sequence, func, add, needcleanup=1):
870 """Internal function."""
871 if type(func) is StringType:
872 self.tk.call(what + (sequence, func))
873 elif func:
874 funcid = self._register(func, self._substitute,
875 needcleanup)
876 cmd = ('%sif {"[%s %s]" == "break"} break\n'
877 %
878 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000879 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000880 self.tk.call(what + (sequence, cmd))
881 return funcid
882 elif sequence:
883 return self.tk.call(what + (sequence,))
884 else:
885 return self.tk.splitlist(self.tk.call(what))
886 def bind(self, sequence=None, func=None, add=None):
887 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000888
Fredrik Lundh06d28152000-08-09 18:03:12 +0000889 SEQUENCE is a string of concatenated event
890 patterns. An event pattern is of the form
891 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
892 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
893 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
894 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
895 Mod1, M1. TYPE is one of Activate, Enter, Map,
896 ButtonPress, Button, Expose, Motion, ButtonRelease
897 FocusIn, MouseWheel, Circulate, FocusOut, Property,
898 Colormap, Gravity Reparent, Configure, KeyPress, Key,
899 Unmap, Deactivate, KeyRelease Visibility, Destroy,
900 Leave and DETAIL is the button number for ButtonPress,
901 ButtonRelease and DETAIL is the Keysym for KeyPress and
902 KeyRelease. Examples are
903 <Control-Button-1> for pressing Control and mouse button 1 or
904 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
905 An event pattern can also be a virtual event of the form
906 <<AString>> where AString can be arbitrary. This
907 event can be generated by event_generate.
908 If events are concatenated they must appear shortly
909 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000910
Fredrik Lundh06d28152000-08-09 18:03:12 +0000911 FUNC will be called if the event sequence occurs with an
912 instance of Event as argument. If the return value of FUNC is
913 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000914
Fredrik Lundh06d28152000-08-09 18:03:12 +0000915 An additional boolean parameter ADD specifies whether FUNC will
916 be called additionally to the other bound function or whether
917 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000918
Fredrik Lundh06d28152000-08-09 18:03:12 +0000919 Bind will return an identifier to allow deletion of the bound function with
920 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000921
Fredrik Lundh06d28152000-08-09 18:03:12 +0000922 If FUNC or SEQUENCE is omitted the bound function or list
923 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000924
Fredrik Lundh06d28152000-08-09 18:03:12 +0000925 return self._bind(('bind', self._w), sequence, func, add)
926 def unbind(self, sequence, funcid=None):
927 """Unbind for this widget for event SEQUENCE the
928 function identified with FUNCID."""
929 self.tk.call('bind', self._w, sequence, '')
930 if funcid:
931 self.deletecommand(funcid)
932 def bind_all(self, sequence=None, func=None, add=None):
933 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
934 An additional boolean parameter ADD specifies whether FUNC will
935 be called additionally to the other bound function or whether
936 it will replace the previous function. See bind for the return value."""
937 return self._bind(('bind', 'all'), sequence, func, add, 0)
938 def unbind_all(self, sequence):
939 """Unbind for all widgets for event SEQUENCE all functions."""
940 self.tk.call('bind', 'all' , sequence, '')
941 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000942
Fredrik Lundh06d28152000-08-09 18:03:12 +0000943 """Bind to widgets with bindtag CLASSNAME at event
944 SEQUENCE a call of function FUNC. An additional
945 boolean parameter ADD specifies whether FUNC will be
946 called additionally to the other bound function or
947 whether it will replace the previous function. See bind for
948 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000949
Fredrik Lundh06d28152000-08-09 18:03:12 +0000950 return self._bind(('bind', className), sequence, func, add, 0)
951 def unbind_class(self, className, sequence):
952 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
953 all functions."""
954 self.tk.call('bind', className , sequence, '')
955 def mainloop(self, n=0):
956 """Call the mainloop of Tk."""
957 self.tk.mainloop(n)
958 def quit(self):
959 """Quit the Tcl interpreter. All widgets will be destroyed."""
960 self.tk.quit()
961 def _getints(self, string):
962 """Internal function."""
963 if string:
964 return tuple(map(getint, self.tk.splitlist(string)))
965 def _getdoubles(self, string):
966 """Internal function."""
967 if string:
968 return tuple(map(getdouble, self.tk.splitlist(string)))
969 def _getboolean(self, string):
970 """Internal function."""
971 if string:
972 return self.tk.getboolean(string)
973 def _displayof(self, displayof):
974 """Internal function."""
975 if displayof:
976 return ('-displayof', displayof)
977 if displayof is None:
978 return ('-displayof', self._w)
979 return ()
980 def _options(self, cnf, kw = None):
981 """Internal function."""
982 if kw:
983 cnf = _cnfmerge((cnf, kw))
984 else:
985 cnf = _cnfmerge(cnf)
986 res = ()
987 for k, v in cnf.items():
988 if v is not None:
989 if k[-1] == '_': k = k[:-1]
990 if callable(v):
991 v = self._register(v)
992 res = res + ('-'+k, v)
993 return res
994 def nametowidget(self, name):
995 """Return the Tkinter instance of a widget identified by
996 its Tcl name NAME."""
997 w = self
998 if name[0] == '.':
999 w = w._root()
1000 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001001 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +00001002 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001003 if i >= 0:
1004 name, tail = name[:i], name[i+1:]
1005 else:
1006 tail = ''
1007 w = w.children[name]
1008 name = tail
1009 return w
1010 _nametowidget = nametowidget
1011 def _register(self, func, subst=None, needcleanup=1):
1012 """Return a newly created Tcl function. If this
1013 function is called, the Python function FUNC will
1014 be executed. An optional function SUBST can
1015 be given which will be executed before FUNC."""
1016 f = CallWrapper(func, subst, self).__call__
1017 name = `id(f)`
1018 try:
1019 func = func.im_func
1020 except AttributeError:
1021 pass
1022 try:
1023 name = name + func.__name__
1024 except AttributeError:
1025 pass
1026 self.tk.createcommand(name, f)
1027 if needcleanup:
1028 if self._tclCommands is None:
1029 self._tclCommands = []
1030 self._tclCommands.append(name)
1031 #print '+ Tkinter created command', name
1032 return name
1033 register = _register
1034 def _root(self):
1035 """Internal function."""
1036 w = self
1037 while w.master: w = w.master
1038 return w
1039 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1040 '%s', '%t', '%w', '%x', '%y',
1041 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001042 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001043 def _substitute(self, *args):
1044 """Internal function."""
1045 if len(args) != len(self._subst_format): return args
1046 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001047
Fredrik Lundh06d28152000-08-09 18:03:12 +00001048 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001049 def getint_event(s):
1050 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1051 try:
1052 return int(s)
1053 except ValueError:
1054 return s
1055
Fredrik Lundh06d28152000-08-09 18:03:12 +00001056 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1057 # Missing: (a, c, d, m, o, v, B, R)
1058 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001059 # serial field: valid vor all events
1060 # number of button: ButtonPress and ButtonRelease events only
1061 # height field: Configure, ConfigureRequest, Create,
1062 # ResizeRequest, and Expose events only
1063 # keycode field: KeyPress and KeyRelease events only
1064 # time field: "valid for events that contain a time field"
1065 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1066 # and Expose events only
1067 # x field: "valid for events that contain a x field"
1068 # y field: "valid for events that contain a y field"
1069 # keysym as decimal: KeyPress and KeyRelease events only
1070 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1071 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001072 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001073 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001074 try: e.focus = getboolean(f)
1075 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001076 e.height = getint_event(h)
1077 e.keycode = getint_event(k)
1078 e.state = getint_event(s)
1079 e.time = getint_event(t)
1080 e.width = getint_event(w)
1081 e.x = getint_event(x)
1082 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001083 e.char = A
1084 try: e.send_event = getboolean(E)
1085 except TclError: pass
1086 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001087 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001088 e.type = T
1089 try:
1090 e.widget = self._nametowidget(W)
1091 except KeyError:
1092 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001093 e.x_root = getint_event(X)
1094 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001095 try:
1096 e.delta = getint(D)
1097 except ValueError:
1098 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001099 return (e,)
1100 def _report_exception(self):
1101 """Internal function."""
1102 import sys
1103 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1104 root = self._root()
1105 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001106 def _configure(self, cmd, cnf, kw):
1107 """Internal function."""
1108 if kw:
1109 cnf = _cnfmerge((cnf, kw))
1110 elif cnf:
1111 cnf = _cnfmerge(cnf)
1112 if cnf is None:
1113 cnf = {}
1114 for x in self.tk.split(
1115 self.tk.call(_flatten((self._w, cmd)))):
1116 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1117 return cnf
1118 if type(cnf) is StringType:
1119 x = self.tk.split(
1120 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1121 return (x[0][1:],) + x[1:]
1122 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001123 # These used to be defined in Widget:
1124 def configure(self, cnf=None, **kw):
1125 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001126
Fredrik Lundh06d28152000-08-09 18:03:12 +00001127 The values for resources are specified as keyword
1128 arguments. To get an overview about
1129 the allowed keyword arguments call the method keys.
1130 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001131 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001132 config = configure
1133 def cget(self, key):
1134 """Return the resource value for a KEY given as string."""
1135 return self.tk.call(self._w, 'cget', '-' + key)
1136 __getitem__ = cget
1137 def __setitem__(self, key, value):
1138 self.configure({key: value})
1139 def keys(self):
1140 """Return a list of all resource names of this widget."""
1141 return map(lambda x: x[0][1:],
1142 self.tk.split(self.tk.call(self._w, 'configure')))
1143 def __str__(self):
1144 """Return the window path name of this widget."""
1145 return self._w
1146 # Pack methods that apply to the master
1147 _noarg_ = ['_noarg_']
1148 def pack_propagate(self, flag=_noarg_):
1149 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001150
Fredrik Lundh06d28152000-08-09 18:03:12 +00001151 A boolean argument specifies whether the geometry information
1152 of the slaves will determine the size of this widget. If no argument
1153 is given the current setting will be returned.
1154 """
1155 if flag is Misc._noarg_:
1156 return self._getboolean(self.tk.call(
1157 'pack', 'propagate', self._w))
1158 else:
1159 self.tk.call('pack', 'propagate', self._w, flag)
1160 propagate = pack_propagate
1161 def pack_slaves(self):
1162 """Return a list of all slaves of this widget
1163 in its packing order."""
1164 return map(self._nametowidget,
1165 self.tk.splitlist(
1166 self.tk.call('pack', 'slaves', self._w)))
1167 slaves = pack_slaves
1168 # Place method that applies to the master
1169 def place_slaves(self):
1170 """Return a list of all slaves of this widget
1171 in its packing order."""
1172 return map(self._nametowidget,
1173 self.tk.splitlist(
1174 self.tk.call(
1175 'place', 'slaves', self._w)))
1176 # Grid methods that apply to the master
1177 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1178 """Return a tuple of integer coordinates for the bounding
1179 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001180
Fredrik Lundh06d28152000-08-09 18:03:12 +00001181 If COLUMN, ROW is given the bounding box applies from
1182 the cell with row and column 0 to the specified
1183 cell. If COL2 and ROW2 are given the bounding box
1184 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001185
Fredrik Lundh06d28152000-08-09 18:03:12 +00001186 The returned integers specify the offset of the upper left
1187 corner in the master widget and the width and height.
1188 """
1189 args = ('grid', 'bbox', self._w)
1190 if column is not None and row is not None:
1191 args = args + (column, row)
1192 if col2 is not None and row2 is not None:
1193 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001194 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001195
Fredrik Lundh06d28152000-08-09 18:03:12 +00001196 bbox = grid_bbox
1197 def _grid_configure(self, command, index, cnf, kw):
1198 """Internal function."""
1199 if type(cnf) is StringType and not kw:
1200 if cnf[-1:] == '_':
1201 cnf = cnf[:-1]
1202 if cnf[:1] != '-':
1203 cnf = '-'+cnf
1204 options = (cnf,)
1205 else:
1206 options = self._options(cnf, kw)
1207 if not options:
1208 res = self.tk.call('grid',
1209 command, self._w, index)
1210 words = self.tk.splitlist(res)
1211 dict = {}
1212 for i in range(0, len(words), 2):
1213 key = words[i][1:]
1214 value = words[i+1]
1215 if not value:
1216 value = None
1217 elif '.' in value:
1218 value = getdouble(value)
1219 else:
1220 value = getint(value)
1221 dict[key] = value
1222 return dict
1223 res = self.tk.call(
1224 ('grid', command, self._w, index)
1225 + options)
1226 if len(options) == 1:
1227 if not res: return None
1228 # In Tk 7.5, -width can be a float
1229 if '.' in res: return getdouble(res)
1230 return getint(res)
1231 def grid_columnconfigure(self, index, cnf={}, **kw):
1232 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001233
Fredrik Lundh06d28152000-08-09 18:03:12 +00001234 Valid resources are minsize (minimum size of the column),
1235 weight (how much does additional space propagate to this column)
1236 and pad (how much space to let additionally)."""
1237 return self._grid_configure('columnconfigure', index, cnf, kw)
1238 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001239 def grid_location(self, x, y):
1240 """Return a tuple of column and row which identify the cell
1241 at which the pixel at position X and Y inside the master
1242 widget is located."""
1243 return self._getints(
1244 self.tk.call(
1245 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001246 def grid_propagate(self, flag=_noarg_):
1247 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001248
Fredrik Lundh06d28152000-08-09 18:03:12 +00001249 A boolean argument specifies whether the geometry information
1250 of the slaves will determine the size of this widget. If no argument
1251 is given, the current setting will be returned.
1252 """
1253 if flag is Misc._noarg_:
1254 return self._getboolean(self.tk.call(
1255 'grid', 'propagate', self._w))
1256 else:
1257 self.tk.call('grid', 'propagate', self._w, flag)
1258 def grid_rowconfigure(self, index, cnf={}, **kw):
1259 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001260
Fredrik Lundh06d28152000-08-09 18:03:12 +00001261 Valid resources are minsize (minimum size of the row),
1262 weight (how much does additional space propagate to this row)
1263 and pad (how much space to let additionally)."""
1264 return self._grid_configure('rowconfigure', index, cnf, kw)
1265 rowconfigure = grid_rowconfigure
1266 def grid_size(self):
1267 """Return a tuple of the number of column and rows in the grid."""
1268 return self._getints(
1269 self.tk.call('grid', 'size', self._w)) or None
1270 size = grid_size
1271 def grid_slaves(self, row=None, column=None):
1272 """Return a list of all slaves of this widget
1273 in its packing order."""
1274 args = ()
1275 if row is not None:
1276 args = args + ('-row', row)
1277 if column is not None:
1278 args = args + ('-column', column)
1279 return map(self._nametowidget,
1280 self.tk.splitlist(self.tk.call(
1281 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001282
Fredrik Lundh06d28152000-08-09 18:03:12 +00001283 # Support for the "event" command, new in Tk 4.2.
1284 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001285
Fredrik Lundh06d28152000-08-09 18:03:12 +00001286 def event_add(self, virtual, *sequences):
1287 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1288 to an event SEQUENCE such that the virtual event is triggered
1289 whenever SEQUENCE occurs."""
1290 args = ('event', 'add', virtual) + sequences
1291 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001292
Fredrik Lundh06d28152000-08-09 18:03:12 +00001293 def event_delete(self, virtual, *sequences):
1294 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1295 args = ('event', 'delete', virtual) + sequences
1296 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001297
Fredrik Lundh06d28152000-08-09 18:03:12 +00001298 def event_generate(self, sequence, **kw):
1299 """Generate an event SEQUENCE. Additional
1300 keyword arguments specify parameter of the event
1301 (e.g. x, y, rootx, rooty)."""
1302 args = ('event', 'generate', self._w, sequence)
1303 for k, v in kw.items():
1304 args = args + ('-%s' % k, str(v))
1305 self.tk.call(args)
1306
1307 def event_info(self, virtual=None):
1308 """Return a list of all virtual events or the information
1309 about the SEQUENCE bound to the virtual event VIRTUAL."""
1310 return self.tk.splitlist(
1311 self.tk.call('event', 'info', virtual))
1312
1313 # Image related commands
1314
1315 def image_names(self):
1316 """Return a list of all existing image names."""
1317 return self.tk.call('image', 'names')
1318
1319 def image_types(self):
1320 """Return a list of all available image types (e.g. phote bitmap)."""
1321 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001322
Guido van Rossum80f8be81997-12-02 19:51:39 +00001323
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001324class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001325 """Internal class. Stores function to call when some user
1326 defined Tcl function is called e.g. after an event occurred."""
1327 def __init__(self, func, subst, widget):
1328 """Store FUNC, SUBST and WIDGET as members."""
1329 self.func = func
1330 self.subst = subst
1331 self.widget = widget
1332 def __call__(self, *args):
1333 """Apply first function SUBST to arguments, than FUNC."""
1334 try:
1335 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001336 args = self.subst(*args)
1337 return self.func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001338 except SystemExit, msg:
1339 raise SystemExit, msg
1340 except:
1341 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001342
Guido van Rossume365a591998-05-01 19:48:20 +00001343
Guido van Rossum18468821994-06-20 07:49:28 +00001344class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001345 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001346
Fredrik Lundh06d28152000-08-09 18:03:12 +00001347 def wm_aspect(self,
1348 minNumer=None, minDenom=None,
1349 maxNumer=None, maxDenom=None):
1350 """Instruct the window manager to set the aspect ratio (width/height)
1351 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1352 of the actual values if no argument is given."""
1353 return self._getints(
1354 self.tk.call('wm', 'aspect', self._w,
1355 minNumer, minDenom,
1356 maxNumer, maxDenom))
1357 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001358
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001359 def wm_attributes(self, *args):
1360 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001361
1362 The first form returns a list of the platform specific flags and
1363 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001364 option. The third form sets one or more of the values. The values
1365 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001366
1367 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001368 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001369 to toolwindow (as defined in the MSDN). -topmost gets or sets
1370 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001371 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001372
1373 On Macintosh, XXXXX
1374
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001375 On Unix, there are currently no special attribute values.
1376 """
1377 args = ('wm', 'attributes', self._w) + args
1378 return self.tk.call(args)
1379 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001380
Fredrik Lundh06d28152000-08-09 18:03:12 +00001381 def wm_client(self, name=None):
1382 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1383 current value."""
1384 return self.tk.call('wm', 'client', self._w, name)
1385 client = wm_client
1386 def wm_colormapwindows(self, *wlist):
1387 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1388 of this widget. This list contains windows whose colormaps differ from their
1389 parents. Return current list of widgets if WLIST is empty."""
1390 if len(wlist) > 1:
1391 wlist = (wlist,) # Tk needs a list of windows here
1392 args = ('wm', 'colormapwindows', self._w) + wlist
1393 return map(self._nametowidget, self.tk.call(args))
1394 colormapwindows = wm_colormapwindows
1395 def wm_command(self, value=None):
1396 """Store VALUE in WM_COMMAND property. It is the command
1397 which shall be used to invoke the application. Return current
1398 command if VALUE is None."""
1399 return self.tk.call('wm', 'command', self._w, value)
1400 command = wm_command
1401 def wm_deiconify(self):
1402 """Deiconify this widget. If it was never mapped it will not be mapped.
1403 On Windows it will raise this widget and give it the focus."""
1404 return self.tk.call('wm', 'deiconify', self._w)
1405 deiconify = wm_deiconify
1406 def wm_focusmodel(self, model=None):
1407 """Set focus model to MODEL. "active" means that this widget will claim
1408 the focus itself, "passive" means that the window manager shall give
1409 the focus. Return current focus model if MODEL is None."""
1410 return self.tk.call('wm', 'focusmodel', self._w, model)
1411 focusmodel = wm_focusmodel
1412 def wm_frame(self):
1413 """Return identifier for decorative frame of this widget if present."""
1414 return self.tk.call('wm', 'frame', self._w)
1415 frame = wm_frame
1416 def wm_geometry(self, newGeometry=None):
1417 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1418 current value if None is given."""
1419 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1420 geometry = wm_geometry
1421 def wm_grid(self,
1422 baseWidth=None, baseHeight=None,
1423 widthInc=None, heightInc=None):
1424 """Instruct the window manager that this widget shall only be
1425 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1426 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1427 number of grid units requested in Tk_GeometryRequest."""
1428 return self._getints(self.tk.call(
1429 'wm', 'grid', self._w,
1430 baseWidth, baseHeight, widthInc, heightInc))
1431 grid = wm_grid
1432 def wm_group(self, pathName=None):
1433 """Set the group leader widgets for related widgets to PATHNAME. Return
1434 the group leader of this widget if None is given."""
1435 return self.tk.call('wm', 'group', self._w, pathName)
1436 group = wm_group
1437 def wm_iconbitmap(self, bitmap=None):
1438 """Set bitmap for the iconified widget to BITMAP. Return
1439 the bitmap if None is given."""
1440 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1441 iconbitmap = wm_iconbitmap
1442 def wm_iconify(self):
1443 """Display widget as icon."""
1444 return self.tk.call('wm', 'iconify', self._w)
1445 iconify = wm_iconify
1446 def wm_iconmask(self, bitmap=None):
1447 """Set mask for the icon bitmap of this widget. Return the
1448 mask if None is given."""
1449 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1450 iconmask = wm_iconmask
1451 def wm_iconname(self, newName=None):
1452 """Set the name of the icon for this widget. Return the name if
1453 None is given."""
1454 return self.tk.call('wm', 'iconname', self._w, newName)
1455 iconname = wm_iconname
1456 def wm_iconposition(self, x=None, y=None):
1457 """Set the position of the icon of this widget to X and Y. Return
1458 a tuple of the current values of X and X if None is given."""
1459 return self._getints(self.tk.call(
1460 'wm', 'iconposition', self._w, x, y))
1461 iconposition = wm_iconposition
1462 def wm_iconwindow(self, pathName=None):
1463 """Set widget PATHNAME to be displayed instead of icon. Return the current
1464 value if None is given."""
1465 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1466 iconwindow = wm_iconwindow
1467 def wm_maxsize(self, width=None, height=None):
1468 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1469 the values are given in grid units. Return the current values if None
1470 is given."""
1471 return self._getints(self.tk.call(
1472 'wm', 'maxsize', self._w, width, height))
1473 maxsize = wm_maxsize
1474 def wm_minsize(self, width=None, height=None):
1475 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1476 the values are given in grid units. Return the current values if None
1477 is given."""
1478 return self._getints(self.tk.call(
1479 'wm', 'minsize', self._w, width, height))
1480 minsize = wm_minsize
1481 def wm_overrideredirect(self, boolean=None):
1482 """Instruct the window manager to ignore this widget
1483 if BOOLEAN is given with 1. Return the current value if None
1484 is given."""
1485 return self._getboolean(self.tk.call(
1486 'wm', 'overrideredirect', self._w, boolean))
1487 overrideredirect = wm_overrideredirect
1488 def wm_positionfrom(self, who=None):
1489 """Instruct the window manager that the position of this widget shall
1490 be defined by the user if WHO is "user", and by its own policy if WHO is
1491 "program"."""
1492 return self.tk.call('wm', 'positionfrom', self._w, who)
1493 positionfrom = wm_positionfrom
1494 def wm_protocol(self, name=None, func=None):
1495 """Bind function FUNC to command NAME for this widget.
1496 Return the function bound to NAME if None is given. NAME could be
1497 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1498 if callable(func):
1499 command = self._register(func)
1500 else:
1501 command = func
1502 return self.tk.call(
1503 'wm', 'protocol', self._w, name, command)
1504 protocol = wm_protocol
1505 def wm_resizable(self, width=None, height=None):
1506 """Instruct the window manager whether this width can be resized
1507 in WIDTH or HEIGHT. Both values are boolean values."""
1508 return self.tk.call('wm', 'resizable', self._w, width, height)
1509 resizable = wm_resizable
1510 def wm_sizefrom(self, who=None):
1511 """Instruct the window manager that the size of this widget shall
1512 be defined by the user if WHO is "user", and by its own policy if WHO is
1513 "program"."""
1514 return self.tk.call('wm', 'sizefrom', self._w, who)
1515 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001516 def wm_state(self, newstate=None):
1517 """Query or set the state of this widget as one of normal, icon,
1518 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1519 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001520 state = wm_state
1521 def wm_title(self, string=None):
1522 """Set the title of this widget."""
1523 return self.tk.call('wm', 'title', self._w, string)
1524 title = wm_title
1525 def wm_transient(self, master=None):
1526 """Instruct the window manager that this widget is transient
1527 with regard to widget MASTER."""
1528 return self.tk.call('wm', 'transient', self._w, master)
1529 transient = wm_transient
1530 def wm_withdraw(self):
1531 """Withdraw this widget from the screen such that it is unmapped
1532 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1533 return self.tk.call('wm', 'withdraw', self._w)
1534 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001535
Guido van Rossum18468821994-06-20 07:49:28 +00001536
1537class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001538 """Toplevel widget of Tk which represents mostly the main window
1539 of an appliation. It has an associated Tcl interpreter."""
1540 _w = '.'
1541 def __init__(self, screenName=None, baseName=None, className='Tk'):
1542 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1543 be created. BASENAME will be used for the identification of the profile file (see
1544 readprofile).
1545 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1546 is the name of the widget class."""
1547 global _default_root
1548 self.master = None
1549 self.children = {}
1550 if baseName is None:
1551 import sys, os
1552 baseName = os.path.basename(sys.argv[0])
1553 baseName, ext = os.path.splitext(baseName)
1554 if ext not in ('.py', '.pyc', '.pyo'):
1555 baseName = baseName + ext
1556 self.tk = _tkinter.create(screenName, baseName, className)
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001557 self.tk.wantobjects(wantobjects)
Jack Jansenbe92af02001-08-23 13:25:59 +00001558 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001559 # Disable event scanning except for Command-Period
1560 _MacOS.SchedParams(1, 0)
1561 # Work around nasty MacTk bug
1562 # XXX Is this one still needed?
1563 self.update()
1564 # Version sanity checks
1565 tk_version = self.tk.getvar('tk_version')
1566 if tk_version != _tkinter.TK_VERSION:
1567 raise RuntimeError, \
1568 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1569 % (_tkinter.TK_VERSION, tk_version)
Martin v. Löwis54895972003-05-24 11:37:15 +00001570 # Under unknown circumstances, tcl_version gets coerced to float
1571 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001572 if tcl_version != _tkinter.TCL_VERSION:
1573 raise RuntimeError, \
1574 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1575 % (_tkinter.TCL_VERSION, tcl_version)
1576 if TkVersion < 4.0:
1577 raise RuntimeError, \
1578 "Tk 4.0 or higher is required; found Tk %s" \
1579 % str(TkVersion)
1580 self.tk.createcommand('tkerror', _tkerror)
1581 self.tk.createcommand('exit', _exit)
1582 self.readprofile(baseName, className)
1583 if _support_default_root and not _default_root:
1584 _default_root = self
1585 self.protocol("WM_DELETE_WINDOW", self.destroy)
1586 def destroy(self):
1587 """Destroy this and all descendants widgets. This will
1588 end the application of this Tcl interpreter."""
1589 for c in self.children.values(): c.destroy()
1590 self.tk.call('destroy', self._w)
1591 Misc.destroy(self)
1592 global _default_root
1593 if _support_default_root and _default_root is self:
1594 _default_root = None
1595 def readprofile(self, baseName, className):
1596 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1597 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1598 such a file exists in the home directory."""
1599 import os
1600 if os.environ.has_key('HOME'): home = os.environ['HOME']
1601 else: home = os.curdir
1602 class_tcl = os.path.join(home, '.%s.tcl' % className)
1603 class_py = os.path.join(home, '.%s.py' % className)
1604 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1605 base_py = os.path.join(home, '.%s.py' % baseName)
1606 dir = {'self': self}
1607 exec 'from Tkinter import *' in dir
1608 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001609 self.tk.call('source', class_tcl)
1610 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001611 execfile(class_py, dir)
1612 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001613 self.tk.call('source', base_tcl)
1614 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001615 execfile(base_py, dir)
1616 def report_callback_exception(self, exc, val, tb):
1617 """Internal function. It reports exception on sys.stderr."""
1618 import traceback, sys
1619 sys.stderr.write("Exception in Tkinter callback\n")
1620 sys.last_type = exc
1621 sys.last_value = val
1622 sys.last_traceback = tb
1623 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001624
Guido van Rossum368e06b1997-11-07 20:38:49 +00001625# Ideally, the classes Pack, Place and Grid disappear, the
1626# pack/place/grid methods are defined on the Widget class, and
1627# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1628# ...), with pack(), place() and grid() being short for
1629# pack_configure(), place_configure() and grid_columnconfigure(), and
1630# forget() being short for pack_forget(). As a practical matter, I'm
1631# afraid that there is too much code out there that may be using the
1632# Pack, Place or Grid class, so I leave them intact -- but only as
1633# backwards compatibility features. Also note that those methods that
1634# take a master as argument (e.g. pack_propagate) have been moved to
1635# the Misc class (which now incorporates all methods common between
1636# toplevel and interior widgets). Again, for compatibility, these are
1637# copied into the Pack, Place or Grid class.
1638
Guido van Rossum18468821994-06-20 07:49:28 +00001639class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001640 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001641
Fredrik Lundh06d28152000-08-09 18:03:12 +00001642 Base class to use the methods pack_* in every widget."""
1643 def pack_configure(self, cnf={}, **kw):
1644 """Pack a widget in the parent widget. Use as options:
1645 after=widget - pack it after you have packed widget
1646 anchor=NSEW (or subset) - position widget according to
1647 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001648 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001649 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001650 fill=NONE or X or Y or BOTH - fill widget if widget grows
1651 in=master - use master to contain this widget
1652 ipadx=amount - add internal padding in x direction
1653 ipady=amount - add internal padding in y direction
1654 padx=amount - add padding in x direction
1655 pady=amount - add padding in y direction
1656 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1657 """
1658 self.tk.call(
1659 ('pack', 'configure', self._w)
1660 + self._options(cnf, kw))
1661 pack = configure = config = pack_configure
1662 def pack_forget(self):
1663 """Unmap this widget and do not use it for the packing order."""
1664 self.tk.call('pack', 'forget', self._w)
1665 forget = pack_forget
1666 def pack_info(self):
1667 """Return information about the packing options
1668 for this widget."""
1669 words = self.tk.splitlist(
1670 self.tk.call('pack', 'info', self._w))
1671 dict = {}
1672 for i in range(0, len(words), 2):
1673 key = words[i][1:]
1674 value = words[i+1]
1675 if value[:1] == '.':
1676 value = self._nametowidget(value)
1677 dict[key] = value
1678 return dict
1679 info = pack_info
1680 propagate = pack_propagate = Misc.pack_propagate
1681 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001682
1683class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001684 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001685
Fredrik Lundh06d28152000-08-09 18:03:12 +00001686 Base class to use the methods place_* in every widget."""
1687 def place_configure(self, cnf={}, **kw):
1688 """Place a widget in the parent widget. Use as options:
1689 in=master - master relative to which the widget is placed.
1690 x=amount - locate anchor of this widget at position x of master
1691 y=amount - locate anchor of this widget at position y of master
1692 relx=amount - locate anchor of this widget between 0.0 and 1.0
1693 relative to width of master (1.0 is right edge)
1694 rely=amount - locate anchor of this widget between 0.0 and 1.0
1695 relative to height of master (1.0 is bottom edge)
1696 anchor=NSEW (or subset) - position anchor according to given direction
1697 width=amount - width of this widget in pixel
1698 height=amount - height of this widget in pixel
1699 relwidth=amount - width of this widget between 0.0 and 1.0
1700 relative to width of master (1.0 is the same width
1701 as the master)
1702 relheight=amount - height of this widget between 0.0 and 1.0
1703 relative to height of master (1.0 is the same
1704 height as the master)
1705 bordermode="inside" or "outside" - whether to take border width of master widget
1706 into account
1707 """
1708 for k in ['in_']:
1709 if kw.has_key(k):
1710 kw[k[:-1]] = kw[k]
1711 del kw[k]
1712 self.tk.call(
1713 ('place', 'configure', self._w)
1714 + self._options(cnf, kw))
1715 place = configure = config = place_configure
1716 def place_forget(self):
1717 """Unmap this widget."""
1718 self.tk.call('place', 'forget', self._w)
1719 forget = place_forget
1720 def place_info(self):
1721 """Return information about the placing options
1722 for this widget."""
1723 words = self.tk.splitlist(
1724 self.tk.call('place', 'info', self._w))
1725 dict = {}
1726 for i in range(0, len(words), 2):
1727 key = words[i][1:]
1728 value = words[i+1]
1729 if value[:1] == '.':
1730 value = self._nametowidget(value)
1731 dict[key] = value
1732 return dict
1733 info = place_info
1734 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001735
Guido van Rossum37dcab11996-05-16 16:00:19 +00001736class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001737 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001738
Fredrik Lundh06d28152000-08-09 18:03:12 +00001739 Base class to use the methods grid_* in every widget."""
1740 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1741 def grid_configure(self, cnf={}, **kw):
1742 """Position a widget in the parent widget in a grid. Use as options:
1743 column=number - use cell identified with given column (starting with 0)
1744 columnspan=number - this widget will span several columns
1745 in=master - use master to contain this widget
1746 ipadx=amount - add internal padding in x direction
1747 ipady=amount - add internal padding in y direction
1748 padx=amount - add padding in x direction
1749 pady=amount - add padding in y direction
1750 row=number - use cell identified with given row (starting with 0)
1751 rowspan=number - this widget will span several rows
1752 sticky=NSEW - if cell is larger on which sides will this
1753 widget stick to the cell boundary
1754 """
1755 self.tk.call(
1756 ('grid', 'configure', self._w)
1757 + self._options(cnf, kw))
1758 grid = configure = config = grid_configure
1759 bbox = grid_bbox = Misc.grid_bbox
1760 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1761 def grid_forget(self):
1762 """Unmap this widget."""
1763 self.tk.call('grid', 'forget', self._w)
1764 forget = grid_forget
1765 def grid_remove(self):
1766 """Unmap this widget but remember the grid options."""
1767 self.tk.call('grid', 'remove', self._w)
1768 def grid_info(self):
1769 """Return information about the options
1770 for positioning this widget in a grid."""
1771 words = self.tk.splitlist(
1772 self.tk.call('grid', 'info', self._w))
1773 dict = {}
1774 for i in range(0, len(words), 2):
1775 key = words[i][1:]
1776 value = words[i+1]
1777 if value[:1] == '.':
1778 value = self._nametowidget(value)
1779 dict[key] = value
1780 return dict
1781 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001782 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001783 propagate = grid_propagate = Misc.grid_propagate
1784 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1785 size = grid_size = Misc.grid_size
1786 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001787
Guido van Rossum368e06b1997-11-07 20:38:49 +00001788class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001789 """Internal class."""
1790 def _setup(self, master, cnf):
1791 """Internal function. Sets up information about children."""
1792 if _support_default_root:
1793 global _default_root
1794 if not master:
1795 if not _default_root:
1796 _default_root = Tk()
1797 master = _default_root
1798 self.master = master
1799 self.tk = master.tk
1800 name = None
1801 if cnf.has_key('name'):
1802 name = cnf['name']
1803 del cnf['name']
1804 if not name:
1805 name = `id(self)`
1806 self._name = name
1807 if master._w=='.':
1808 self._w = '.' + name
1809 else:
1810 self._w = master._w + '.' + name
1811 self.children = {}
1812 if self.master.children.has_key(self._name):
1813 self.master.children[self._name].destroy()
1814 self.master.children[self._name] = self
1815 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1816 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1817 and appropriate options."""
1818 if kw:
1819 cnf = _cnfmerge((cnf, kw))
1820 self.widgetName = widgetName
1821 BaseWidget._setup(self, master, cnf)
1822 classes = []
1823 for k in cnf.keys():
1824 if type(k) is ClassType:
1825 classes.append((k, cnf[k]))
1826 del cnf[k]
1827 self.tk.call(
1828 (widgetName, self._w) + extra + self._options(cnf))
1829 for k, v in classes:
1830 k.configure(self, v)
1831 def destroy(self):
1832 """Destroy this and all descendants widgets."""
1833 for c in self.children.values(): c.destroy()
1834 if self.master.children.has_key(self._name):
1835 del self.master.children[self._name]
1836 self.tk.call('destroy', self._w)
1837 Misc.destroy(self)
1838 def _do(self, name, args=()):
1839 # XXX Obsolete -- better use self.tk.call directly!
1840 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001841
Guido van Rossum368e06b1997-11-07 20:38:49 +00001842class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001843 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001844
Fredrik Lundh06d28152000-08-09 18:03:12 +00001845 Base class for a widget which can be positioned with the geometry managers
1846 Pack, Place or Grid."""
1847 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001848
1849class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001850 """Toplevel widget, e.g. for dialogs."""
1851 def __init__(self, master=None, cnf={}, **kw):
1852 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001853
Fredrik Lundh06d28152000-08-09 18:03:12 +00001854 Valid resource names: background, bd, bg, borderwidth, class,
1855 colormap, container, cursor, height, highlightbackground,
1856 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1857 use, visual, width."""
1858 if kw:
1859 cnf = _cnfmerge((cnf, kw))
1860 extra = ()
1861 for wmkey in ['screen', 'class_', 'class', 'visual',
1862 'colormap']:
1863 if cnf.has_key(wmkey):
1864 val = cnf[wmkey]
1865 # TBD: a hack needed because some keys
1866 # are not valid as keyword arguments
1867 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1868 else: opt = '-'+wmkey
1869 extra = extra + (opt, val)
1870 del cnf[wmkey]
1871 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1872 root = self._root()
1873 self.iconname(root.iconname())
1874 self.title(root.title())
1875 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001876
1877class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001878 """Button widget."""
1879 def __init__(self, master=None, cnf={}, **kw):
1880 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001881
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001882 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001883
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001884 activebackground, activeforeground, anchor,
1885 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001886 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001887 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001888 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001889 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001890 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001891 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001892
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001893 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001894
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001895 command, compound, default, height,
1896 overrelief, state, width
1897 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001898 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001899
Fredrik Lundh06d28152000-08-09 18:03:12 +00001900 def tkButtonEnter(self, *dummy):
1901 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001902
Fredrik Lundh06d28152000-08-09 18:03:12 +00001903 def tkButtonLeave(self, *dummy):
1904 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001905
Fredrik Lundh06d28152000-08-09 18:03:12 +00001906 def tkButtonDown(self, *dummy):
1907 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001908
Fredrik Lundh06d28152000-08-09 18:03:12 +00001909 def tkButtonUp(self, *dummy):
1910 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001911
Fredrik Lundh06d28152000-08-09 18:03:12 +00001912 def tkButtonInvoke(self, *dummy):
1913 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001914
Fredrik Lundh06d28152000-08-09 18:03:12 +00001915 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001916 """Flash the button.
1917
1918 This is accomplished by redisplaying
1919 the button several times, alternating between active and
1920 normal colors. At the end of the flash the button is left
1921 in the same normal/active state as when the command was
1922 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001923 disabled.
1924 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001925 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00001926
Fredrik Lundh06d28152000-08-09 18:03:12 +00001927 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001928 """Invoke the command associated with the button.
1929
1930 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001931 or an empty string if there is no command associated with
1932 the button. This command is ignored if the button's state
1933 is disabled.
1934 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001935 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001936
1937# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001938# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001939def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001940 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001941def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001942 s = 'insert'
1943 for a in args:
1944 if a: s = s + (' ' + a)
1945 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001946def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001947 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001948def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001949 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001950def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001951 if y is None:
1952 return '@' + `x`
1953 else:
1954 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001955
1956class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001957 """Canvas widget to display graphical elements like lines or text."""
1958 def __init__(self, master=None, cnf={}, **kw):
1959 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001960
Fredrik Lundh06d28152000-08-09 18:03:12 +00001961 Valid resource names: background, bd, bg, borderwidth, closeenough,
1962 confine, cursor, height, highlightbackground, highlightcolor,
1963 highlightthickness, insertbackground, insertborderwidth,
1964 insertofftime, insertontime, insertwidth, offset, relief,
1965 scrollregion, selectbackground, selectborderwidth, selectforeground,
1966 state, takefocus, width, xscrollcommand, xscrollincrement,
1967 yscrollcommand, yscrollincrement."""
1968 Widget.__init__(self, master, 'canvas', cnf, kw)
1969 def addtag(self, *args):
1970 """Internal function."""
1971 self.tk.call((self._w, 'addtag') + args)
1972 def addtag_above(self, newtag, tagOrId):
1973 """Add tag NEWTAG to all items above TAGORID."""
1974 self.addtag(newtag, 'above', tagOrId)
1975 def addtag_all(self, newtag):
1976 """Add tag NEWTAG to all items."""
1977 self.addtag(newtag, 'all')
1978 def addtag_below(self, newtag, tagOrId):
1979 """Add tag NEWTAG to all items below TAGORID."""
1980 self.addtag(newtag, 'below', tagOrId)
1981 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1982 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1983 If several match take the top-most.
1984 All items closer than HALO are considered overlapping (all are
1985 closests). If START is specified the next below this tag is taken."""
1986 self.addtag(newtag, 'closest', x, y, halo, start)
1987 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1988 """Add tag NEWTAG to all items in the rectangle defined
1989 by X1,Y1,X2,Y2."""
1990 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1991 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1992 """Add tag NEWTAG to all items which overlap the rectangle
1993 defined by X1,Y1,X2,Y2."""
1994 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1995 def addtag_withtag(self, newtag, tagOrId):
1996 """Add tag NEWTAG to all items with TAGORID."""
1997 self.addtag(newtag, 'withtag', tagOrId)
1998 def bbox(self, *args):
1999 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2000 which encloses all items with tags specified as arguments."""
2001 return self._getints(
2002 self.tk.call((self._w, 'bbox') + args)) or None
2003 def tag_unbind(self, tagOrId, sequence, funcid=None):
2004 """Unbind for all items with TAGORID for event SEQUENCE the
2005 function identified with FUNCID."""
2006 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2007 if funcid:
2008 self.deletecommand(funcid)
2009 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2010 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002011
Fredrik Lundh06d28152000-08-09 18:03:12 +00002012 An additional boolean parameter ADD specifies whether FUNC will be
2013 called additionally to the other bound function or whether it will
2014 replace the previous function. See bind for the return value."""
2015 return self._bind((self._w, 'bind', tagOrId),
2016 sequence, func, add)
2017 def canvasx(self, screenx, gridspacing=None):
2018 """Return the canvas x coordinate of pixel position SCREENX rounded
2019 to nearest multiple of GRIDSPACING units."""
2020 return getdouble(self.tk.call(
2021 self._w, 'canvasx', screenx, gridspacing))
2022 def canvasy(self, screeny, gridspacing=None):
2023 """Return the canvas y coordinate of pixel position SCREENY rounded
2024 to nearest multiple of GRIDSPACING units."""
2025 return getdouble(self.tk.call(
2026 self._w, 'canvasy', screeny, gridspacing))
2027 def coords(self, *args):
2028 """Return a list of coordinates for the item given in ARGS."""
2029 # XXX Should use _flatten on args
2030 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002031 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002032 self.tk.call((self._w, 'coords') + args)))
2033 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2034 """Internal function."""
2035 args = _flatten(args)
2036 cnf = args[-1]
2037 if type(cnf) in (DictionaryType, TupleType):
2038 args = args[:-1]
2039 else:
2040 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002041 return getint(self.tk.call(
2042 self._w, 'create', itemType,
2043 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002044 def create_arc(self, *args, **kw):
2045 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2046 return self._create('arc', args, kw)
2047 def create_bitmap(self, *args, **kw):
2048 """Create bitmap with coordinates x1,y1."""
2049 return self._create('bitmap', args, kw)
2050 def create_image(self, *args, **kw):
2051 """Create image item with coordinates x1,y1."""
2052 return self._create('image', args, kw)
2053 def create_line(self, *args, **kw):
2054 """Create line with coordinates x1,y1,...,xn,yn."""
2055 return self._create('line', args, kw)
2056 def create_oval(self, *args, **kw):
2057 """Create oval with coordinates x1,y1,x2,y2."""
2058 return self._create('oval', args, kw)
2059 def create_polygon(self, *args, **kw):
2060 """Create polygon with coordinates x1,y1,...,xn,yn."""
2061 return self._create('polygon', args, kw)
2062 def create_rectangle(self, *args, **kw):
2063 """Create rectangle with coordinates x1,y1,x2,y2."""
2064 return self._create('rectangle', args, kw)
2065 def create_text(self, *args, **kw):
2066 """Create text with coordinates x1,y1."""
2067 return self._create('text', args, kw)
2068 def create_window(self, *args, **kw):
2069 """Create window with coordinates x1,y1,x2,y2."""
2070 return self._create('window', args, kw)
2071 def dchars(self, *args):
2072 """Delete characters of text items identified by tag or id in ARGS (possibly
2073 several times) from FIRST to LAST character (including)."""
2074 self.tk.call((self._w, 'dchars') + args)
2075 def delete(self, *args):
2076 """Delete items identified by all tag or ids contained in ARGS."""
2077 self.tk.call((self._w, 'delete') + args)
2078 def dtag(self, *args):
2079 """Delete tag or id given as last arguments in ARGS from items
2080 identified by first argument in ARGS."""
2081 self.tk.call((self._w, 'dtag') + args)
2082 def find(self, *args):
2083 """Internal function."""
2084 return self._getints(
2085 self.tk.call((self._w, 'find') + args)) or ()
2086 def find_above(self, tagOrId):
2087 """Return items above TAGORID."""
2088 return self.find('above', tagOrId)
2089 def find_all(self):
2090 """Return all items."""
2091 return self.find('all')
2092 def find_below(self, tagOrId):
2093 """Return all items below TAGORID."""
2094 return self.find('below', tagOrId)
2095 def find_closest(self, x, y, halo=None, start=None):
2096 """Return item which is closest to pixel at X, Y.
2097 If several match take the top-most.
2098 All items closer than HALO are considered overlapping (all are
2099 closests). If START is specified the next below this tag is taken."""
2100 return self.find('closest', x, y, halo, start)
2101 def find_enclosed(self, x1, y1, x2, y2):
2102 """Return all items in rectangle defined
2103 by X1,Y1,X2,Y2."""
2104 return self.find('enclosed', x1, y1, x2, y2)
2105 def find_overlapping(self, x1, y1, x2, y2):
2106 """Return all items which overlap the rectangle
2107 defined by X1,Y1,X2,Y2."""
2108 return self.find('overlapping', x1, y1, x2, y2)
2109 def find_withtag(self, tagOrId):
2110 """Return all items with TAGORID."""
2111 return self.find('withtag', tagOrId)
2112 def focus(self, *args):
2113 """Set focus to the first item specified in ARGS."""
2114 return self.tk.call((self._w, 'focus') + args)
2115 def gettags(self, *args):
2116 """Return tags associated with the first item specified in ARGS."""
2117 return self.tk.splitlist(
2118 self.tk.call((self._w, 'gettags') + args))
2119 def icursor(self, *args):
2120 """Set cursor at position POS in the item identified by TAGORID.
2121 In ARGS TAGORID must be first."""
2122 self.tk.call((self._w, 'icursor') + args)
2123 def index(self, *args):
2124 """Return position of cursor as integer in item specified in ARGS."""
2125 return getint(self.tk.call((self._w, 'index') + args))
2126 def insert(self, *args):
2127 """Insert TEXT in item TAGORID at position POS. ARGS must
2128 be TAGORID POS TEXT."""
2129 self.tk.call((self._w, 'insert') + args)
2130 def itemcget(self, tagOrId, option):
2131 """Return the resource value for an OPTION for item TAGORID."""
2132 return self.tk.call(
2133 (self._w, 'itemcget') + (tagOrId, '-'+option))
2134 def itemconfigure(self, tagOrId, cnf=None, **kw):
2135 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002136
Fredrik Lundh06d28152000-08-09 18:03:12 +00002137 The values for resources are specified as keyword
2138 arguments. To get an overview about
2139 the allowed keyword arguments call the method without arguments.
2140 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002141 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002142 itemconfig = itemconfigure
2143 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2144 # so the preferred name for them is tag_lower, tag_raise
2145 # (similar to tag_bind, and similar to the Text widget);
2146 # unfortunately can't delete the old ones yet (maybe in 1.6)
2147 def tag_lower(self, *args):
2148 """Lower an item TAGORID given in ARGS
2149 (optional below another item)."""
2150 self.tk.call((self._w, 'lower') + args)
2151 lower = tag_lower
2152 def move(self, *args):
2153 """Move an item TAGORID given in ARGS."""
2154 self.tk.call((self._w, 'move') + args)
2155 def postscript(self, cnf={}, **kw):
2156 """Print the contents of the canvas to a postscript
2157 file. Valid options: colormap, colormode, file, fontmap,
2158 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2159 rotate, witdh, x, y."""
2160 return self.tk.call((self._w, 'postscript') +
2161 self._options(cnf, kw))
2162 def tag_raise(self, *args):
2163 """Raise an item TAGORID given in ARGS
2164 (optional above another item)."""
2165 self.tk.call((self._w, 'raise') + args)
2166 lift = tkraise = tag_raise
2167 def scale(self, *args):
2168 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2169 self.tk.call((self._w, 'scale') + args)
2170 def scan_mark(self, x, y):
2171 """Remember the current X, Y coordinates."""
2172 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002173 def scan_dragto(self, x, y, gain=10):
2174 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002175 difference between X and Y and the coordinates given in
2176 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002177 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002178 def select_adjust(self, tagOrId, index):
2179 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2180 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2181 def select_clear(self):
2182 """Clear the selection if it is in this widget."""
2183 self.tk.call(self._w, 'select', 'clear')
2184 def select_from(self, tagOrId, index):
2185 """Set the fixed end of a selection in item TAGORID to INDEX."""
2186 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2187 def select_item(self):
2188 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002189 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002190 def select_to(self, tagOrId, index):
2191 """Set the variable end of a selection in item TAGORID to INDEX."""
2192 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2193 def type(self, tagOrId):
2194 """Return the type of the item TAGORID."""
2195 return self.tk.call(self._w, 'type', tagOrId) or None
2196 def xview(self, *args):
2197 """Query and change horizontal position of the view."""
2198 if not args:
2199 return self._getdoubles(self.tk.call(self._w, 'xview'))
2200 self.tk.call((self._w, 'xview') + args)
2201 def xview_moveto(self, fraction):
2202 """Adjusts the view in the window so that FRACTION of the
2203 total width of the canvas is off-screen to the left."""
2204 self.tk.call(self._w, 'xview', 'moveto', fraction)
2205 def xview_scroll(self, number, what):
2206 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2207 self.tk.call(self._w, 'xview', 'scroll', number, what)
2208 def yview(self, *args):
2209 """Query and change vertical position of the view."""
2210 if not args:
2211 return self._getdoubles(self.tk.call(self._w, 'yview'))
2212 self.tk.call((self._w, 'yview') + args)
2213 def yview_moveto(self, fraction):
2214 """Adjusts the view in the window so that FRACTION of the
2215 total height of the canvas is off-screen to the top."""
2216 self.tk.call(self._w, 'yview', 'moveto', fraction)
2217 def yview_scroll(self, number, what):
2218 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2219 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002220
2221class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002222 """Checkbutton widget which is either in on- or off-state."""
2223 def __init__(self, master=None, cnf={}, **kw):
2224 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002225
Fredrik Lundh06d28152000-08-09 18:03:12 +00002226 Valid resource names: activebackground, activeforeground, anchor,
2227 background, bd, bg, bitmap, borderwidth, command, cursor,
2228 disabledforeground, fg, font, foreground, height,
2229 highlightbackground, highlightcolor, highlightthickness, image,
2230 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2231 selectcolor, selectimage, state, takefocus, text, textvariable,
2232 underline, variable, width, wraplength."""
2233 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2234 def deselect(self):
2235 """Put the button in off-state."""
2236 self.tk.call(self._w, 'deselect')
2237 def flash(self):
2238 """Flash the button."""
2239 self.tk.call(self._w, 'flash')
2240 def invoke(self):
2241 """Toggle the button and invoke a command if given as resource."""
2242 return self.tk.call(self._w, 'invoke')
2243 def select(self):
2244 """Put the button in on-state."""
2245 self.tk.call(self._w, 'select')
2246 def toggle(self):
2247 """Toggle the button."""
2248 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002249
2250class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002251 """Entry widget which allows to display simple text."""
2252 def __init__(self, master=None, cnf={}, **kw):
2253 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002254
Fredrik Lundh06d28152000-08-09 18:03:12 +00002255 Valid resource names: background, bd, bg, borderwidth, cursor,
2256 exportselection, fg, font, foreground, highlightbackground,
2257 highlightcolor, highlightthickness, insertbackground,
2258 insertborderwidth, insertofftime, insertontime, insertwidth,
2259 invalidcommand, invcmd, justify, relief, selectbackground,
2260 selectborderwidth, selectforeground, show, state, takefocus,
2261 textvariable, validate, validatecommand, vcmd, width,
2262 xscrollcommand."""
2263 Widget.__init__(self, master, 'entry', cnf, kw)
2264 def delete(self, first, last=None):
2265 """Delete text from FIRST to LAST (not included)."""
2266 self.tk.call(self._w, 'delete', first, last)
2267 def get(self):
2268 """Return the text."""
2269 return self.tk.call(self._w, 'get')
2270 def icursor(self, index):
2271 """Insert cursor at INDEX."""
2272 self.tk.call(self._w, 'icursor', index)
2273 def index(self, index):
2274 """Return position of cursor."""
2275 return getint(self.tk.call(
2276 self._w, 'index', index))
2277 def insert(self, index, string):
2278 """Insert STRING at INDEX."""
2279 self.tk.call(self._w, 'insert', index, string)
2280 def scan_mark(self, x):
2281 """Remember the current X, Y coordinates."""
2282 self.tk.call(self._w, 'scan', 'mark', x)
2283 def scan_dragto(self, x):
2284 """Adjust the view of the canvas to 10 times the
2285 difference between X and Y and the coordinates given in
2286 scan_mark."""
2287 self.tk.call(self._w, 'scan', 'dragto', x)
2288 def selection_adjust(self, index):
2289 """Adjust the end of the selection near the cursor to INDEX."""
2290 self.tk.call(self._w, 'selection', 'adjust', index)
2291 select_adjust = selection_adjust
2292 def selection_clear(self):
2293 """Clear the selection if it is in this widget."""
2294 self.tk.call(self._w, 'selection', 'clear')
2295 select_clear = selection_clear
2296 def selection_from(self, index):
2297 """Set the fixed end of a selection to INDEX."""
2298 self.tk.call(self._w, 'selection', 'from', index)
2299 select_from = selection_from
2300 def selection_present(self):
2301 """Return whether the widget has the selection."""
2302 return self.tk.getboolean(
2303 self.tk.call(self._w, 'selection', 'present'))
2304 select_present = selection_present
2305 def selection_range(self, start, end):
2306 """Set the selection from START to END (not included)."""
2307 self.tk.call(self._w, 'selection', 'range', start, end)
2308 select_range = selection_range
2309 def selection_to(self, index):
2310 """Set the variable end of a selection to INDEX."""
2311 self.tk.call(self._w, 'selection', 'to', index)
2312 select_to = selection_to
2313 def xview(self, index):
2314 """Query and change horizontal position of the view."""
2315 self.tk.call(self._w, 'xview', index)
2316 def xview_moveto(self, fraction):
2317 """Adjust the view in the window so that FRACTION of the
2318 total width of the entry is off-screen to the left."""
2319 self.tk.call(self._w, 'xview', 'moveto', fraction)
2320 def xview_scroll(self, number, what):
2321 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2322 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002323
2324class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002325 """Frame widget which may contain other widgets and can have a 3D border."""
2326 def __init__(self, master=None, cnf={}, **kw):
2327 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002328
Fredrik Lundh06d28152000-08-09 18:03:12 +00002329 Valid resource names: background, bd, bg, borderwidth, class,
2330 colormap, container, cursor, height, highlightbackground,
2331 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2332 cnf = _cnfmerge((cnf, kw))
2333 extra = ()
2334 if cnf.has_key('class_'):
2335 extra = ('-class', cnf['class_'])
2336 del cnf['class_']
2337 elif cnf.has_key('class'):
2338 extra = ('-class', cnf['class'])
2339 del cnf['class']
2340 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002341
2342class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002343 """Label widget which can display text and bitmaps."""
2344 def __init__(self, master=None, cnf={}, **kw):
2345 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002346
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002347 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002348
2349 activebackground, activeforeground, anchor,
2350 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002351 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002352 highlightbackground, highlightcolor,
2353 highlightthickness, image, justify,
2354 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002355 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002356
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002357 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002358
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002359 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002360
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002361 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002362 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002363
Guido van Rossum18468821994-06-20 07:49:28 +00002364class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002365 """Listbox widget which can display a list of strings."""
2366 def __init__(self, master=None, cnf={}, **kw):
2367 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002368
Fredrik Lundh06d28152000-08-09 18:03:12 +00002369 Valid resource names: background, bd, bg, borderwidth, cursor,
2370 exportselection, fg, font, foreground, height, highlightbackground,
2371 highlightcolor, highlightthickness, relief, selectbackground,
2372 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2373 width, xscrollcommand, yscrollcommand, listvariable."""
2374 Widget.__init__(self, master, 'listbox', cnf, kw)
2375 def activate(self, index):
2376 """Activate item identified by INDEX."""
2377 self.tk.call(self._w, 'activate', index)
2378 def bbox(self, *args):
2379 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2380 which encloses the item identified by index in ARGS."""
2381 return self._getints(
2382 self.tk.call((self._w, 'bbox') + args)) or None
2383 def curselection(self):
2384 """Return list of indices of currently selected item."""
2385 # XXX Ought to apply self._getints()...
2386 return self.tk.splitlist(self.tk.call(
2387 self._w, 'curselection'))
2388 def delete(self, first, last=None):
2389 """Delete items from FIRST to LAST (not included)."""
2390 self.tk.call(self._w, 'delete', first, last)
2391 def get(self, first, last=None):
2392 """Get list of items from FIRST to LAST (not included)."""
2393 if last:
2394 return self.tk.splitlist(self.tk.call(
2395 self._w, 'get', first, last))
2396 else:
2397 return self.tk.call(self._w, 'get', first)
2398 def index(self, index):
2399 """Return index of item identified with INDEX."""
2400 i = self.tk.call(self._w, 'index', index)
2401 if i == 'none': return None
2402 return getint(i)
2403 def insert(self, index, *elements):
2404 """Insert ELEMENTS at INDEX."""
2405 self.tk.call((self._w, 'insert', index) + elements)
2406 def nearest(self, y):
2407 """Get index of item which is nearest to y coordinate Y."""
2408 return getint(self.tk.call(
2409 self._w, 'nearest', y))
2410 def scan_mark(self, x, y):
2411 """Remember the current X, Y coordinates."""
2412 self.tk.call(self._w, 'scan', 'mark', x, y)
2413 def scan_dragto(self, x, y):
2414 """Adjust the view of the listbox to 10 times the
2415 difference between X and Y and the coordinates given in
2416 scan_mark."""
2417 self.tk.call(self._w, 'scan', 'dragto', x, y)
2418 def see(self, index):
2419 """Scroll such that INDEX is visible."""
2420 self.tk.call(self._w, 'see', index)
2421 def selection_anchor(self, index):
2422 """Set the fixed end oft the selection to INDEX."""
2423 self.tk.call(self._w, 'selection', 'anchor', index)
2424 select_anchor = selection_anchor
2425 def selection_clear(self, first, last=None):
2426 """Clear the selection from FIRST to LAST (not included)."""
2427 self.tk.call(self._w,
2428 'selection', 'clear', first, last)
2429 select_clear = selection_clear
2430 def selection_includes(self, index):
2431 """Return 1 if INDEX is part of the selection."""
2432 return self.tk.getboolean(self.tk.call(
2433 self._w, 'selection', 'includes', index))
2434 select_includes = selection_includes
2435 def selection_set(self, first, last=None):
2436 """Set the selection from FIRST to LAST (not included) without
2437 changing the currently selected elements."""
2438 self.tk.call(self._w, 'selection', 'set', first, last)
2439 select_set = selection_set
2440 def size(self):
2441 """Return the number of elements in the listbox."""
2442 return getint(self.tk.call(self._w, 'size'))
2443 def xview(self, *what):
2444 """Query and change horizontal position of the view."""
2445 if not what:
2446 return self._getdoubles(self.tk.call(self._w, 'xview'))
2447 self.tk.call((self._w, 'xview') + what)
2448 def xview_moveto(self, fraction):
2449 """Adjust the view in the window so that FRACTION of the
2450 total width of the entry is off-screen to the left."""
2451 self.tk.call(self._w, 'xview', 'moveto', fraction)
2452 def xview_scroll(self, number, what):
2453 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2454 self.tk.call(self._w, 'xview', 'scroll', number, what)
2455 def yview(self, *what):
2456 """Query and change vertical position of the view."""
2457 if not what:
2458 return self._getdoubles(self.tk.call(self._w, 'yview'))
2459 self.tk.call((self._w, 'yview') + what)
2460 def yview_moveto(self, fraction):
2461 """Adjust the view in the window so that FRACTION of the
2462 total width of the entry is off-screen to the top."""
2463 self.tk.call(self._w, 'yview', 'moveto', fraction)
2464 def yview_scroll(self, number, what):
2465 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2466 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002467 def itemcget(self, index, option):
2468 """Return the resource value for an ITEM and an OPTION."""
2469 return self.tk.call(
2470 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002471 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002472 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002473
2474 The values for resources are specified as keyword arguments.
2475 To get an overview about the allowed keyword arguments
2476 call the method without arguments.
2477 Valid resource names: background, bg, foreground, fg,
2478 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002479 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002480 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002481
2482class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002483 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2484 def __init__(self, master=None, cnf={}, **kw):
2485 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002486
Fredrik Lundh06d28152000-08-09 18:03:12 +00002487 Valid resource names: activebackground, activeborderwidth,
2488 activeforeground, background, bd, bg, borderwidth, cursor,
2489 disabledforeground, fg, font, foreground, postcommand, relief,
2490 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2491 Widget.__init__(self, master, 'menu', cnf, kw)
2492 def tk_bindForTraversal(self):
2493 pass # obsolete since Tk 4.0
2494 def tk_mbPost(self):
2495 self.tk.call('tk_mbPost', self._w)
2496 def tk_mbUnpost(self):
2497 self.tk.call('tk_mbUnpost')
2498 def tk_traverseToMenu(self, char):
2499 self.tk.call('tk_traverseToMenu', self._w, char)
2500 def tk_traverseWithinMenu(self, char):
2501 self.tk.call('tk_traverseWithinMenu', self._w, char)
2502 def tk_getMenuButtons(self):
2503 return self.tk.call('tk_getMenuButtons', self._w)
2504 def tk_nextMenu(self, count):
2505 self.tk.call('tk_nextMenu', count)
2506 def tk_nextMenuEntry(self, count):
2507 self.tk.call('tk_nextMenuEntry', count)
2508 def tk_invokeMenu(self):
2509 self.tk.call('tk_invokeMenu', self._w)
2510 def tk_firstMenu(self):
2511 self.tk.call('tk_firstMenu', self._w)
2512 def tk_mbButtonDown(self):
2513 self.tk.call('tk_mbButtonDown', self._w)
2514 def tk_popup(self, x, y, entry=""):
2515 """Post the menu at position X,Y with entry ENTRY."""
2516 self.tk.call('tk_popup', self._w, x, y, entry)
2517 def activate(self, index):
2518 """Activate entry at INDEX."""
2519 self.tk.call(self._w, 'activate', index)
2520 def add(self, itemType, cnf={}, **kw):
2521 """Internal function."""
2522 self.tk.call((self._w, 'add', itemType) +
2523 self._options(cnf, kw))
2524 def add_cascade(self, cnf={}, **kw):
2525 """Add hierarchical menu item."""
2526 self.add('cascade', cnf or kw)
2527 def add_checkbutton(self, cnf={}, **kw):
2528 """Add checkbutton menu item."""
2529 self.add('checkbutton', cnf or kw)
2530 def add_command(self, cnf={}, **kw):
2531 """Add command menu item."""
2532 self.add('command', cnf or kw)
2533 def add_radiobutton(self, cnf={}, **kw):
2534 """Addd radio menu item."""
2535 self.add('radiobutton', cnf or kw)
2536 def add_separator(self, cnf={}, **kw):
2537 """Add separator."""
2538 self.add('separator', cnf or kw)
2539 def insert(self, index, itemType, cnf={}, **kw):
2540 """Internal function."""
2541 self.tk.call((self._w, 'insert', index, itemType) +
2542 self._options(cnf, kw))
2543 def insert_cascade(self, index, cnf={}, **kw):
2544 """Add hierarchical menu item at INDEX."""
2545 self.insert(index, 'cascade', cnf or kw)
2546 def insert_checkbutton(self, index, cnf={}, **kw):
2547 """Add checkbutton menu item at INDEX."""
2548 self.insert(index, 'checkbutton', cnf or kw)
2549 def insert_command(self, index, cnf={}, **kw):
2550 """Add command menu item at INDEX."""
2551 self.insert(index, 'command', cnf or kw)
2552 def insert_radiobutton(self, index, cnf={}, **kw):
2553 """Addd radio menu item at INDEX."""
2554 self.insert(index, 'radiobutton', cnf or kw)
2555 def insert_separator(self, index, cnf={}, **kw):
2556 """Add separator at INDEX."""
2557 self.insert(index, 'separator', cnf or kw)
2558 def delete(self, index1, index2=None):
2559 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2560 self.tk.call(self._w, 'delete', index1, index2)
2561 def entrycget(self, index, option):
2562 """Return the resource value of an menu item for OPTION at INDEX."""
2563 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2564 def entryconfigure(self, index, cnf=None, **kw):
2565 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002566 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002567 entryconfig = entryconfigure
2568 def index(self, index):
2569 """Return the index of a menu item identified by INDEX."""
2570 i = self.tk.call(self._w, 'index', index)
2571 if i == 'none': return None
2572 return getint(i)
2573 def invoke(self, index):
2574 """Invoke a menu item identified by INDEX and execute
2575 the associated command."""
2576 return self.tk.call(self._w, 'invoke', index)
2577 def post(self, x, y):
2578 """Display a menu at position X,Y."""
2579 self.tk.call(self._w, 'post', x, y)
2580 def type(self, index):
2581 """Return the type of the menu item at INDEX."""
2582 return self.tk.call(self._w, 'type', index)
2583 def unpost(self):
2584 """Unmap a menu."""
2585 self.tk.call(self._w, 'unpost')
2586 def yposition(self, index):
2587 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2588 return getint(self.tk.call(
2589 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002590
2591class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002592 """Menubutton widget, obsolete since Tk8.0."""
2593 def __init__(self, master=None, cnf={}, **kw):
2594 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002595
2596class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002597 """Message widget to display multiline text. Obsolete since Label does it too."""
2598 def __init__(self, master=None, cnf={}, **kw):
2599 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002600
2601class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002602 """Radiobutton widget which shows only one of several buttons in on-state."""
2603 def __init__(self, master=None, cnf={}, **kw):
2604 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002605
Fredrik Lundh06d28152000-08-09 18:03:12 +00002606 Valid resource names: activebackground, activeforeground, anchor,
2607 background, bd, bg, bitmap, borderwidth, command, cursor,
2608 disabledforeground, fg, font, foreground, height,
2609 highlightbackground, highlightcolor, highlightthickness, image,
2610 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2611 state, takefocus, text, textvariable, underline, value, variable,
2612 width, wraplength."""
2613 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2614 def deselect(self):
2615 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002616
Fredrik Lundh06d28152000-08-09 18:03:12 +00002617 self.tk.call(self._w, 'deselect')
2618 def flash(self):
2619 """Flash the button."""
2620 self.tk.call(self._w, 'flash')
2621 def invoke(self):
2622 """Toggle the button and invoke a command if given as resource."""
2623 return self.tk.call(self._w, 'invoke')
2624 def select(self):
2625 """Put the button in on-state."""
2626 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002627
2628class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002629 """Scale widget which can display a numerical scale."""
2630 def __init__(self, master=None, cnf={}, **kw):
2631 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002632
Fredrik Lundh06d28152000-08-09 18:03:12 +00002633 Valid resource names: activebackground, background, bigincrement, bd,
2634 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2635 highlightbackground, highlightcolor, highlightthickness, label,
2636 length, orient, relief, repeatdelay, repeatinterval, resolution,
2637 showvalue, sliderlength, sliderrelief, state, takefocus,
2638 tickinterval, to, troughcolor, variable, width."""
2639 Widget.__init__(self, master, 'scale', cnf, kw)
2640 def get(self):
2641 """Get the current value as integer or float."""
2642 value = self.tk.call(self._w, 'get')
2643 try:
2644 return getint(value)
2645 except ValueError:
2646 return getdouble(value)
2647 def set(self, value):
2648 """Set the value to VALUE."""
2649 self.tk.call(self._w, 'set', value)
2650 def coords(self, value=None):
2651 """Return a tuple (X,Y) of the point along the centerline of the
2652 trough that corresponds to VALUE or the current value if None is
2653 given."""
2654
2655 return self._getints(self.tk.call(self._w, 'coords', value))
2656 def identify(self, x, y):
2657 """Return where the point X,Y lies. Valid return values are "slider",
2658 "though1" and "though2"."""
2659 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002660
2661class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002662 """Scrollbar widget which displays a slider at a certain position."""
2663 def __init__(self, master=None, cnf={}, **kw):
2664 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002665
Fredrik Lundh06d28152000-08-09 18:03:12 +00002666 Valid resource names: activebackground, activerelief,
2667 background, bd, bg, borderwidth, command, cursor,
2668 elementborderwidth, highlightbackground,
2669 highlightcolor, highlightthickness, jump, orient,
2670 relief, repeatdelay, repeatinterval, takefocus,
2671 troughcolor, width."""
2672 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2673 def activate(self, index):
2674 """Display the element at INDEX with activebackground and activerelief.
2675 INDEX can be "arrow1","slider" or "arrow2"."""
2676 self.tk.call(self._w, 'activate', index)
2677 def delta(self, deltax, deltay):
2678 """Return the fractional change of the scrollbar setting if it
2679 would be moved by DELTAX or DELTAY pixels."""
2680 return getdouble(
2681 self.tk.call(self._w, 'delta', deltax, deltay))
2682 def fraction(self, x, y):
2683 """Return the fractional value which corresponds to a slider
2684 position of X,Y."""
2685 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2686 def identify(self, x, y):
2687 """Return the element under position X,Y as one of
2688 "arrow1","slider","arrow2" or ""."""
2689 return self.tk.call(self._w, 'identify', x, y)
2690 def get(self):
2691 """Return the current fractional values (upper and lower end)
2692 of the slider position."""
2693 return self._getdoubles(self.tk.call(self._w, 'get'))
2694 def set(self, *args):
2695 """Set the fractional values of the slider position (upper and
2696 lower ends as value between 0 and 1)."""
2697 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002698
2699
2700
Guido van Rossum18468821994-06-20 07:49:28 +00002701class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002702 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002703 def __init__(self, master=None, cnf={}, **kw):
2704 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002705
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002706 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002707
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002708 background, borderwidth, cursor,
2709 exportselection, font, foreground,
2710 highlightbackground, highlightcolor,
2711 highlightthickness, insertbackground,
2712 insertborderwidth, insertofftime,
2713 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002714 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002715 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002716 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002717 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002718
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002719 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002720
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002721 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002722 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002723 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002724
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002725 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002726 Widget.__init__(self, master, 'text', cnf, kw)
2727 def bbox(self, *args):
2728 """Return a tuple of (x,y,width,height) which gives the bounding
2729 box of the visible part of the character at the index in ARGS."""
2730 return self._getints(
2731 self.tk.call((self._w, 'bbox') + args)) or None
2732 def tk_textSelectTo(self, index):
2733 self.tk.call('tk_textSelectTo', self._w, index)
2734 def tk_textBackspace(self):
2735 self.tk.call('tk_textBackspace', self._w)
2736 def tk_textIndexCloser(self, a, b, c):
2737 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2738 def tk_textResetAnchor(self, index):
2739 self.tk.call('tk_textResetAnchor', self._w, index)
2740 def compare(self, index1, op, index2):
2741 """Return whether between index INDEX1 and index INDEX2 the
2742 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2743 return self.tk.getboolean(self.tk.call(
2744 self._w, 'compare', index1, op, index2))
2745 def debug(self, boolean=None):
2746 """Turn on the internal consistency checks of the B-Tree inside the text
2747 widget according to BOOLEAN."""
2748 return self.tk.getboolean(self.tk.call(
2749 self._w, 'debug', boolean))
2750 def delete(self, index1, index2=None):
2751 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2752 self.tk.call(self._w, 'delete', index1, index2)
2753 def dlineinfo(self, index):
2754 """Return tuple (x,y,width,height,baseline) giving the bounding box
2755 and baseline position of the visible part of the line containing
2756 the character at INDEX."""
2757 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002758 def dump(self, index1, index2=None, command=None, **kw):
2759 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002760
Guido van Rossum256705b2002-04-23 13:29:43 +00002761 The type of contents returned in filtered based on the keyword
2762 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2763 given and true, then the corresponding items are returned. The result
2764 is a list of triples of the form (key, value, index). If none of the
2765 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002766
Guido van Rossum256705b2002-04-23 13:29:43 +00002767 If the 'command' argument is given, it is called once for each element
2768 of the list of triples, with the values of each triple serving as the
2769 arguments to the function. In this case the list is not returned."""
2770 args = []
2771 func_name = None
2772 result = None
2773 if not command:
2774 # Never call the dump command without the -command flag, since the
2775 # output could involve Tcl quoting and would be a pain to parse
2776 # right. Instead just set the command to build a list of triples
2777 # as if we had done the parsing.
2778 result = []
2779 def append_triple(key, value, index, result=result):
2780 result.append((key, value, index))
2781 command = append_triple
2782 try:
2783 if not isinstance(command, str):
2784 func_name = command = self._register(command)
2785 args += ["-command", command]
2786 for key in kw:
2787 if kw[key]: args.append("-" + key)
2788 args.append(index1)
2789 if index2:
2790 args.append(index2)
2791 self.tk.call(self._w, "dump", *args)
2792 return result
2793 finally:
2794 if func_name:
2795 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002796
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002797 ## new in tk8.4
2798 def edit(self, *args):
2799 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002800
2801 This method controls the undo mechanism and
2802 the modified flag. The exact behavior of the
2803 command depends on the option argument that
2804 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002805 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002806
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002807 edit_modified, edit_redo, edit_reset, edit_separator
2808 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002809
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002810 """
2811 return self._getints(
2812 self.tk.call((self._w, 'edit') + args)) or ()
2813
2814 def edit_modified(self, arg=None):
2815 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002816
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002817 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002818 flag of the widget. The insert, delete, edit undo and
2819 edit redo commands or the user can set or clear the
2820 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002821 modified flag of the widget to arg.
2822 """
2823 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002824
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002825 def edit_redo(self):
2826 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002827
2828 When the undo option is true, reapplies the last
2829 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002830 then. Generates an error when the redo stack is empty.
2831 Does nothing when the undo option is false.
2832 """
2833 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002834
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002835 def edit_reset(self):
2836 """Clears the undo and redo stacks
2837 """
2838 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002839
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002840 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002841 """Inserts a separator (boundary) on the undo stack.
2842
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002843 Does nothing when the undo option is false
2844 """
2845 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002846
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002847 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002848 """Undoes the last edit action
2849
2850 If the undo option is true. An edit action is defined
2851 as all the insert and delete commands that are recorded
2852 on the undo stack in between two separators. Generates
2853 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002854 when the undo option is false
2855 """
2856 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002857
Fredrik Lundh06d28152000-08-09 18:03:12 +00002858 def get(self, index1, index2=None):
2859 """Return the text from INDEX1 to INDEX2 (not included)."""
2860 return self.tk.call(self._w, 'get', index1, index2)
2861 # (Image commands are new in 8.0)
2862 def image_cget(self, index, option):
2863 """Return the value of OPTION of an embedded image at INDEX."""
2864 if option[:1] != "-":
2865 option = "-" + option
2866 if option[-1:] == "_":
2867 option = option[:-1]
2868 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002869 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002870 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002871 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002872 def image_create(self, index, cnf={}, **kw):
2873 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002874 return self.tk.call(
2875 self._w, "image", "create", index,
2876 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002877 def image_names(self):
2878 """Return all names of embedded images in this widget."""
2879 return self.tk.call(self._w, "image", "names")
2880 def index(self, index):
2881 """Return the index in the form line.char for INDEX."""
2882 return self.tk.call(self._w, 'index', index)
2883 def insert(self, index, chars, *args):
2884 """Insert CHARS before the characters at INDEX. An additional
2885 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2886 self.tk.call((self._w, 'insert', index, chars) + args)
2887 def mark_gravity(self, markName, direction=None):
2888 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2889 Return the current value if None is given for DIRECTION."""
2890 return self.tk.call(
2891 (self._w, 'mark', 'gravity', markName, direction))
2892 def mark_names(self):
2893 """Return all mark names."""
2894 return self.tk.splitlist(self.tk.call(
2895 self._w, 'mark', 'names'))
2896 def mark_set(self, markName, index):
2897 """Set mark MARKNAME before the character at INDEX."""
2898 self.tk.call(self._w, 'mark', 'set', markName, index)
2899 def mark_unset(self, *markNames):
2900 """Delete all marks in MARKNAMES."""
2901 self.tk.call((self._w, 'mark', 'unset') + markNames)
2902 def mark_next(self, index):
2903 """Return the name of the next mark after INDEX."""
2904 return self.tk.call(self._w, 'mark', 'next', index) or None
2905 def mark_previous(self, index):
2906 """Return the name of the previous mark before INDEX."""
2907 return self.tk.call(self._w, 'mark', 'previous', index) or None
2908 def scan_mark(self, x, y):
2909 """Remember the current X, Y coordinates."""
2910 self.tk.call(self._w, 'scan', 'mark', x, y)
2911 def scan_dragto(self, x, y):
2912 """Adjust the view of the text to 10 times the
2913 difference between X and Y and the coordinates given in
2914 scan_mark."""
2915 self.tk.call(self._w, 'scan', 'dragto', x, y)
2916 def search(self, pattern, index, stopindex=None,
2917 forwards=None, backwards=None, exact=None,
2918 regexp=None, nocase=None, count=None):
2919 """Search PATTERN beginning from INDEX until STOPINDEX.
2920 Return the index of the first character of a match or an empty string."""
2921 args = [self._w, 'search']
2922 if forwards: args.append('-forwards')
2923 if backwards: args.append('-backwards')
2924 if exact: args.append('-exact')
2925 if regexp: args.append('-regexp')
2926 if nocase: args.append('-nocase')
2927 if count: args.append('-count'); args.append(count)
2928 if pattern[0] == '-': args.append('--')
2929 args.append(pattern)
2930 args.append(index)
2931 if stopindex: args.append(stopindex)
2932 return self.tk.call(tuple(args))
2933 def see(self, index):
2934 """Scroll such that the character at INDEX is visible."""
2935 self.tk.call(self._w, 'see', index)
2936 def tag_add(self, tagName, index1, *args):
2937 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2938 Additional pairs of indices may follow in ARGS."""
2939 self.tk.call(
2940 (self._w, 'tag', 'add', tagName, index1) + args)
2941 def tag_unbind(self, tagName, sequence, funcid=None):
2942 """Unbind for all characters with TAGNAME for event SEQUENCE the
2943 function identified with FUNCID."""
2944 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2945 if funcid:
2946 self.deletecommand(funcid)
2947 def tag_bind(self, tagName, sequence, func, add=None):
2948 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002949
Fredrik Lundh06d28152000-08-09 18:03:12 +00002950 An additional boolean parameter ADD specifies whether FUNC will be
2951 called additionally to the other bound function or whether it will
2952 replace the previous function. See bind for the return value."""
2953 return self._bind((self._w, 'tag', 'bind', tagName),
2954 sequence, func, add)
2955 def tag_cget(self, tagName, option):
2956 """Return the value of OPTION for tag TAGNAME."""
2957 if option[:1] != '-':
2958 option = '-' + option
2959 if option[-1:] == '_':
2960 option = option[:-1]
2961 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002962 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002963 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002964 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002965 tag_config = tag_configure
2966 def tag_delete(self, *tagNames):
2967 """Delete all tags in TAGNAMES."""
2968 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2969 def tag_lower(self, tagName, belowThis=None):
2970 """Change the priority of tag TAGNAME such that it is lower
2971 than the priority of BELOWTHIS."""
2972 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2973 def tag_names(self, index=None):
2974 """Return a list of all tag names."""
2975 return self.tk.splitlist(
2976 self.tk.call(self._w, 'tag', 'names', index))
2977 def tag_nextrange(self, tagName, index1, index2=None):
2978 """Return a list of start and end index for the first sequence of
2979 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2980 The text is searched forward from INDEX1."""
2981 return self.tk.splitlist(self.tk.call(
2982 self._w, 'tag', 'nextrange', tagName, index1, index2))
2983 def tag_prevrange(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 backwards from INDEX1."""
2987 return self.tk.splitlist(self.tk.call(
2988 self._w, 'tag', 'prevrange', tagName, index1, index2))
2989 def tag_raise(self, tagName, aboveThis=None):
2990 """Change the priority of tag TAGNAME such that it is higher
2991 than the priority of ABOVETHIS."""
2992 self.tk.call(
2993 self._w, 'tag', 'raise', tagName, aboveThis)
2994 def tag_ranges(self, tagName):
2995 """Return a list of ranges of text which have tag TAGNAME."""
2996 return self.tk.splitlist(self.tk.call(
2997 self._w, 'tag', 'ranges', tagName))
2998 def tag_remove(self, tagName, index1, index2=None):
2999 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3000 self.tk.call(
3001 self._w, 'tag', 'remove', tagName, index1, index2)
3002 def window_cget(self, index, option):
3003 """Return the value of OPTION of an embedded window at INDEX."""
3004 if option[:1] != '-':
3005 option = '-' + option
3006 if option[-1:] == '_':
3007 option = option[:-1]
3008 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003009 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003010 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003011 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003012 window_config = window_configure
3013 def window_create(self, index, cnf={}, **kw):
3014 """Create a window at INDEX."""
3015 self.tk.call(
3016 (self._w, 'window', 'create', index)
3017 + self._options(cnf, kw))
3018 def window_names(self):
3019 """Return all names of embedded windows in this widget."""
3020 return self.tk.splitlist(
3021 self.tk.call(self._w, 'window', 'names'))
3022 def xview(self, *what):
3023 """Query and change horizontal position of the view."""
3024 if not what:
3025 return self._getdoubles(self.tk.call(self._w, 'xview'))
3026 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003027 def xview_moveto(self, fraction):
3028 """Adjusts the view in the window so that FRACTION of the
3029 total width of the canvas is off-screen to the left."""
3030 self.tk.call(self._w, 'xview', 'moveto', fraction)
3031 def xview_scroll(self, number, what):
3032 """Shift the x-view according to NUMBER which is measured
3033 in "units" or "pages" (WHAT)."""
3034 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003035 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003036 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003037 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003038 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003039 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003040 def yview_moveto(self, fraction):
3041 """Adjusts the view in the window so that FRACTION of the
3042 total height of the canvas is off-screen to the top."""
3043 self.tk.call(self._w, 'yview', 'moveto', fraction)
3044 def yview_scroll(self, number, what):
3045 """Shift the y-view according to NUMBER which is measured
3046 in "units" or "pages" (WHAT)."""
3047 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003048 def yview_pickplace(self, *what):
3049 """Obsolete function, use see."""
3050 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003051
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003052
Guido van Rossum28574b51996-10-21 15:16:51 +00003053class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003054 """Internal class. It wraps the command in the widget OptionMenu."""
3055 def __init__(self, var, value, callback=None):
3056 self.__value = value
3057 self.__var = var
3058 self.__callback = callback
3059 def __call__(self, *args):
3060 self.__var.set(self.__value)
3061 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003062 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003063
3064class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003065 """OptionMenu which allows the user to select a value from a menu."""
3066 def __init__(self, master, variable, value, *values, **kwargs):
3067 """Construct an optionmenu widget with the parent MASTER, with
3068 the resource textvariable set to VARIABLE, the initially selected
3069 value VALUE, the other menu values VALUES and an additional
3070 keyword argument command."""
3071 kw = {"borderwidth": 2, "textvariable": variable,
3072 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3073 "highlightthickness": 2}
3074 Widget.__init__(self, master, "menubutton", kw)
3075 self.widgetName = 'tk_optionMenu'
3076 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3077 self.menuname = menu._w
3078 # 'command' is the only supported keyword
3079 callback = kwargs.get('command')
3080 if kwargs.has_key('command'):
3081 del kwargs['command']
3082 if kwargs:
3083 raise TclError, 'unknown option -'+kwargs.keys()[0]
3084 menu.add_command(label=value,
3085 command=_setit(variable, value, callback))
3086 for v in values:
3087 menu.add_command(label=v,
3088 command=_setit(variable, v, callback))
3089 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003090
Fredrik Lundh06d28152000-08-09 18:03:12 +00003091 def __getitem__(self, name):
3092 if name == 'menu':
3093 return self.__menu
3094 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003095
Fredrik Lundh06d28152000-08-09 18:03:12 +00003096 def destroy(self):
3097 """Destroy this widget and the associated menu."""
3098 Menubutton.destroy(self)
3099 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003100
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003101class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003102 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003103 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003104 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3105 self.name = None
3106 if not master:
3107 master = _default_root
3108 if not master:
3109 raise RuntimeError, 'Too early to create image'
3110 self.tk = master.tk
3111 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003112 Image._last_id += 1
3113 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003114 # The following is needed for systems where id(x)
3115 # can return a negative number, such as Linux/m68k:
3116 if name[0] == '-': name = '_' + name[1:]
3117 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3118 elif kw: cnf = kw
3119 options = ()
3120 for k, v in cnf.items():
3121 if callable(v):
3122 v = self._register(v)
3123 options = options + ('-'+k, v)
3124 self.tk.call(('image', 'create', imgtype, name,) + options)
3125 self.name = name
3126 def __str__(self): return self.name
3127 def __del__(self):
3128 if self.name:
3129 try:
3130 self.tk.call('image', 'delete', self.name)
3131 except TclError:
3132 # May happen if the root was destroyed
3133 pass
3134 def __setitem__(self, key, value):
3135 self.tk.call(self.name, 'configure', '-'+key, value)
3136 def __getitem__(self, key):
3137 return self.tk.call(self.name, 'configure', '-'+key)
3138 def configure(self, **kw):
3139 """Configure the image."""
3140 res = ()
3141 for k, v in _cnfmerge(kw).items():
3142 if v is not None:
3143 if k[-1] == '_': k = k[:-1]
3144 if callable(v):
3145 v = self._register(v)
3146 res = res + ('-'+k, v)
3147 self.tk.call((self.name, 'config') + res)
3148 config = configure
3149 def height(self):
3150 """Return the height of the image."""
3151 return getint(
3152 self.tk.call('image', 'height', self.name))
3153 def type(self):
3154 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3155 return self.tk.call('image', 'type', self.name)
3156 def width(self):
3157 """Return the width of the image."""
3158 return getint(
3159 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003160
3161class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003162 """Widget which can display colored images in GIF, PPM/PGM format."""
3163 def __init__(self, name=None, cnf={}, master=None, **kw):
3164 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003165
Fredrik Lundh06d28152000-08-09 18:03:12 +00003166 Valid resource names: data, format, file, gamma, height, palette,
3167 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003168 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003169 def blank(self):
3170 """Display a transparent image."""
3171 self.tk.call(self.name, 'blank')
3172 def cget(self, option):
3173 """Return the value of OPTION."""
3174 return self.tk.call(self.name, 'cget', '-' + option)
3175 # XXX config
3176 def __getitem__(self, key):
3177 return self.tk.call(self.name, 'cget', '-' + key)
3178 # XXX copy -from, -to, ...?
3179 def copy(self):
3180 """Return a new PhotoImage with the same image as this widget."""
3181 destImage = PhotoImage()
3182 self.tk.call(destImage, 'copy', self.name)
3183 return destImage
3184 def zoom(self,x,y=''):
3185 """Return a new PhotoImage with the same image as this widget
3186 but zoom it with X and Y."""
3187 destImage = PhotoImage()
3188 if y=='': y=x
3189 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3190 return destImage
3191 def subsample(self,x,y=''):
3192 """Return a new PhotoImage based on the same image as this widget
3193 but use only every Xth or Yth pixel."""
3194 destImage = PhotoImage()
3195 if y=='': y=x
3196 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3197 return destImage
3198 def get(self, x, y):
3199 """Return the color (red, green, blue) of the pixel at X,Y."""
3200 return self.tk.call(self.name, 'get', x, y)
3201 def put(self, data, to=None):
3202 """Put row formated colors to image starting from
3203 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3204 args = (self.name, 'put', data)
3205 if to:
3206 if to[0] == '-to':
3207 to = to[1:]
3208 args = args + ('-to',) + tuple(to)
3209 self.tk.call(args)
3210 # XXX read
3211 def write(self, filename, format=None, from_coords=None):
3212 """Write image to file FILENAME in FORMAT starting from
3213 position FROM_COORDS."""
3214 args = (self.name, 'write', filename)
3215 if format:
3216 args = args + ('-format', format)
3217 if from_coords:
3218 args = args + ('-from',) + tuple(from_coords)
3219 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003220
3221class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003222 """Widget which can display a bitmap."""
3223 def __init__(self, name=None, cnf={}, master=None, **kw):
3224 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003225
Fredrik Lundh06d28152000-08-09 18:03:12 +00003226 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003227 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003228
3229def image_names(): return _default_root.tk.call('image', 'names')
3230def image_types(): return _default_root.tk.call('image', 'types')
3231
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003232
3233class Spinbox(Widget):
3234 """spinbox widget."""
3235 def __init__(self, master=None, cnf={}, **kw):
3236 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003237
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003238 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003239
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003240 activebackground, background, borderwidth,
3241 cursor, exportselection, font, foreground,
3242 highlightbackground, highlightcolor,
3243 highlightthickness, insertbackground,
3244 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003245 insertontime, insertwidth, justify, relief,
3246 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003247 selectbackground, selectborderwidth
3248 selectforeground, takefocus, textvariable
3249 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003250
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003251 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003252
3253 buttonbackground, buttoncursor,
3254 buttondownrelief, buttonuprelief,
3255 command, disabledbackground,
3256 disabledforeground, format, from,
3257 invalidcommand, increment,
3258 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003259 validate, validatecommand values,
3260 width, wrap,
3261 """
3262 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003263
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003264 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003265 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3266 rectangle which encloses the character given by index.
3267
3268 The first two elements of the list give the x and y
3269 coordinates of the upper-left corner of the screen
3270 area covered by the character (in pixels relative
3271 to the widget) and the last two elements give the
3272 width and height of the character, in pixels. The
3273 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003274 visible area of the window.
3275 """
3276 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003277
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003278 def delete(self, first, last=None):
3279 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003280
3281 First is the index of the first character to delete,
3282 and last is the index of the character just after
3283 the last one to delete. If last isn't specified it
3284 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003285 deleted. This command returns an empty string.
3286 """
3287 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003288
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003289 def get(self):
3290 """Returns the spinbox's string"""
3291 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003292
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003293 def icursor(self, index):
3294 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003295
3296 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003297 the character given by index. Returns an empty string
3298 """
3299 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003300
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003301 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003302 """Returns the name of the widget at position x, y
3303
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003304 Return value is one of: none, buttondown, buttonup, entry
3305 """
3306 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003307
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003308 def index(self, index):
3309 """Returns the numerical index corresponding to index
3310 """
3311 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003312
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003313 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003314 """Insert string s at index
3315
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003316 Returns an empty string.
3317 """
3318 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003319
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003320 def invoke(self, element):
3321 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003322
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003323 The element could be buttondown or buttonup
3324 triggering the action associated with it.
3325 """
3326 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003327
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003328 def scan(self, *args):
3329 """Internal function."""
3330 return self._getints(
3331 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003332
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003333 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003334 """Records x and the current view in the spinbox window;
3335
3336 used in conjunction with later scan dragto commands.
3337 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003338 press in the widget. It returns an empty string.
3339 """
3340 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003341
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003342 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003343 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003344 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003345
3346 It then adjusts the view left or right by 10 times the
3347 difference in x-coordinates. This command is typically
3348 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003349 produce the effect of dragging the spinbox at high speed
3350 through the window. The return value is an empty string.
3351 """
3352 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003353
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003354 def selection(self, *args):
3355 """Internal function."""
3356 return self._getints(
3357 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003358
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003359 def selection_adjust(self, index):
3360 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003361 given by index,
3362
3363 Then adjust that end of the selection to be at index
3364 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003365 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003366 select to commands. If the selection isn't currently in
3367 the spinbox, then a new selection is created to include
3368 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003369 anchor point, inclusive. Returns an empty string.
3370 """
3371 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003372
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003373 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003374 """Clear the selection
3375
3376 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003377 command has no effect. Returns an empty string.
3378 """
3379 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003380
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003381 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003382 """Sets or gets the currently selected element.
3383
3384 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003385 displayed depressed
3386 """
3387 return self.selection("element", element)
3388
3389###########################################################################
3390
3391class LabelFrame(Widget):
3392 """labelframe widget."""
3393 def __init__(self, master=None, cnf={}, **kw):
3394 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003395
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003396 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003397
3398 borderwidth, cursor, font, foreground,
3399 highlightbackground, highlightcolor,
3400 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003401 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003402
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003403 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003404
3405 background, class, colormap, container,
3406 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003407 visual, width
3408 """
3409 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003410
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003411########################################################################
3412
3413class PanedWindow(Widget):
3414 """panedwindow widget."""
3415 def __init__(self, master=None, cnf={}, **kw):
3416 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003417
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003418 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003419
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003420 background, borderwidth, cursor, height,
3421 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003422
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003423 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003424
3425 handlepad, handlesize, opaqueresize,
3426 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003427 sashwidth, showhandle,
3428 """
3429 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3430
3431 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003432 """Add a child widget to the panedwindow in a new pane.
3433
3434 The child argument is the name of the child widget
3435 followed by pairs of arguments that specify how to
3436 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003437 accepted by the configure subcommand.
3438 """
3439 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003440
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003441 def remove(self, child):
3442 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003443
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003444 All geometry management options for child will be forgotten.
3445 """
3446 self.tk.call(self._w, 'forget', child)
3447 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003448
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003449 def identify(self, x, y):
3450 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003451
3452 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003453 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003454 handle, and a word indicating whether it is over a sash
3455 or a handle, such as {0 sash} or {2 handle}. If the point
3456 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003457 an empty list.
3458 """
3459 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003460
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003461 def proxy(self, *args):
3462 """Internal function."""
3463 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003464 self.tk.call((self._w, 'proxy') + args)) or ()
3465
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003466 def proxy_coord(self):
3467 """Return the x and y pair of the most recent proxy location
3468 """
3469 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003470
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003471 def proxy_forget(self):
3472 """Remove the proxy from the display.
3473 """
3474 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003475
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003476 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003477 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003478 """
3479 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003480
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003481 def sash(self, *args):
3482 """Internal function."""
3483 return self._getints(
3484 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003485
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003486 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003487 """Return the current x and y pair for the sash given by index.
3488
3489 Index must be an integer between 0 and 1 less than the
3490 number of panes in the panedwindow. The coordinates given are
3491 those of the top left corner of the region containing the sash.
3492 pathName sash dragto index x y This command computes the
3493 difference between the given coordinates and the coordinates
3494 given to the last sash coord command for the given sash. It then
3495 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003496 empty string.
3497 """
3498 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003499
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003500 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003501 """Records x and y for the sash given by index;
3502
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003503 Used in conjunction with later dragto commands to move the sash.
3504 """
3505 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003506
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003507 def sash_place(self, index, x, y):
3508 """Place the sash given by index at the given coordinates
3509 """
3510 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003511
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003512 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003513 """Query a management option for window.
3514
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003515 Option may be any value allowed by the paneconfigure subcommand
3516 """
3517 return self.tk.call(
3518 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003519
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003520 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521 """Query or modify the management options for window.
3522
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003523 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003524 of the available options for pathName. If option is
3525 specified with no value, then the command returns a list
3526 describing the one named option (this list will be identical
3527 to the corresponding sublist of the value returned if no
3528 option is specified). If one or more option-value pairs are
3529 specified, then the command modifies the given widget
3530 option(s) to have the given value(s); in this case the
3531 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003532 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003533
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003534 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003535 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003536 should be the name of a window already managed by pathName.
3537 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003538 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003539 should be the name of a window already managed by pathName.
3540 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003541 Specify a height for the window. The height will be the
3542 outer dimension of the window including its border, if
3543 any. If size is an empty string, or if -height is not
3544 specified, then the height requested internally by the
3545 window will be used initially; the height may later be
3546 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003547 Size may be any value accepted by Tk_GetPixels.
3548 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003549 Specifies that the size of the window cannot be made
3550 less than n. This constraint only affects the size of
3551 the widget in the paned dimension -- the x dimension
3552 for horizontal panedwindows, the y dimension for
3553 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003554 Tk_GetPixels.
3555 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003556 Specifies a non-negative value indicating how much
3557 extra space to leave on each side of the window in
3558 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003559 accepted by Tk_GetPixels.
3560 pady n
3561 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003562 extra space to leave on each side of the window in
3563 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003564 accepted by Tk_GetPixels.
3565 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003566 If a window's pane is larger than the requested
3567 dimensions of the window, this option may be used
3568 to position (or stretch) the window within its pane.
3569 Style is a string that contains zero or more of the
3570 characters n, s, e or w. The string can optionally
3571 contains spaces or commas, but they are ignored. Each
3572 letter refers to a side (north, south, east, or west)
3573 that the window will "stick" to. If both n and s
3574 (or e and w) are specified, the window will be
3575 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003576 its cavity.
3577 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003578 Specify a width for the window. The width will be
3579 the outer dimension of the window including its
3580 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003581 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003582 internally by the window will be used initially; the
3583 width may later be adjusted by the movement of sashes
3584 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003585 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003586
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003587 """
3588 if cnf is None and not kw:
3589 cnf = {}
3590 for x in self.tk.split(
3591 self.tk.call(self._w,
3592 'paneconfigure', tagOrId)):
3593 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3594 return cnf
3595 if type(cnf) == StringType and not kw:
3596 x = self.tk.split(self.tk.call(
3597 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3598 return (x[0][1:],) + x[1:]
3599 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3600 self._options(cnf, kw))
3601 paneconfig = paneconfigure
3602
3603 def panes(self):
3604 """Returns an ordered list of the child panes."""
3605 return self.tk.call(self._w, 'panes')
3606
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003607######################################################################
3608# Extensions:
3609
3610class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003611 def __init__(self, master=None, cnf={}, **kw):
3612 Widget.__init__(self, master, 'studbutton', cnf, kw)
3613 self.bind('<Any-Enter>', self.tkButtonEnter)
3614 self.bind('<Any-Leave>', self.tkButtonLeave)
3615 self.bind('<1>', self.tkButtonDown)
3616 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003617
3618class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003619 def __init__(self, master=None, cnf={}, **kw):
3620 Widget.__init__(self, master, 'tributton', cnf, kw)
3621 self.bind('<Any-Enter>', self.tkButtonEnter)
3622 self.bind('<Any-Leave>', self.tkButtonLeave)
3623 self.bind('<1>', self.tkButtonDown)
3624 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3625 self['fg'] = self['bg']
3626 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003627
Guido van Rossumc417ef81996-08-21 23:38:59 +00003628######################################################################
3629# Test:
3630
3631def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003632 root = Tk()
3633 text = "This is Tcl/Tk version %s" % TclVersion
3634 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003635 try:
3636 text = text + unicode("\nThis should be a cedilla: \347",
3637 "iso-8859-1")
3638 except NameError:
3639 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003640 label = Label(root, text=text)
3641 label.pack()
3642 test = Button(root, text="Click me!",
3643 command=lambda root=root: root.test.configure(
3644 text="[%s]" % root.test['text']))
3645 test.pack()
3646 root.test = test
3647 quit = Button(root, text="QUIT", command=root.destroy)
3648 quit.pack()
3649 # The following three commands are needed so the window pops
3650 # up on top on Windows...
3651 root.iconify()
3652 root.update()
3653 root.deiconify()
3654 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003655
3656if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003657 _test()