blob: b5c07cb3c6f13740c9a0fad71c7a9a24ca391cd6 [file] [log] [blame]
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001"""Wrapper functions for Tcl/Tk.
2
3Tkinter provides classes which allow the display, positioning and
4control of widgets. Toplevel widgets are Tk and Toplevel. Other
5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00006Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
7LabelFrame and PanedWindow.
8
9Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
11under Tk.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000012
13Widgets are positioned with one of the geometry managers Place, Pack
14or Grid. These managers can be called with methods place, pack, grid
15available in every Widget.
16
Guido van Rossuma0adb922001-09-01 18:29:55 +000017Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000019
20Example (Hello, World):
21import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25frame.pack(fill=BOTH,expand=1)
26label = Tkinter.Label(frame, text="Hello, World")
27label.pack(fill=X, expand=1)
28button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
29button.pack(side=BOTTOM)
30tk.mainloop()
31"""
Guido van Rossum2dcf5291994-07-06 09:23:20 +000032
Guido van Rossum37dcab11996-05-16 16:00:19 +000033__version__ = "$Revision$"
34
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import sys
36if sys.platform == "win32":
Fredrik Lundh06d28152000-08-09 18:03:12 +000037 import FixTk # Attempt to configure Tcl/Tk without requiring PATH
Guido van Rossumf8d579c1999-01-04 18:06:45 +000038import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000039tkinter = _tkinter # b/w compat for export
40TclError = _tkinter.TclError
Guido van Rossum7e9394a1995-03-17 16:21:33 +000041from types import *
Guido van Rossuma5773dd1995-09-07 19:22:00 +000042from Tkconstants import *
Guido van Rossumf0c891a1998-04-29 21:43:36 +000043try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000044 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000045except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000046 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000047
Eric S. Raymondfc170b12001-02-09 11:51:27 +000048TkVersion = float(_tkinter.TK_VERSION)
49TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000050
Guido van Rossumd6615ab1997-08-05 02:35:01 +000051READABLE = _tkinter.READABLE
52WRITABLE = _tkinter.WRITABLE
53EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000054
55# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
56try: _tkinter.createfilehandler
57except AttributeError: _tkinter.createfilehandler = None
58try: _tkinter.deletefilehandler
59except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000060
61
Guido van Rossum2dcf5291994-07-06 09:23:20 +000062def _flatten(tuple):
Fredrik Lundh06d28152000-08-09 18:03:12 +000063 """Internal function."""
64 res = ()
65 for item in tuple:
66 if type(item) in (TupleType, ListType):
67 res = res + _flatten(item)
68 elif item is not None:
69 res = res + (item,)
70 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000071
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000072try: _flatten = _tkinter._flatten
73except AttributeError: pass
74
Guido van Rossum2dcf5291994-07-06 09:23:20 +000075def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000076 """Internal function."""
77 if type(cnfs) is DictionaryType:
78 return cnfs
79 elif type(cnfs) in (NoneType, StringType):
80 return cnfs
81 else:
82 cnf = {}
83 for c in _flatten(cnfs):
84 try:
85 cnf.update(c)
86 except (AttributeError, TypeError), msg:
87 print "_cnfmerge: fallback due to:", msg
88 for k, v in c.items():
89 cnf[k] = v
90 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000091
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000092try: _cnfmerge = _tkinter._cnfmerge
93except AttributeError: pass
94
Guido van Rossum2dcf5291994-07-06 09:23:20 +000095class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000096 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000097
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +000099
Fredrik Lundh06d28152000-08-09 18:03:12 +0000100 KeyPress, KeyRelease - for keyboard events
101 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
102 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
103 Colormap, Gravity, Reparent, Property, Destroy, Activate,
104 Deactivate - for window events.
105
106 If a callback function for one of these events is registered
107 using bind, bind_all, bind_class, or tag_bind, the callback is
108 called with an Event as first argument. It will have the
109 following attributes (in braces are the event types for which
110 the attribute is valid):
111
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000112 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000113 num - mouse button pressed (ButtonPress, ButtonRelease)
114 focus - whether the window has the focus (Enter, Leave)
115 height - height of the exposed window (Configure, Expose)
116 width - width of the exposed window (Configure, Expose)
117 keycode - keycode of the pressed key (KeyPress, KeyRelease)
118 state - state of the event as a number (ButtonPress, ButtonRelease,
119 Enter, KeyPress, KeyRelease,
120 Leave, Motion)
121 state - state as a string (Visibility)
122 time - when the event occurred
123 x - x-position of the mouse
124 y - y-position of the mouse
125 x_root - x-position of the mouse on the screen
126 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
127 y_root - y-position of the mouse on the screen
128 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
129 char - pressed character (KeyPress, KeyRelease)
130 send_event - see X/Windows documentation
131 keysym - keysym of the the event as a string (KeyPress, KeyRelease)
132 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
133 type - type of the event as a number
134 widget - widget in which the event occurred
135 delta - delta of wheel movement (MouseWheel)
136 """
137 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000138
Guido van Rossumc4570481998-03-20 20:45:49 +0000139_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000140_default_root = None
141
Guido van Rossumc4570481998-03-20 20:45:49 +0000142def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000143 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000144
Fredrik Lundh06d28152000-08-09 18:03:12 +0000145 Call this function to inhibit that the first instance of
146 Tk is used for windows without an explicit parent window.
147 """
148 global _support_default_root
149 _support_default_root = 0
150 global _default_root
151 _default_root = None
152 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000153
Guido van Rossum45853db1994-06-20 12:19:19 +0000154def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000155 """Internal function."""
156 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000157
Guido van Rossum97aeca11994-07-07 13:12:12 +0000158def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000159 """Internal function. Calling it will throw the exception SystemExit."""
160 raise SystemExit, code
Guido van Rossum97aeca11994-07-07 13:12:12 +0000161
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000162_varnum = 0
163class Variable:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000164 """Internal class. Base class to define value holders for e.g. buttons."""
165 _default = ""
166 def __init__(self, master=None):
167 """Construct a variable with an optional MASTER as master widget.
168 The variable is named PY_VAR_number in Tcl.
169 """
170 global _varnum
171 if not master:
172 master = _default_root
173 self._master = master
174 self._tk = master.tk
175 self._name = 'PY_VAR' + `_varnum`
176 _varnum = _varnum + 1
177 self.set(self._default)
178 def __del__(self):
179 """Unset the variable in Tcl."""
180 self._tk.globalunsetvar(self._name)
181 def __str__(self):
182 """Return the name of the variable in Tcl."""
183 return self._name
184 def set(self, value):
185 """Set the variable to VALUE."""
186 return self._tk.globalsetvar(self._name, value)
187 def trace_variable(self, mode, callback):
188 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000189
Fredrik Lundh06d28152000-08-09 18:03:12 +0000190 MODE is one of "r", "w", "u" for read, write, undefine.
191 CALLBACK must be a function which is called when
192 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000193
Fredrik Lundh06d28152000-08-09 18:03:12 +0000194 Return the name of the callback.
195 """
196 cbname = self._master._register(callback)
197 self._tk.call("trace", "variable", self._name, mode, cbname)
198 return cbname
199 trace = trace_variable
200 def trace_vdelete(self, mode, cbname):
201 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000202
Fredrik Lundh06d28152000-08-09 18:03:12 +0000203 MODE is one of "r", "w", "u" for read, write, undefine.
204 CBNAME is the name of the callback returned from trace_variable or trace.
205 """
206 self._tk.call("trace", "vdelete", self._name, mode, cbname)
207 self._master.deletecommand(cbname)
208 def trace_vinfo(self):
209 """Return all trace callback information."""
210 return map(self._tk.split, self._tk.splitlist(
211 self._tk.call("trace", "vinfo", self._name)))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000212
213class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000214 """Value holder for strings variables."""
215 _default = ""
216 def __init__(self, master=None):
217 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000218
Fredrik Lundh06d28152000-08-09 18:03:12 +0000219 MASTER can be given as master widget."""
220 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000221
Fredrik Lundh06d28152000-08-09 18:03:12 +0000222 def get(self):
223 """Return value of variable as string."""
224 return self._tk.globalgetvar(self._name)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000225
226class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000227 """Value holder for integer variables."""
228 _default = 0
229 def __init__(self, master=None):
230 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000231
Fredrik Lundh06d28152000-08-09 18:03:12 +0000232 MASTER can be given as master widget."""
233 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000234
Fredrik Lundh06d28152000-08-09 18:03:12 +0000235 def get(self):
236 """Return the value of the variable as an integer."""
237 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000238
239class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000240 """Value holder for float variables."""
241 _default = 0.0
242 def __init__(self, master=None):
243 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000244
Fredrik Lundh06d28152000-08-09 18:03:12 +0000245 MASTER can be given as a master widget."""
246 Variable.__init__(self, master)
247
248 def get(self):
249 """Return the value of the variable as a float."""
250 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000251
252class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000253 """Value holder for boolean variables."""
254 _default = "false"
255 def __init__(self, master=None):
256 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000257
Fredrik Lundh06d28152000-08-09 18:03:12 +0000258 MASTER can be given as a master widget."""
259 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000260
Fredrik Lundh06d28152000-08-09 18:03:12 +0000261 def get(self):
262 """Return the value of the variable as 0 or 1."""
263 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000264
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000265def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000266 """Run the main loop of Tcl."""
267 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000268
Guido van Rossum0132f691998-04-30 17:50:36 +0000269getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000270
Guido van Rossum0132f691998-04-30 17:50:36 +0000271getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000272
273def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000274 """Convert true and false to integer values 1 and 0."""
275 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000276
Guido van Rossum368e06b1997-11-07 20:38:49 +0000277# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000278class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000279 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000280
Fredrik Lundh06d28152000-08-09 18:03:12 +0000281 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000282
Fredrik Lundh06d28152000-08-09 18:03:12 +0000283 # XXX font command?
284 _tclCommands = None
285 def destroy(self):
286 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000287
Fredrik Lundh06d28152000-08-09 18:03:12 +0000288 Delete all Tcl commands created for
289 this widget in the Tcl interpreter."""
290 if self._tclCommands is not None:
291 for name in self._tclCommands:
292 #print '- Tkinter: deleted command', name
293 self.tk.deletecommand(name)
294 self._tclCommands = None
295 def deletecommand(self, name):
296 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000297
Fredrik Lundh06d28152000-08-09 18:03:12 +0000298 Delete the Tcl command provided in NAME."""
299 #print '- Tkinter: deleted command', name
300 self.tk.deletecommand(name)
301 try:
302 self._tclCommands.remove(name)
303 except ValueError:
304 pass
305 def tk_strictMotif(self, boolean=None):
306 """Set Tcl internal variable, whether the look and feel
307 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000308
Fredrik Lundh06d28152000-08-09 18:03:12 +0000309 A parameter of 1 means adhere to Motif (e.g. no color
310 change if mouse passes over slider).
311 Returns the set value."""
312 return self.tk.getboolean(self.tk.call(
313 'set', 'tk_strictMotif', boolean))
314 def tk_bisque(self):
315 """Change the color scheme to light brown as used in Tk 3.6 and before."""
316 self.tk.call('tk_bisque')
317 def tk_setPalette(self, *args, **kw):
318 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000319
Fredrik Lundh06d28152000-08-09 18:03:12 +0000320 A single color as argument will cause that all colors of Tk
321 widget elements are derived from this.
322 Alternatively several keyword parameters and its associated
323 colors can be given. The following keywords are valid:
324 activeBackground, foreground, selectColor,
325 activeForeground, highlightBackground, selectBackground,
326 background, highlightColor, selectForeground,
327 disabledForeground, insertBackground, troughColor."""
328 self.tk.call(('tk_setPalette',)
329 + _flatten(args) + _flatten(kw.items()))
330 def tk_menuBar(self, *args):
331 """Do not use. Needed in Tk 3.6 and earlier."""
332 pass # obsolete since Tk 4.0
333 def wait_variable(self, name='PY_VAR'):
334 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000335
Fredrik Lundh06d28152000-08-09 18:03:12 +0000336 A parameter of type IntVar, StringVar, DoubleVar or
337 BooleanVar must be given."""
338 self.tk.call('tkwait', 'variable', name)
339 waitvar = wait_variable # XXX b/w compat
340 def wait_window(self, window=None):
341 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000342
Fredrik Lundh06d28152000-08-09 18:03:12 +0000343 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000344 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000345 window = self
346 self.tk.call('tkwait', 'window', window._w)
347 def wait_visibility(self, window=None):
348 """Wait until the visibility of a WIDGET changes
349 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000350
Fredrik Lundh06d28152000-08-09 18:03:12 +0000351 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000352 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000353 window = self
354 self.tk.call('tkwait', 'visibility', window._w)
355 def setvar(self, name='PY_VAR', value='1'):
356 """Set Tcl variable NAME to VALUE."""
357 self.tk.setvar(name, value)
358 def getvar(self, name='PY_VAR'):
359 """Return value of Tcl variable NAME."""
360 return self.tk.getvar(name)
361 getint = int
362 getdouble = float
363 def getboolean(self, s):
364 """Return 0 or 1 for Tcl boolean values true and false given as parameter."""
365 return self.tk.getboolean(s)
366 def focus_set(self):
367 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000368
Fredrik Lundh06d28152000-08-09 18:03:12 +0000369 If the application currently does not have the focus
370 this widget will get the focus if the application gets
371 the focus through the window manager."""
372 self.tk.call('focus', self._w)
373 focus = focus_set # XXX b/w compat?
374 def focus_force(self):
375 """Direct input focus to this widget even if the
376 application does not have the focus. Use with
377 caution!"""
378 self.tk.call('focus', '-force', self._w)
379 def focus_get(self):
380 """Return the widget which has currently the focus in the
381 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000382
Fredrik Lundh06d28152000-08-09 18:03:12 +0000383 Use focus_displayof to allow working with several
384 displays. Return None if application does not have
385 the focus."""
386 name = self.tk.call('focus')
387 if name == 'none' or not name: return None
388 return self._nametowidget(name)
389 def focus_displayof(self):
390 """Return the widget which has currently the focus on the
391 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000392
Fredrik Lundh06d28152000-08-09 18:03:12 +0000393 Return None if the application does not have the focus."""
394 name = self.tk.call('focus', '-displayof', self._w)
395 if name == 'none' or not name: return None
396 return self._nametowidget(name)
397 def focus_lastfor(self):
398 """Return the widget which would have the focus if top level
399 for this widget gets the focus from the window manager."""
400 name = self.tk.call('focus', '-lastfor', self._w)
401 if name == 'none' or not name: return None
402 return self._nametowidget(name)
403 def tk_focusFollowsMouse(self):
404 """The widget under mouse will get automatically focus. Can not
405 be disabled easily."""
406 self.tk.call('tk_focusFollowsMouse')
407 def tk_focusNext(self):
408 """Return the next widget in the focus order which follows
409 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000410
Fredrik Lundh06d28152000-08-09 18:03:12 +0000411 The focus order first goes to the next child, then to
412 the children of the child recursively and then to the
413 next sibling which is higher in the stacking order. A
414 widget is omitted if it has the takefocus resource set
415 to 0."""
416 name = self.tk.call('tk_focusNext', self._w)
417 if not name: return None
418 return self._nametowidget(name)
419 def tk_focusPrev(self):
420 """Return previous widget in the focus order. See tk_focusNext for details."""
421 name = self.tk.call('tk_focusPrev', self._w)
422 if not name: return None
423 return self._nametowidget(name)
424 def after(self, ms, func=None, *args):
425 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000426
Fredrik Lundh06d28152000-08-09 18:03:12 +0000427 MS specifies the time in milliseconds. FUNC gives the
428 function which shall be called. Additional parameters
429 are given as parameters to the function call. Return
430 identifier to cancel scheduling with after_cancel."""
431 if not func:
432 # I'd rather use time.sleep(ms*0.001)
433 self.tk.call('after', ms)
434 else:
435 # XXX Disgusting hack to clean up after calling func
436 tmp = []
437 def callit(func=func, args=args, self=self, tmp=tmp):
438 try:
439 apply(func, args)
440 finally:
441 try:
442 self.deletecommand(tmp[0])
443 except TclError:
444 pass
445 name = self._register(callit)
446 tmp.append(name)
447 return self.tk.call('after', ms, name)
448 def after_idle(self, func, *args):
449 """Call FUNC once if the Tcl main loop has no event to
450 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000451
Fredrik Lundh06d28152000-08-09 18:03:12 +0000452 Return an identifier to cancel the scheduling with
453 after_cancel."""
454 return apply(self.after, ('idle', func) + args)
455 def after_cancel(self, id):
456 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000457
Fredrik Lundh06d28152000-08-09 18:03:12 +0000458 Identifier returned by after or after_idle must be
459 given as first parameter."""
460 self.tk.call('after', 'cancel', id)
461 def bell(self, displayof=0):
462 """Ring a display's bell."""
463 self.tk.call(('bell',) + self._displayof(displayof))
464 # Clipboard handling:
465 def clipboard_clear(self, **kw):
466 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000467
Fredrik Lundh06d28152000-08-09 18:03:12 +0000468 A widget specified for the optional displayof keyword
469 argument specifies the target display."""
470 if not kw.has_key('displayof'): kw['displayof'] = self._w
471 self.tk.call(('clipboard', 'clear') + self._options(kw))
472 def clipboard_append(self, string, **kw):
473 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000474
Fredrik Lundh06d28152000-08-09 18:03:12 +0000475 A widget specified at the optional displayof keyword
476 argument specifies the target display. The clipboard
477 can be retrieved with selection_get."""
478 if not kw.has_key('displayof'): kw['displayof'] = self._w
479 self.tk.call(('clipboard', 'append') + self._options(kw)
480 + ('--', string))
481 # XXX grab current w/o window argument
482 def grab_current(self):
483 """Return widget which has currently the grab in this application
484 or None."""
485 name = self.tk.call('grab', 'current', self._w)
486 if not name: return None
487 return self._nametowidget(name)
488 def grab_release(self):
489 """Release grab for this widget if currently set."""
490 self.tk.call('grab', 'release', self._w)
491 def grab_set(self):
492 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000493
Fredrik Lundh06d28152000-08-09 18:03:12 +0000494 A grab directs all events to this and descendant
495 widgets in the application."""
496 self.tk.call('grab', 'set', self._w)
497 def grab_set_global(self):
498 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000499
Fredrik Lundh06d28152000-08-09 18:03:12 +0000500 A global grab directs all events to this and
501 descendant widgets on the display. Use with caution -
502 other applications do not get events anymore."""
503 self.tk.call('grab', 'set', '-global', self._w)
504 def grab_status(self):
505 """Return None, "local" or "global" if this widget has
506 no, a local or a global grab."""
507 status = self.tk.call('grab', 'status', self._w)
508 if status == 'none': status = None
509 return status
510 def lower(self, belowThis=None):
511 """Lower this widget in the stacking order."""
512 self.tk.call('lower', self._w, belowThis)
513 def option_add(self, pattern, value, priority = None):
514 """Set a VALUE (second parameter) for an option
515 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000516
Fredrik Lundh06d28152000-08-09 18:03:12 +0000517 An optional third parameter gives the numeric priority
518 (defaults to 80)."""
519 self.tk.call('option', 'add', pattern, value, priority)
520 def option_clear(self):
521 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000522
Fredrik Lundh06d28152000-08-09 18:03:12 +0000523 It will be reloaded if option_add is called."""
524 self.tk.call('option', 'clear')
525 def option_get(self, name, className):
526 """Return the value for an option NAME for this widget
527 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000528
Fredrik Lundh06d28152000-08-09 18:03:12 +0000529 Values with higher priority override lower values."""
530 return self.tk.call('option', 'get', self._w, name, className)
531 def option_readfile(self, fileName, priority = None):
532 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000533
Fredrik Lundh06d28152000-08-09 18:03:12 +0000534 An optional second parameter gives the numeric
535 priority."""
536 self.tk.call('option', 'readfile', fileName, priority)
537 def selection_clear(self, **kw):
538 """Clear the current X selection."""
539 if not kw.has_key('displayof'): kw['displayof'] = self._w
540 self.tk.call(('selection', 'clear') + self._options(kw))
541 def selection_get(self, **kw):
542 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000543
Fredrik Lundh06d28152000-08-09 18:03:12 +0000544 A keyword parameter selection specifies the name of
545 the selection and defaults to PRIMARY. A keyword
546 parameter displayof specifies a widget on the display
547 to use."""
548 if not kw.has_key('displayof'): kw['displayof'] = self._w
549 return self.tk.call(('selection', 'get') + self._options(kw))
550 def selection_handle(self, command, **kw):
551 """Specify a function COMMAND to call if the X
552 selection owned by this widget is queried by another
553 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000554
Fredrik Lundh06d28152000-08-09 18:03:12 +0000555 This function must return the contents of the
556 selection. The function will be called with the
557 arguments OFFSET and LENGTH which allows the chunking
558 of very long selections. The following keyword
559 parameters can be provided:
560 selection - name of the selection (default PRIMARY),
561 type - type of the selection (e.g. STRING, FILE_NAME)."""
562 name = self._register(command)
563 self.tk.call(('selection', 'handle') + self._options(kw)
564 + (self._w, name))
565 def selection_own(self, **kw):
566 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000567
Fredrik Lundh06d28152000-08-09 18:03:12 +0000568 A keyword parameter selection specifies the name of
569 the selection (default PRIMARY)."""
570 self.tk.call(('selection', 'own') +
571 self._options(kw) + (self._w,))
572 def selection_own_get(self, **kw):
573 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000574
Fredrik Lundh06d28152000-08-09 18:03:12 +0000575 The following keyword parameter can
576 be provided:
577 selection - name of the selection (default PRIMARY),
578 type - type of the selection (e.g. STRING, FILE_NAME)."""
579 if not kw.has_key('displayof'): kw['displayof'] = self._w
580 name = self.tk.call(('selection', 'own') + self._options(kw))
581 if not name: return None
582 return self._nametowidget(name)
583 def send(self, interp, cmd, *args):
584 """Send Tcl command CMD to different interpreter INTERP to be executed."""
585 return self.tk.call(('send', interp, cmd) + args)
586 def lower(self, belowThis=None):
587 """Lower this widget in the stacking order."""
588 self.tk.call('lower', self._w, belowThis)
589 def tkraise(self, aboveThis=None):
590 """Raise this widget in the stacking order."""
591 self.tk.call('raise', self._w, aboveThis)
592 lift = tkraise
593 def colormodel(self, value=None):
594 """Useless. Not implemented in Tk."""
595 return self.tk.call('tk', 'colormodel', self._w, value)
596 def winfo_atom(self, name, displayof=0):
597 """Return integer which represents atom NAME."""
598 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
599 return getint(self.tk.call(args))
600 def winfo_atomname(self, id, displayof=0):
601 """Return name of atom with identifier ID."""
602 args = ('winfo', 'atomname') \
603 + self._displayof(displayof) + (id,)
604 return self.tk.call(args)
605 def winfo_cells(self):
606 """Return number of cells in the colormap for this widget."""
607 return getint(
608 self.tk.call('winfo', 'cells', self._w))
609 def winfo_children(self):
610 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000611 result = []
612 for child in self.tk.splitlist(
613 self.tk.call('winfo', 'children', self._w)):
614 try:
615 # Tcl sometimes returns extra windows, e.g. for
616 # menus; those need to be skipped
617 result.append(self._nametowidget(child))
618 except KeyError:
619 pass
620 return result
621
Fredrik Lundh06d28152000-08-09 18:03:12 +0000622 def winfo_class(self):
623 """Return window class name of this widget."""
624 return self.tk.call('winfo', 'class', self._w)
625 def winfo_colormapfull(self):
626 """Return true if at the last color request the colormap was full."""
627 return self.tk.getboolean(
628 self.tk.call('winfo', 'colormapfull', self._w))
629 def winfo_containing(self, rootX, rootY, displayof=0):
630 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
631 args = ('winfo', 'containing') \
632 + self._displayof(displayof) + (rootX, rootY)
633 name = self.tk.call(args)
634 if not name: return None
635 return self._nametowidget(name)
636 def winfo_depth(self):
637 """Return the number of bits per pixel."""
638 return getint(self.tk.call('winfo', 'depth', self._w))
639 def winfo_exists(self):
640 """Return true if this widget exists."""
641 return getint(
642 self.tk.call('winfo', 'exists', self._w))
643 def winfo_fpixels(self, number):
644 """Return the number of pixels for the given distance NUMBER
645 (e.g. "3c") as float."""
646 return getdouble(self.tk.call(
647 'winfo', 'fpixels', self._w, number))
648 def winfo_geometry(self):
649 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
650 return self.tk.call('winfo', 'geometry', self._w)
651 def winfo_height(self):
652 """Return height of this widget."""
653 return getint(
654 self.tk.call('winfo', 'height', self._w))
655 def winfo_id(self):
656 """Return identifier ID for this widget."""
657 return self.tk.getint(
658 self.tk.call('winfo', 'id', self._w))
659 def winfo_interps(self, displayof=0):
660 """Return the name of all Tcl interpreters for this display."""
661 args = ('winfo', 'interps') + self._displayof(displayof)
662 return self.tk.splitlist(self.tk.call(args))
663 def winfo_ismapped(self):
664 """Return true if this widget is mapped."""
665 return getint(
666 self.tk.call('winfo', 'ismapped', self._w))
667 def winfo_manager(self):
668 """Return the window mananger name for this widget."""
669 return self.tk.call('winfo', 'manager', self._w)
670 def winfo_name(self):
671 """Return the name of this widget."""
672 return self.tk.call('winfo', 'name', self._w)
673 def winfo_parent(self):
674 """Return the name of the parent of this widget."""
675 return self.tk.call('winfo', 'parent', self._w)
676 def winfo_pathname(self, id, displayof=0):
677 """Return the pathname of the widget given by ID."""
678 args = ('winfo', 'pathname') \
679 + self._displayof(displayof) + (id,)
680 return self.tk.call(args)
681 def winfo_pixels(self, number):
682 """Rounded integer value of winfo_fpixels."""
683 return getint(
684 self.tk.call('winfo', 'pixels', self._w, number))
685 def winfo_pointerx(self):
686 """Return the x coordinate of the pointer on the root window."""
687 return getint(
688 self.tk.call('winfo', 'pointerx', self._w))
689 def winfo_pointerxy(self):
690 """Return a tuple of x and y coordinates of the pointer on the root window."""
691 return self._getints(
692 self.tk.call('winfo', 'pointerxy', self._w))
693 def winfo_pointery(self):
694 """Return the y coordinate of the pointer on the root window."""
695 return getint(
696 self.tk.call('winfo', 'pointery', self._w))
697 def winfo_reqheight(self):
698 """Return requested height of this widget."""
699 return getint(
700 self.tk.call('winfo', 'reqheight', self._w))
701 def winfo_reqwidth(self):
702 """Return requested width of this widget."""
703 return getint(
704 self.tk.call('winfo', 'reqwidth', self._w))
705 def winfo_rgb(self, color):
706 """Return tuple of decimal values for red, green, blue for
707 COLOR in this widget."""
708 return self._getints(
709 self.tk.call('winfo', 'rgb', self._w, color))
710 def winfo_rootx(self):
711 """Return x coordinate of upper left corner of this widget on the
712 root window."""
713 return getint(
714 self.tk.call('winfo', 'rootx', self._w))
715 def winfo_rooty(self):
716 """Return y coordinate of upper left corner of this widget on the
717 root window."""
718 return getint(
719 self.tk.call('winfo', 'rooty', self._w))
720 def winfo_screen(self):
721 """Return the screen name of this widget."""
722 return self.tk.call('winfo', 'screen', self._w)
723 def winfo_screencells(self):
724 """Return the number of the cells in the colormap of the screen
725 of this widget."""
726 return getint(
727 self.tk.call('winfo', 'screencells', self._w))
728 def winfo_screendepth(self):
729 """Return the number of bits per pixel of the root window of the
730 screen of this widget."""
731 return getint(
732 self.tk.call('winfo', 'screendepth', self._w))
733 def winfo_screenheight(self):
734 """Return the number of pixels of the height of the screen of this widget
735 in pixel."""
736 return getint(
737 self.tk.call('winfo', 'screenheight', self._w))
738 def winfo_screenmmheight(self):
739 """Return the number of pixels of the height of the screen of
740 this widget in mm."""
741 return getint(
742 self.tk.call('winfo', 'screenmmheight', self._w))
743 def winfo_screenmmwidth(self):
744 """Return the number of pixels of the width of the screen of
745 this widget in mm."""
746 return getint(
747 self.tk.call('winfo', 'screenmmwidth', self._w))
748 def winfo_screenvisual(self):
749 """Return one of the strings directcolor, grayscale, pseudocolor,
750 staticcolor, staticgray, or truecolor for the default
751 colormodel of this screen."""
752 return self.tk.call('winfo', 'screenvisual', self._w)
753 def winfo_screenwidth(self):
754 """Return the number of pixels of the width of the screen of
755 this widget in pixel."""
756 return getint(
757 self.tk.call('winfo', 'screenwidth', self._w))
758 def winfo_server(self):
759 """Return information of the X-Server of the screen of this widget in
760 the form "XmajorRminor vendor vendorVersion"."""
761 return self.tk.call('winfo', 'server', self._w)
762 def winfo_toplevel(self):
763 """Return the toplevel widget of this widget."""
764 return self._nametowidget(self.tk.call(
765 'winfo', 'toplevel', self._w))
766 def winfo_viewable(self):
767 """Return true if the widget and all its higher ancestors are mapped."""
768 return getint(
769 self.tk.call('winfo', 'viewable', self._w))
770 def winfo_visual(self):
771 """Return one of the strings directcolor, grayscale, pseudocolor,
772 staticcolor, staticgray, or truecolor for the
773 colormodel of this widget."""
774 return self.tk.call('winfo', 'visual', self._w)
775 def winfo_visualid(self):
776 """Return the X identifier for the visual for this widget."""
777 return self.tk.call('winfo', 'visualid', self._w)
778 def winfo_visualsavailable(self, includeids=0):
779 """Return a list of all visuals available for the screen
780 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000781
Fredrik Lundh06d28152000-08-09 18:03:12 +0000782 Each item in the list consists of a visual name (see winfo_visual), a
783 depth and if INCLUDEIDS=1 is given also the X identifier."""
784 data = self.tk.split(
785 self.tk.call('winfo', 'visualsavailable', self._w,
786 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000787 if type(data) is StringType:
788 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000789 return map(self.__winfo_parseitem, data)
790 def __winfo_parseitem(self, t):
791 """Internal function."""
792 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
793 def __winfo_getint(self, x):
794 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000795 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000796 def winfo_vrootheight(self):
797 """Return the height of the virtual root window associated with this
798 widget in pixels. If there is no virtual root window return the
799 height of the screen."""
800 return getint(
801 self.tk.call('winfo', 'vrootheight', self._w))
802 def winfo_vrootwidth(self):
803 """Return the width of the virtual root window associated with this
804 widget in pixel. If there is no virtual root window return the
805 width of the screen."""
806 return getint(
807 self.tk.call('winfo', 'vrootwidth', self._w))
808 def winfo_vrootx(self):
809 """Return the x offset of the virtual root relative to the root
810 window of the screen of this widget."""
811 return getint(
812 self.tk.call('winfo', 'vrootx', self._w))
813 def winfo_vrooty(self):
814 """Return the y offset of the virtual root relative to the root
815 window of the screen of this widget."""
816 return getint(
817 self.tk.call('winfo', 'vrooty', self._w))
818 def winfo_width(self):
819 """Return the width of this widget."""
820 return getint(
821 self.tk.call('winfo', 'width', self._w))
822 def winfo_x(self):
823 """Return the x coordinate of the upper left corner of this widget
824 in the parent."""
825 return getint(
826 self.tk.call('winfo', 'x', self._w))
827 def winfo_y(self):
828 """Return the y coordinate of the upper left corner of this widget
829 in the parent."""
830 return getint(
831 self.tk.call('winfo', 'y', self._w))
832 def update(self):
833 """Enter event loop until all pending events have been processed by Tcl."""
834 self.tk.call('update')
835 def update_idletasks(self):
836 """Enter event loop until all idle callbacks have been called. This
837 will update the display of windows but not process events caused by
838 the user."""
839 self.tk.call('update', 'idletasks')
840 def bindtags(self, tagList=None):
841 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000842
Fredrik Lundh06d28152000-08-09 18:03:12 +0000843 With no argument return the list of all bindtags associated with
844 this widget. With a list of strings as argument the bindtags are
845 set to this list. The bindtags determine in which order events are
846 processed (see bind)."""
847 if tagList is None:
848 return self.tk.splitlist(
849 self.tk.call('bindtags', self._w))
850 else:
851 self.tk.call('bindtags', self._w, tagList)
852 def _bind(self, what, sequence, func, add, needcleanup=1):
853 """Internal function."""
854 if type(func) is StringType:
855 self.tk.call(what + (sequence, func))
856 elif func:
857 funcid = self._register(func, self._substitute,
858 needcleanup)
859 cmd = ('%sif {"[%s %s]" == "break"} break\n'
860 %
861 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000862 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000863 self.tk.call(what + (sequence, cmd))
864 return funcid
865 elif sequence:
866 return self.tk.call(what + (sequence,))
867 else:
868 return self.tk.splitlist(self.tk.call(what))
869 def bind(self, sequence=None, func=None, add=None):
870 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000871
Fredrik Lundh06d28152000-08-09 18:03:12 +0000872 SEQUENCE is a string of concatenated event
873 patterns. An event pattern is of the form
874 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
875 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
876 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
877 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
878 Mod1, M1. TYPE is one of Activate, Enter, Map,
879 ButtonPress, Button, Expose, Motion, ButtonRelease
880 FocusIn, MouseWheel, Circulate, FocusOut, Property,
881 Colormap, Gravity Reparent, Configure, KeyPress, Key,
882 Unmap, Deactivate, KeyRelease Visibility, Destroy,
883 Leave and DETAIL is the button number for ButtonPress,
884 ButtonRelease and DETAIL is the Keysym for KeyPress and
885 KeyRelease. Examples are
886 <Control-Button-1> for pressing Control and mouse button 1 or
887 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
888 An event pattern can also be a virtual event of the form
889 <<AString>> where AString can be arbitrary. This
890 event can be generated by event_generate.
891 If events are concatenated they must appear shortly
892 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000893
Fredrik Lundh06d28152000-08-09 18:03:12 +0000894 FUNC will be called if the event sequence occurs with an
895 instance of Event as argument. If the return value of FUNC is
896 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000897
Fredrik Lundh06d28152000-08-09 18:03:12 +0000898 An additional boolean parameter ADD specifies whether FUNC will
899 be called additionally to the other bound function or whether
900 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000901
Fredrik Lundh06d28152000-08-09 18:03:12 +0000902 Bind will return an identifier to allow deletion of the bound function with
903 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000904
Fredrik Lundh06d28152000-08-09 18:03:12 +0000905 If FUNC or SEQUENCE is omitted the bound function or list
906 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000907
Fredrik Lundh06d28152000-08-09 18:03:12 +0000908 return self._bind(('bind', self._w), sequence, func, add)
909 def unbind(self, sequence, funcid=None):
910 """Unbind for this widget for event SEQUENCE the
911 function identified with FUNCID."""
912 self.tk.call('bind', self._w, sequence, '')
913 if funcid:
914 self.deletecommand(funcid)
915 def bind_all(self, sequence=None, func=None, add=None):
916 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
917 An additional boolean parameter ADD specifies whether FUNC will
918 be called additionally to the other bound function or whether
919 it will replace the previous function. See bind for the return value."""
920 return self._bind(('bind', 'all'), sequence, func, add, 0)
921 def unbind_all(self, sequence):
922 """Unbind for all widgets for event SEQUENCE all functions."""
923 self.tk.call('bind', 'all' , sequence, '')
924 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000925
Fredrik Lundh06d28152000-08-09 18:03:12 +0000926 """Bind to widgets with bindtag CLASSNAME at event
927 SEQUENCE a call of function FUNC. An additional
928 boolean parameter ADD specifies whether FUNC will be
929 called additionally to the other bound function or
930 whether it will replace the previous function. See bind for
931 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000932
Fredrik Lundh06d28152000-08-09 18:03:12 +0000933 return self._bind(('bind', className), sequence, func, add, 0)
934 def unbind_class(self, className, sequence):
935 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
936 all functions."""
937 self.tk.call('bind', className , sequence, '')
938 def mainloop(self, n=0):
939 """Call the mainloop of Tk."""
940 self.tk.mainloop(n)
941 def quit(self):
942 """Quit the Tcl interpreter. All widgets will be destroyed."""
943 self.tk.quit()
944 def _getints(self, string):
945 """Internal function."""
946 if string:
947 return tuple(map(getint, self.tk.splitlist(string)))
948 def _getdoubles(self, string):
949 """Internal function."""
950 if string:
951 return tuple(map(getdouble, self.tk.splitlist(string)))
952 def _getboolean(self, string):
953 """Internal function."""
954 if string:
955 return self.tk.getboolean(string)
956 def _displayof(self, displayof):
957 """Internal function."""
958 if displayof:
959 return ('-displayof', displayof)
960 if displayof is None:
961 return ('-displayof', self._w)
962 return ()
963 def _options(self, cnf, kw = None):
964 """Internal function."""
965 if kw:
966 cnf = _cnfmerge((cnf, kw))
967 else:
968 cnf = _cnfmerge(cnf)
969 res = ()
970 for k, v in cnf.items():
971 if v is not None:
972 if k[-1] == '_': k = k[:-1]
973 if callable(v):
974 v = self._register(v)
975 res = res + ('-'+k, v)
976 return res
977 def nametowidget(self, name):
978 """Return the Tkinter instance of a widget identified by
979 its Tcl name NAME."""
980 w = self
981 if name[0] == '.':
982 w = w._root()
983 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000984 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000985 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +0000986 if i >= 0:
987 name, tail = name[:i], name[i+1:]
988 else:
989 tail = ''
990 w = w.children[name]
991 name = tail
992 return w
993 _nametowidget = nametowidget
994 def _register(self, func, subst=None, needcleanup=1):
995 """Return a newly created Tcl function. If this
996 function is called, the Python function FUNC will
997 be executed. An optional function SUBST can
998 be given which will be executed before FUNC."""
999 f = CallWrapper(func, subst, self).__call__
1000 name = `id(f)`
1001 try:
1002 func = func.im_func
1003 except AttributeError:
1004 pass
1005 try:
1006 name = name + func.__name__
1007 except AttributeError:
1008 pass
1009 self.tk.createcommand(name, f)
1010 if needcleanup:
1011 if self._tclCommands is None:
1012 self._tclCommands = []
1013 self._tclCommands.append(name)
1014 #print '+ Tkinter created command', name
1015 return name
1016 register = _register
1017 def _root(self):
1018 """Internal function."""
1019 w = self
1020 while w.master: w = w.master
1021 return w
1022 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1023 '%s', '%t', '%w', '%x', '%y',
1024 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001025 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001026 def _substitute(self, *args):
1027 """Internal function."""
1028 if len(args) != len(self._subst_format): return args
1029 getboolean = self.tk.getboolean
1030 getint = int
1031 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1032 # Missing: (a, c, d, m, o, v, B, R)
1033 e = Event()
1034 e.serial = getint(nsign)
1035 e.num = getint(b)
1036 try: e.focus = getboolean(f)
1037 except TclError: pass
1038 e.height = getint(h)
1039 e.keycode = getint(k)
1040 # For Visibility events, event state is a string and
1041 # not an integer:
1042 try:
1043 e.state = getint(s)
1044 except ValueError:
1045 e.state = s
1046 e.time = getint(t)
1047 e.width = getint(w)
1048 e.x = getint(x)
1049 e.y = getint(y)
1050 e.char = A
1051 try: e.send_event = getboolean(E)
1052 except TclError: pass
1053 e.keysym = K
1054 e.keysym_num = getint(N)
1055 e.type = T
1056 try:
1057 e.widget = self._nametowidget(W)
1058 except KeyError:
1059 e.widget = W
1060 e.x_root = getint(X)
1061 e.y_root = getint(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001062 try:
1063 e.delta = getint(D)
1064 except ValueError:
1065 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001066 return (e,)
1067 def _report_exception(self):
1068 """Internal function."""
1069 import sys
1070 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1071 root = self._root()
1072 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001073 def _configure(self, cmd, cnf, kw):
1074 """Internal function."""
1075 if kw:
1076 cnf = _cnfmerge((cnf, kw))
1077 elif cnf:
1078 cnf = _cnfmerge(cnf)
1079 if cnf is None:
1080 cnf = {}
1081 for x in self.tk.split(
1082 self.tk.call(_flatten((self._w, cmd)))):
1083 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1084 return cnf
1085 if type(cnf) is StringType:
1086 x = self.tk.split(
1087 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1088 return (x[0][1:],) + x[1:]
1089 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001090 # These used to be defined in Widget:
1091 def configure(self, cnf=None, **kw):
1092 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001093
Fredrik Lundh06d28152000-08-09 18:03:12 +00001094 The values for resources are specified as keyword
1095 arguments. To get an overview about
1096 the allowed keyword arguments call the method keys.
1097 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001098 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001099 config = configure
1100 def cget(self, key):
1101 """Return the resource value for a KEY given as string."""
1102 return self.tk.call(self._w, 'cget', '-' + key)
1103 __getitem__ = cget
1104 def __setitem__(self, key, value):
1105 self.configure({key: value})
1106 def keys(self):
1107 """Return a list of all resource names of this widget."""
1108 return map(lambda x: x[0][1:],
1109 self.tk.split(self.tk.call(self._w, 'configure')))
1110 def __str__(self):
1111 """Return the window path name of this widget."""
1112 return self._w
1113 # Pack methods that apply to the master
1114 _noarg_ = ['_noarg_']
1115 def pack_propagate(self, flag=_noarg_):
1116 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001117
Fredrik Lundh06d28152000-08-09 18:03:12 +00001118 A boolean argument specifies whether the geometry information
1119 of the slaves will determine the size of this widget. If no argument
1120 is given the current setting will be returned.
1121 """
1122 if flag is Misc._noarg_:
1123 return self._getboolean(self.tk.call(
1124 'pack', 'propagate', self._w))
1125 else:
1126 self.tk.call('pack', 'propagate', self._w, flag)
1127 propagate = pack_propagate
1128 def pack_slaves(self):
1129 """Return a list of all slaves of this widget
1130 in its packing order."""
1131 return map(self._nametowidget,
1132 self.tk.splitlist(
1133 self.tk.call('pack', 'slaves', self._w)))
1134 slaves = pack_slaves
1135 # Place method that applies to the master
1136 def place_slaves(self):
1137 """Return a list of all slaves of this widget
1138 in its packing order."""
1139 return map(self._nametowidget,
1140 self.tk.splitlist(
1141 self.tk.call(
1142 'place', 'slaves', self._w)))
1143 # Grid methods that apply to the master
1144 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1145 """Return a tuple of integer coordinates for the bounding
1146 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001147
Fredrik Lundh06d28152000-08-09 18:03:12 +00001148 If COLUMN, ROW is given the bounding box applies from
1149 the cell with row and column 0 to the specified
1150 cell. If COL2 and ROW2 are given the bounding box
1151 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001152
Fredrik Lundh06d28152000-08-09 18:03:12 +00001153 The returned integers specify the offset of the upper left
1154 corner in the master widget and the width and height.
1155 """
1156 args = ('grid', 'bbox', self._w)
1157 if column is not None and row is not None:
1158 args = args + (column, row)
1159 if col2 is not None and row2 is not None:
1160 args = args + (col2, row2)
1161 return self._getints(apply(self.tk.call, args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001162
Fredrik Lundh06d28152000-08-09 18:03:12 +00001163 bbox = grid_bbox
1164 def _grid_configure(self, command, index, cnf, kw):
1165 """Internal function."""
1166 if type(cnf) is StringType and not kw:
1167 if cnf[-1:] == '_':
1168 cnf = cnf[:-1]
1169 if cnf[:1] != '-':
1170 cnf = '-'+cnf
1171 options = (cnf,)
1172 else:
1173 options = self._options(cnf, kw)
1174 if not options:
1175 res = self.tk.call('grid',
1176 command, self._w, index)
1177 words = self.tk.splitlist(res)
1178 dict = {}
1179 for i in range(0, len(words), 2):
1180 key = words[i][1:]
1181 value = words[i+1]
1182 if not value:
1183 value = None
1184 elif '.' in value:
1185 value = getdouble(value)
1186 else:
1187 value = getint(value)
1188 dict[key] = value
1189 return dict
1190 res = self.tk.call(
1191 ('grid', command, self._w, index)
1192 + options)
1193 if len(options) == 1:
1194 if not res: return None
1195 # In Tk 7.5, -width can be a float
1196 if '.' in res: return getdouble(res)
1197 return getint(res)
1198 def grid_columnconfigure(self, index, cnf={}, **kw):
1199 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001200
Fredrik Lundh06d28152000-08-09 18:03:12 +00001201 Valid resources are minsize (minimum size of the column),
1202 weight (how much does additional space propagate to this column)
1203 and pad (how much space to let additionally)."""
1204 return self._grid_configure('columnconfigure', index, cnf, kw)
1205 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001206 def grid_location(self, x, y):
1207 """Return a tuple of column and row which identify the cell
1208 at which the pixel at position X and Y inside the master
1209 widget is located."""
1210 return self._getints(
1211 self.tk.call(
1212 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001213 def grid_propagate(self, flag=_noarg_):
1214 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001215
Fredrik Lundh06d28152000-08-09 18:03:12 +00001216 A boolean argument specifies whether the geometry information
1217 of the slaves will determine the size of this widget. If no argument
1218 is given, the current setting will be returned.
1219 """
1220 if flag is Misc._noarg_:
1221 return self._getboolean(self.tk.call(
1222 'grid', 'propagate', self._w))
1223 else:
1224 self.tk.call('grid', 'propagate', self._w, flag)
1225 def grid_rowconfigure(self, index, cnf={}, **kw):
1226 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001227
Fredrik Lundh06d28152000-08-09 18:03:12 +00001228 Valid resources are minsize (minimum size of the row),
1229 weight (how much does additional space propagate to this row)
1230 and pad (how much space to let additionally)."""
1231 return self._grid_configure('rowconfigure', index, cnf, kw)
1232 rowconfigure = grid_rowconfigure
1233 def grid_size(self):
1234 """Return a tuple of the number of column and rows in the grid."""
1235 return self._getints(
1236 self.tk.call('grid', 'size', self._w)) or None
1237 size = grid_size
1238 def grid_slaves(self, row=None, column=None):
1239 """Return a list of all slaves of this widget
1240 in its packing order."""
1241 args = ()
1242 if row is not None:
1243 args = args + ('-row', row)
1244 if column is not None:
1245 args = args + ('-column', column)
1246 return map(self._nametowidget,
1247 self.tk.splitlist(self.tk.call(
1248 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001249
Fredrik Lundh06d28152000-08-09 18:03:12 +00001250 # Support for the "event" command, new in Tk 4.2.
1251 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001252
Fredrik Lundh06d28152000-08-09 18:03:12 +00001253 def event_add(self, virtual, *sequences):
1254 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1255 to an event SEQUENCE such that the virtual event is triggered
1256 whenever SEQUENCE occurs."""
1257 args = ('event', 'add', virtual) + sequences
1258 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001259
Fredrik Lundh06d28152000-08-09 18:03:12 +00001260 def event_delete(self, virtual, *sequences):
1261 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1262 args = ('event', 'delete', virtual) + sequences
1263 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001264
Fredrik Lundh06d28152000-08-09 18:03:12 +00001265 def event_generate(self, sequence, **kw):
1266 """Generate an event SEQUENCE. Additional
1267 keyword arguments specify parameter of the event
1268 (e.g. x, y, rootx, rooty)."""
1269 args = ('event', 'generate', self._w, sequence)
1270 for k, v in kw.items():
1271 args = args + ('-%s' % k, str(v))
1272 self.tk.call(args)
1273
1274 def event_info(self, virtual=None):
1275 """Return a list of all virtual events or the information
1276 about the SEQUENCE bound to the virtual event VIRTUAL."""
1277 return self.tk.splitlist(
1278 self.tk.call('event', 'info', virtual))
1279
1280 # Image related commands
1281
1282 def image_names(self):
1283 """Return a list of all existing image names."""
1284 return self.tk.call('image', 'names')
1285
1286 def image_types(self):
1287 """Return a list of all available image types (e.g. phote bitmap)."""
1288 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001289
Guido van Rossum80f8be81997-12-02 19:51:39 +00001290
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001291class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001292 """Internal class. Stores function to call when some user
1293 defined Tcl function is called e.g. after an event occurred."""
1294 def __init__(self, func, subst, widget):
1295 """Store FUNC, SUBST and WIDGET as members."""
1296 self.func = func
1297 self.subst = subst
1298 self.widget = widget
1299 def __call__(self, *args):
1300 """Apply first function SUBST to arguments, than FUNC."""
1301 try:
1302 if self.subst:
1303 args = apply(self.subst, args)
1304 return apply(self.func, args)
1305 except SystemExit, msg:
1306 raise SystemExit, msg
1307 except:
1308 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001309
Guido van Rossume365a591998-05-01 19:48:20 +00001310
Guido van Rossum18468821994-06-20 07:49:28 +00001311class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001312 """Provides functions for the communication with the window manager."""
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001313
Fredrik Lundh06d28152000-08-09 18:03:12 +00001314 def wm_aspect(self,
1315 minNumer=None, minDenom=None,
1316 maxNumer=None, maxDenom=None):
1317 """Instruct the window manager to set the aspect ratio (width/height)
1318 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1319 of the actual values if no argument is given."""
1320 return self._getints(
1321 self.tk.call('wm', 'aspect', self._w,
1322 minNumer, minDenom,
1323 maxNumer, maxDenom))
1324 aspect = wm_aspect
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001325
1326 def wm_attributes(self, *args):
1327 """This subcommand returns or sets platform specific attributes
1328
1329 The first form returns a list of the platform specific flags and
1330 their values. The second form returns the value for the specific
1331 option. The third form sets one or more of the values. The values
1332 are as follows:
1333
1334 On Windows, -disabled gets or sets whether the window is in a
1335 disabled state. -toolwindow gets or sets the style of the window
1336 to toolwindow (as defined in the MSDN). -topmost gets or sets
1337 whether this is a topmost window (displays above all other
1338 windows).
1339
1340 On Macintosh, XXXXX
1341
1342 On Unix, there are currently no special attribute values.
1343 """
1344 args = ('wm', 'attributes', self._w) + args
1345 return self.tk.call(args)
1346 attributes=wm_attributes
1347
Fredrik Lundh06d28152000-08-09 18:03:12 +00001348 def wm_client(self, name=None):
1349 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1350 current value."""
1351 return self.tk.call('wm', 'client', self._w, name)
1352 client = wm_client
1353 def wm_colormapwindows(self, *wlist):
1354 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1355 of this widget. This list contains windows whose colormaps differ from their
1356 parents. Return current list of widgets if WLIST is empty."""
1357 if len(wlist) > 1:
1358 wlist = (wlist,) # Tk needs a list of windows here
1359 args = ('wm', 'colormapwindows', self._w) + wlist
1360 return map(self._nametowidget, self.tk.call(args))
1361 colormapwindows = wm_colormapwindows
1362 def wm_command(self, value=None):
1363 """Store VALUE in WM_COMMAND property. It is the command
1364 which shall be used to invoke the application. Return current
1365 command if VALUE is None."""
1366 return self.tk.call('wm', 'command', self._w, value)
1367 command = wm_command
1368 def wm_deiconify(self):
1369 """Deiconify this widget. If it was never mapped it will not be mapped.
1370 On Windows it will raise this widget and give it the focus."""
1371 return self.tk.call('wm', 'deiconify', self._w)
1372 deiconify = wm_deiconify
1373 def wm_focusmodel(self, model=None):
1374 """Set focus model to MODEL. "active" means that this widget will claim
1375 the focus itself, "passive" means that the window manager shall give
1376 the focus. Return current focus model if MODEL is None."""
1377 return self.tk.call('wm', 'focusmodel', self._w, model)
1378 focusmodel = wm_focusmodel
1379 def wm_frame(self):
1380 """Return identifier for decorative frame of this widget if present."""
1381 return self.tk.call('wm', 'frame', self._w)
1382 frame = wm_frame
1383 def wm_geometry(self, newGeometry=None):
1384 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1385 current value if None is given."""
1386 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1387 geometry = wm_geometry
1388 def wm_grid(self,
1389 baseWidth=None, baseHeight=None,
1390 widthInc=None, heightInc=None):
1391 """Instruct the window manager that this widget shall only be
1392 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1393 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1394 number of grid units requested in Tk_GeometryRequest."""
1395 return self._getints(self.tk.call(
1396 'wm', 'grid', self._w,
1397 baseWidth, baseHeight, widthInc, heightInc))
1398 grid = wm_grid
1399 def wm_group(self, pathName=None):
1400 """Set the group leader widgets for related widgets to PATHNAME. Return
1401 the group leader of this widget if None is given."""
1402 return self.tk.call('wm', 'group', self._w, pathName)
1403 group = wm_group
1404 def wm_iconbitmap(self, bitmap=None):
1405 """Set bitmap for the iconified widget to BITMAP. Return
1406 the bitmap if None is given."""
1407 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1408 iconbitmap = wm_iconbitmap
1409 def wm_iconify(self):
1410 """Display widget as icon."""
1411 return self.tk.call('wm', 'iconify', self._w)
1412 iconify = wm_iconify
1413 def wm_iconmask(self, bitmap=None):
1414 """Set mask for the icon bitmap of this widget. Return the
1415 mask if None is given."""
1416 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1417 iconmask = wm_iconmask
1418 def wm_iconname(self, newName=None):
1419 """Set the name of the icon for this widget. Return the name if
1420 None is given."""
1421 return self.tk.call('wm', 'iconname', self._w, newName)
1422 iconname = wm_iconname
1423 def wm_iconposition(self, x=None, y=None):
1424 """Set the position of the icon of this widget to X and Y. Return
1425 a tuple of the current values of X and X if None is given."""
1426 return self._getints(self.tk.call(
1427 'wm', 'iconposition', self._w, x, y))
1428 iconposition = wm_iconposition
1429 def wm_iconwindow(self, pathName=None):
1430 """Set widget PATHNAME to be displayed instead of icon. Return the current
1431 value if None is given."""
1432 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1433 iconwindow = wm_iconwindow
1434 def wm_maxsize(self, width=None, height=None):
1435 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1436 the values are given in grid units. Return the current values if None
1437 is given."""
1438 return self._getints(self.tk.call(
1439 'wm', 'maxsize', self._w, width, height))
1440 maxsize = wm_maxsize
1441 def wm_minsize(self, width=None, height=None):
1442 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1443 the values are given in grid units. Return the current values if None
1444 is given."""
1445 return self._getints(self.tk.call(
1446 'wm', 'minsize', self._w, width, height))
1447 minsize = wm_minsize
1448 def wm_overrideredirect(self, boolean=None):
1449 """Instruct the window manager to ignore this widget
1450 if BOOLEAN is given with 1. Return the current value if None
1451 is given."""
1452 return self._getboolean(self.tk.call(
1453 'wm', 'overrideredirect', self._w, boolean))
1454 overrideredirect = wm_overrideredirect
1455 def wm_positionfrom(self, who=None):
1456 """Instruct the window manager that the position of this widget shall
1457 be defined by the user if WHO is "user", and by its own policy if WHO is
1458 "program"."""
1459 return self.tk.call('wm', 'positionfrom', self._w, who)
1460 positionfrom = wm_positionfrom
1461 def wm_protocol(self, name=None, func=None):
1462 """Bind function FUNC to command NAME for this widget.
1463 Return the function bound to NAME if None is given. NAME could be
1464 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1465 if callable(func):
1466 command = self._register(func)
1467 else:
1468 command = func
1469 return self.tk.call(
1470 'wm', 'protocol', self._w, name, command)
1471 protocol = wm_protocol
1472 def wm_resizable(self, width=None, height=None):
1473 """Instruct the window manager whether this width can be resized
1474 in WIDTH or HEIGHT. Both values are boolean values."""
1475 return self.tk.call('wm', 'resizable', self._w, width, height)
1476 resizable = wm_resizable
1477 def wm_sizefrom(self, who=None):
1478 """Instruct the window manager that the size of this widget shall
1479 be defined by the user if WHO is "user", and by its own policy if WHO is
1480 "program"."""
1481 return self.tk.call('wm', 'sizefrom', self._w, who)
1482 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001483 def wm_state(self, newstate=None):
1484 """Query or set the state of this widget as one of normal, icon,
1485 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1486 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001487 state = wm_state
1488 def wm_title(self, string=None):
1489 """Set the title of this widget."""
1490 return self.tk.call('wm', 'title', self._w, string)
1491 title = wm_title
1492 def wm_transient(self, master=None):
1493 """Instruct the window manager that this widget is transient
1494 with regard to widget MASTER."""
1495 return self.tk.call('wm', 'transient', self._w, master)
1496 transient = wm_transient
1497 def wm_withdraw(self):
1498 """Withdraw this widget from the screen such that it is unmapped
1499 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1500 return self.tk.call('wm', 'withdraw', self._w)
1501 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001502
Guido van Rossum18468821994-06-20 07:49:28 +00001503
1504class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001505 """Toplevel widget of Tk which represents mostly the main window
1506 of an appliation. It has an associated Tcl interpreter."""
1507 _w = '.'
1508 def __init__(self, screenName=None, baseName=None, className='Tk'):
1509 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1510 be created. BASENAME will be used for the identification of the profile file (see
1511 readprofile).
1512 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1513 is the name of the widget class."""
1514 global _default_root
1515 self.master = None
1516 self.children = {}
1517 if baseName is None:
1518 import sys, os
1519 baseName = os.path.basename(sys.argv[0])
1520 baseName, ext = os.path.splitext(baseName)
1521 if ext not in ('.py', '.pyc', '.pyo'):
1522 baseName = baseName + ext
1523 self.tk = _tkinter.create(screenName, baseName, className)
Jack Jansenbe92af02001-08-23 13:25:59 +00001524 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001525 # Disable event scanning except for Command-Period
1526 _MacOS.SchedParams(1, 0)
1527 # Work around nasty MacTk bug
1528 # XXX Is this one still needed?
1529 self.update()
1530 # Version sanity checks
1531 tk_version = self.tk.getvar('tk_version')
1532 if tk_version != _tkinter.TK_VERSION:
1533 raise RuntimeError, \
1534 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1535 % (_tkinter.TK_VERSION, tk_version)
1536 tcl_version = self.tk.getvar('tcl_version')
1537 if tcl_version != _tkinter.TCL_VERSION:
1538 raise RuntimeError, \
1539 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1540 % (_tkinter.TCL_VERSION, tcl_version)
1541 if TkVersion < 4.0:
1542 raise RuntimeError, \
1543 "Tk 4.0 or higher is required; found Tk %s" \
1544 % str(TkVersion)
1545 self.tk.createcommand('tkerror', _tkerror)
1546 self.tk.createcommand('exit', _exit)
1547 self.readprofile(baseName, className)
1548 if _support_default_root and not _default_root:
1549 _default_root = self
1550 self.protocol("WM_DELETE_WINDOW", self.destroy)
1551 def destroy(self):
1552 """Destroy this and all descendants widgets. This will
1553 end the application of this Tcl interpreter."""
1554 for c in self.children.values(): c.destroy()
1555 self.tk.call('destroy', self._w)
1556 Misc.destroy(self)
1557 global _default_root
1558 if _support_default_root and _default_root is self:
1559 _default_root = None
1560 def readprofile(self, baseName, className):
1561 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1562 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1563 such a file exists in the home directory."""
1564 import os
1565 if os.environ.has_key('HOME'): home = os.environ['HOME']
1566 else: home = os.curdir
1567 class_tcl = os.path.join(home, '.%s.tcl' % className)
1568 class_py = os.path.join(home, '.%s.py' % className)
1569 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1570 base_py = os.path.join(home, '.%s.py' % baseName)
1571 dir = {'self': self}
1572 exec 'from Tkinter import *' in dir
1573 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001574 self.tk.call('source', class_tcl)
1575 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001576 execfile(class_py, dir)
1577 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001578 self.tk.call('source', base_tcl)
1579 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001580 execfile(base_py, dir)
1581 def report_callback_exception(self, exc, val, tb):
1582 """Internal function. It reports exception on sys.stderr."""
1583 import traceback, sys
1584 sys.stderr.write("Exception in Tkinter callback\n")
1585 sys.last_type = exc
1586 sys.last_value = val
1587 sys.last_traceback = tb
1588 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001589
Guido van Rossum368e06b1997-11-07 20:38:49 +00001590# Ideally, the classes Pack, Place and Grid disappear, the
1591# pack/place/grid methods are defined on the Widget class, and
1592# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1593# ...), with pack(), place() and grid() being short for
1594# pack_configure(), place_configure() and grid_columnconfigure(), and
1595# forget() being short for pack_forget(). As a practical matter, I'm
1596# afraid that there is too much code out there that may be using the
1597# Pack, Place or Grid class, so I leave them intact -- but only as
1598# backwards compatibility features. Also note that those methods that
1599# take a master as argument (e.g. pack_propagate) have been moved to
1600# the Misc class (which now incorporates all methods common between
1601# toplevel and interior widgets). Again, for compatibility, these are
1602# copied into the Pack, Place or Grid class.
1603
Guido van Rossum18468821994-06-20 07:49:28 +00001604class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001605 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001606
Fredrik Lundh06d28152000-08-09 18:03:12 +00001607 Base class to use the methods pack_* in every widget."""
1608 def pack_configure(self, cnf={}, **kw):
1609 """Pack a widget in the parent widget. Use as options:
1610 after=widget - pack it after you have packed widget
1611 anchor=NSEW (or subset) - position widget according to
1612 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001613 before=widget - pack it before you will pack widget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001614 expand=1 or 0 - expand widget if parent size grows
1615 fill=NONE or X or Y or BOTH - fill widget if widget grows
1616 in=master - use master to contain this widget
1617 ipadx=amount - add internal padding in x direction
1618 ipady=amount - add internal padding in y direction
1619 padx=amount - add padding in x direction
1620 pady=amount - add padding in y direction
1621 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1622 """
1623 self.tk.call(
1624 ('pack', 'configure', self._w)
1625 + self._options(cnf, kw))
1626 pack = configure = config = pack_configure
1627 def pack_forget(self):
1628 """Unmap this widget and do not use it for the packing order."""
1629 self.tk.call('pack', 'forget', self._w)
1630 forget = pack_forget
1631 def pack_info(self):
1632 """Return information about the packing options
1633 for this widget."""
1634 words = self.tk.splitlist(
1635 self.tk.call('pack', 'info', self._w))
1636 dict = {}
1637 for i in range(0, len(words), 2):
1638 key = words[i][1:]
1639 value = words[i+1]
1640 if value[:1] == '.':
1641 value = self._nametowidget(value)
1642 dict[key] = value
1643 return dict
1644 info = pack_info
1645 propagate = pack_propagate = Misc.pack_propagate
1646 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001647
1648class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001649 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001650
Fredrik Lundh06d28152000-08-09 18:03:12 +00001651 Base class to use the methods place_* in every widget."""
1652 def place_configure(self, cnf={}, **kw):
1653 """Place a widget in the parent widget. Use as options:
1654 in=master - master relative to which the widget is placed.
1655 x=amount - locate anchor of this widget at position x of master
1656 y=amount - locate anchor of this widget at position y of master
1657 relx=amount - locate anchor of this widget between 0.0 and 1.0
1658 relative to width of master (1.0 is right edge)
1659 rely=amount - locate anchor of this widget between 0.0 and 1.0
1660 relative to height of master (1.0 is bottom edge)
1661 anchor=NSEW (or subset) - position anchor according to given direction
1662 width=amount - width of this widget in pixel
1663 height=amount - height of this widget in pixel
1664 relwidth=amount - width of this widget between 0.0 and 1.0
1665 relative to width of master (1.0 is the same width
1666 as the master)
1667 relheight=amount - height of this widget between 0.0 and 1.0
1668 relative to height of master (1.0 is the same
1669 height as the master)
1670 bordermode="inside" or "outside" - whether to take border width of master widget
1671 into account
1672 """
1673 for k in ['in_']:
1674 if kw.has_key(k):
1675 kw[k[:-1]] = kw[k]
1676 del kw[k]
1677 self.tk.call(
1678 ('place', 'configure', self._w)
1679 + self._options(cnf, kw))
1680 place = configure = config = place_configure
1681 def place_forget(self):
1682 """Unmap this widget."""
1683 self.tk.call('place', 'forget', self._w)
1684 forget = place_forget
1685 def place_info(self):
1686 """Return information about the placing options
1687 for this widget."""
1688 words = self.tk.splitlist(
1689 self.tk.call('place', 'info', self._w))
1690 dict = {}
1691 for i in range(0, len(words), 2):
1692 key = words[i][1:]
1693 value = words[i+1]
1694 if value[:1] == '.':
1695 value = self._nametowidget(value)
1696 dict[key] = value
1697 return dict
1698 info = place_info
1699 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001700
Guido van Rossum37dcab11996-05-16 16:00:19 +00001701class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001702 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001703
Fredrik Lundh06d28152000-08-09 18:03:12 +00001704 Base class to use the methods grid_* in every widget."""
1705 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1706 def grid_configure(self, cnf={}, **kw):
1707 """Position a widget in the parent widget in a grid. Use as options:
1708 column=number - use cell identified with given column (starting with 0)
1709 columnspan=number - this widget will span several columns
1710 in=master - use master to contain this widget
1711 ipadx=amount - add internal padding in x direction
1712 ipady=amount - add internal padding in y direction
1713 padx=amount - add padding in x direction
1714 pady=amount - add padding in y direction
1715 row=number - use cell identified with given row (starting with 0)
1716 rowspan=number - this widget will span several rows
1717 sticky=NSEW - if cell is larger on which sides will this
1718 widget stick to the cell boundary
1719 """
1720 self.tk.call(
1721 ('grid', 'configure', self._w)
1722 + self._options(cnf, kw))
1723 grid = configure = config = grid_configure
1724 bbox = grid_bbox = Misc.grid_bbox
1725 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1726 def grid_forget(self):
1727 """Unmap this widget."""
1728 self.tk.call('grid', 'forget', self._w)
1729 forget = grid_forget
1730 def grid_remove(self):
1731 """Unmap this widget but remember the grid options."""
1732 self.tk.call('grid', 'remove', self._w)
1733 def grid_info(self):
1734 """Return information about the options
1735 for positioning this widget in a grid."""
1736 words = self.tk.splitlist(
1737 self.tk.call('grid', 'info', self._w))
1738 dict = {}
1739 for i in range(0, len(words), 2):
1740 key = words[i][1:]
1741 value = words[i+1]
1742 if value[:1] == '.':
1743 value = self._nametowidget(value)
1744 dict[key] = value
1745 return dict
1746 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001747 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001748 propagate = grid_propagate = Misc.grid_propagate
1749 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1750 size = grid_size = Misc.grid_size
1751 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001752
Guido van Rossum368e06b1997-11-07 20:38:49 +00001753class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001754 """Internal class."""
1755 def _setup(self, master, cnf):
1756 """Internal function. Sets up information about children."""
1757 if _support_default_root:
1758 global _default_root
1759 if not master:
1760 if not _default_root:
1761 _default_root = Tk()
1762 master = _default_root
1763 self.master = master
1764 self.tk = master.tk
1765 name = None
1766 if cnf.has_key('name'):
1767 name = cnf['name']
1768 del cnf['name']
1769 if not name:
1770 name = `id(self)`
1771 self._name = name
1772 if master._w=='.':
1773 self._w = '.' + name
1774 else:
1775 self._w = master._w + '.' + name
1776 self.children = {}
1777 if self.master.children.has_key(self._name):
1778 self.master.children[self._name].destroy()
1779 self.master.children[self._name] = self
1780 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1781 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1782 and appropriate options."""
1783 if kw:
1784 cnf = _cnfmerge((cnf, kw))
1785 self.widgetName = widgetName
1786 BaseWidget._setup(self, master, cnf)
1787 classes = []
1788 for k in cnf.keys():
1789 if type(k) is ClassType:
1790 classes.append((k, cnf[k]))
1791 del cnf[k]
1792 self.tk.call(
1793 (widgetName, self._w) + extra + self._options(cnf))
1794 for k, v in classes:
1795 k.configure(self, v)
1796 def destroy(self):
1797 """Destroy this and all descendants widgets."""
1798 for c in self.children.values(): c.destroy()
1799 if self.master.children.has_key(self._name):
1800 del self.master.children[self._name]
1801 self.tk.call('destroy', self._w)
1802 Misc.destroy(self)
1803 def _do(self, name, args=()):
1804 # XXX Obsolete -- better use self.tk.call directly!
1805 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001806
Guido van Rossum368e06b1997-11-07 20:38:49 +00001807class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001808 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001809
Fredrik Lundh06d28152000-08-09 18:03:12 +00001810 Base class for a widget which can be positioned with the geometry managers
1811 Pack, Place or Grid."""
1812 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001813
1814class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001815 """Toplevel widget, e.g. for dialogs."""
1816 def __init__(self, master=None, cnf={}, **kw):
1817 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001818
Fredrik Lundh06d28152000-08-09 18:03:12 +00001819 Valid resource names: background, bd, bg, borderwidth, class,
1820 colormap, container, cursor, height, highlightbackground,
1821 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1822 use, visual, width."""
1823 if kw:
1824 cnf = _cnfmerge((cnf, kw))
1825 extra = ()
1826 for wmkey in ['screen', 'class_', 'class', 'visual',
1827 'colormap']:
1828 if cnf.has_key(wmkey):
1829 val = cnf[wmkey]
1830 # TBD: a hack needed because some keys
1831 # are not valid as keyword arguments
1832 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1833 else: opt = '-'+wmkey
1834 extra = extra + (opt, val)
1835 del cnf[wmkey]
1836 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1837 root = self._root()
1838 self.iconname(root.iconname())
1839 self.title(root.title())
1840 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001841
1842class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001843 """Button widget."""
1844 def __init__(self, master=None, cnf={}, **kw):
1845 """Construct a button widget with the parent MASTER.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001846
1847 STANDARD OPTIONS
1848
1849 activebackground, activeforeground, anchor,
1850 background, bitmap, borderwidth, cursor,
1851 disabledforeground, font, foreground
1852 highlightbackground, highlightcolor,
1853 highlightthickness, image, justify,
1854 padx, pady, relief, repeatdelay,
1855 repeatinterval, takefocus, text,
1856 textvariable, underline, wraplength
1857
1858 WIDGET-SPECIFIC OPTIONS
1859
1860 command, compound, default, height,
1861 overrelief, state, width
1862 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001863 Widget.__init__(self, master, 'button', cnf, kw)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001864
Fredrik Lundh06d28152000-08-09 18:03:12 +00001865 def tkButtonEnter(self, *dummy):
1866 self.tk.call('tkButtonEnter', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001867
Fredrik Lundh06d28152000-08-09 18:03:12 +00001868 def tkButtonLeave(self, *dummy):
1869 self.tk.call('tkButtonLeave', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001870
Fredrik Lundh06d28152000-08-09 18:03:12 +00001871 def tkButtonDown(self, *dummy):
1872 self.tk.call('tkButtonDown', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001873
Fredrik Lundh06d28152000-08-09 18:03:12 +00001874 def tkButtonUp(self, *dummy):
1875 self.tk.call('tkButtonUp', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001876
Fredrik Lundh06d28152000-08-09 18:03:12 +00001877 def tkButtonInvoke(self, *dummy):
1878 self.tk.call('tkButtonInvoke', self._w)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001879
Fredrik Lundh06d28152000-08-09 18:03:12 +00001880 def flash(self):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001881 """Flash the button.
1882
1883 This is accomplished by redisplaying
1884 the button several times, alternating between active and
1885 normal colors. At the end of the flash the button is left
1886 in the same normal/active state as when the command was
1887 invoked. This command is ignored if the button's state is
1888 disabled.
1889 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001890 self.tk.call(self._w, 'flash')
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001891
Fredrik Lundh06d28152000-08-09 18:03:12 +00001892 def invoke(self):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001893 """Invoke the command associated with the button.
1894
1895 The return value is the return value from the command,
1896 or an empty string if there is no command associated with
1897 the button. This command is ignored if the button's state
1898 is disabled.
1899 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001900 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001901
1902# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001903# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001904def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001905 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001906def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001907 s = 'insert'
1908 for a in args:
1909 if a: s = s + (' ' + a)
1910 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001911def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001912 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001913def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001914 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001915def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001916 if y is None:
1917 return '@' + `x`
1918 else:
1919 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001920
1921class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001922 """Canvas widget to display graphical elements like lines or text."""
1923 def __init__(self, master=None, cnf={}, **kw):
1924 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001925
Fredrik Lundh06d28152000-08-09 18:03:12 +00001926 Valid resource names: background, bd, bg, borderwidth, closeenough,
1927 confine, cursor, height, highlightbackground, highlightcolor,
1928 highlightthickness, insertbackground, insertborderwidth,
1929 insertofftime, insertontime, insertwidth, offset, relief,
1930 scrollregion, selectbackground, selectborderwidth, selectforeground,
1931 state, takefocus, width, xscrollcommand, xscrollincrement,
1932 yscrollcommand, yscrollincrement."""
1933 Widget.__init__(self, master, 'canvas', cnf, kw)
1934 def addtag(self, *args):
1935 """Internal function."""
1936 self.tk.call((self._w, 'addtag') + args)
1937 def addtag_above(self, newtag, tagOrId):
1938 """Add tag NEWTAG to all items above TAGORID."""
1939 self.addtag(newtag, 'above', tagOrId)
1940 def addtag_all(self, newtag):
1941 """Add tag NEWTAG to all items."""
1942 self.addtag(newtag, 'all')
1943 def addtag_below(self, newtag, tagOrId):
1944 """Add tag NEWTAG to all items below TAGORID."""
1945 self.addtag(newtag, 'below', tagOrId)
1946 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1947 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1948 If several match take the top-most.
1949 All items closer than HALO are considered overlapping (all are
1950 closests). If START is specified the next below this tag is taken."""
1951 self.addtag(newtag, 'closest', x, y, halo, start)
1952 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1953 """Add tag NEWTAG to all items in the rectangle defined
1954 by X1,Y1,X2,Y2."""
1955 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1956 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1957 """Add tag NEWTAG to all items which overlap the rectangle
1958 defined by X1,Y1,X2,Y2."""
1959 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1960 def addtag_withtag(self, newtag, tagOrId):
1961 """Add tag NEWTAG to all items with TAGORID."""
1962 self.addtag(newtag, 'withtag', tagOrId)
1963 def bbox(self, *args):
1964 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1965 which encloses all items with tags specified as arguments."""
1966 return self._getints(
1967 self.tk.call((self._w, 'bbox') + args)) or None
1968 def tag_unbind(self, tagOrId, sequence, funcid=None):
1969 """Unbind for all items with TAGORID for event SEQUENCE the
1970 function identified with FUNCID."""
1971 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
1972 if funcid:
1973 self.deletecommand(funcid)
1974 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
1975 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001976
Fredrik Lundh06d28152000-08-09 18:03:12 +00001977 An additional boolean parameter ADD specifies whether FUNC will be
1978 called additionally to the other bound function or whether it will
1979 replace the previous function. See bind for the return value."""
1980 return self._bind((self._w, 'bind', tagOrId),
1981 sequence, func, add)
1982 def canvasx(self, screenx, gridspacing=None):
1983 """Return the canvas x coordinate of pixel position SCREENX rounded
1984 to nearest multiple of GRIDSPACING units."""
1985 return getdouble(self.tk.call(
1986 self._w, 'canvasx', screenx, gridspacing))
1987 def canvasy(self, screeny, gridspacing=None):
1988 """Return the canvas y coordinate of pixel position SCREENY rounded
1989 to nearest multiple of GRIDSPACING units."""
1990 return getdouble(self.tk.call(
1991 self._w, 'canvasy', screeny, gridspacing))
1992 def coords(self, *args):
1993 """Return a list of coordinates for the item given in ARGS."""
1994 # XXX Should use _flatten on args
1995 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00001996 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001997 self.tk.call((self._w, 'coords') + args)))
1998 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
1999 """Internal function."""
2000 args = _flatten(args)
2001 cnf = args[-1]
2002 if type(cnf) in (DictionaryType, TupleType):
2003 args = args[:-1]
2004 else:
2005 cnf = {}
2006 return getint(apply(
2007 self.tk.call,
2008 (self._w, 'create', itemType)
2009 + args + self._options(cnf, kw)))
2010 def create_arc(self, *args, **kw):
2011 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2012 return self._create('arc', args, kw)
2013 def create_bitmap(self, *args, **kw):
2014 """Create bitmap with coordinates x1,y1."""
2015 return self._create('bitmap', args, kw)
2016 def create_image(self, *args, **kw):
2017 """Create image item with coordinates x1,y1."""
2018 return self._create('image', args, kw)
2019 def create_line(self, *args, **kw):
2020 """Create line with coordinates x1,y1,...,xn,yn."""
2021 return self._create('line', args, kw)
2022 def create_oval(self, *args, **kw):
2023 """Create oval with coordinates x1,y1,x2,y2."""
2024 return self._create('oval', args, kw)
2025 def create_polygon(self, *args, **kw):
2026 """Create polygon with coordinates x1,y1,...,xn,yn."""
2027 return self._create('polygon', args, kw)
2028 def create_rectangle(self, *args, **kw):
2029 """Create rectangle with coordinates x1,y1,x2,y2."""
2030 return self._create('rectangle', args, kw)
2031 def create_text(self, *args, **kw):
2032 """Create text with coordinates x1,y1."""
2033 return self._create('text', args, kw)
2034 def create_window(self, *args, **kw):
2035 """Create window with coordinates x1,y1,x2,y2."""
2036 return self._create('window', args, kw)
2037 def dchars(self, *args):
2038 """Delete characters of text items identified by tag or id in ARGS (possibly
2039 several times) from FIRST to LAST character (including)."""
2040 self.tk.call((self._w, 'dchars') + args)
2041 def delete(self, *args):
2042 """Delete items identified by all tag or ids contained in ARGS."""
2043 self.tk.call((self._w, 'delete') + args)
2044 def dtag(self, *args):
2045 """Delete tag or id given as last arguments in ARGS from items
2046 identified by first argument in ARGS."""
2047 self.tk.call((self._w, 'dtag') + args)
2048 def find(self, *args):
2049 """Internal function."""
2050 return self._getints(
2051 self.tk.call((self._w, 'find') + args)) or ()
2052 def find_above(self, tagOrId):
2053 """Return items above TAGORID."""
2054 return self.find('above', tagOrId)
2055 def find_all(self):
2056 """Return all items."""
2057 return self.find('all')
2058 def find_below(self, tagOrId):
2059 """Return all items below TAGORID."""
2060 return self.find('below', tagOrId)
2061 def find_closest(self, x, y, halo=None, start=None):
2062 """Return item which is closest to pixel at X, Y.
2063 If several match take the top-most.
2064 All items closer than HALO are considered overlapping (all are
2065 closests). If START is specified the next below this tag is taken."""
2066 return self.find('closest', x, y, halo, start)
2067 def find_enclosed(self, x1, y1, x2, y2):
2068 """Return all items in rectangle defined
2069 by X1,Y1,X2,Y2."""
2070 return self.find('enclosed', x1, y1, x2, y2)
2071 def find_overlapping(self, x1, y1, x2, y2):
2072 """Return all items which overlap the rectangle
2073 defined by X1,Y1,X2,Y2."""
2074 return self.find('overlapping', x1, y1, x2, y2)
2075 def find_withtag(self, tagOrId):
2076 """Return all items with TAGORID."""
2077 return self.find('withtag', tagOrId)
2078 def focus(self, *args):
2079 """Set focus to the first item specified in ARGS."""
2080 return self.tk.call((self._w, 'focus') + args)
2081 def gettags(self, *args):
2082 """Return tags associated with the first item specified in ARGS."""
2083 return self.tk.splitlist(
2084 self.tk.call((self._w, 'gettags') + args))
2085 def icursor(self, *args):
2086 """Set cursor at position POS in the item identified by TAGORID.
2087 In ARGS TAGORID must be first."""
2088 self.tk.call((self._w, 'icursor') + args)
2089 def index(self, *args):
2090 """Return position of cursor as integer in item specified in ARGS."""
2091 return getint(self.tk.call((self._w, 'index') + args))
2092 def insert(self, *args):
2093 """Insert TEXT in item TAGORID at position POS. ARGS must
2094 be TAGORID POS TEXT."""
2095 self.tk.call((self._w, 'insert') + args)
2096 def itemcget(self, tagOrId, option):
2097 """Return the resource value for an OPTION for item TAGORID."""
2098 return self.tk.call(
2099 (self._w, 'itemcget') + (tagOrId, '-'+option))
2100 def itemconfigure(self, tagOrId, cnf=None, **kw):
2101 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002102
Fredrik Lundh06d28152000-08-09 18:03:12 +00002103 The values for resources are specified as keyword
2104 arguments. To get an overview about
2105 the allowed keyword arguments call the method without arguments.
2106 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002107 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002108 itemconfig = itemconfigure
2109 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2110 # so the preferred name for them is tag_lower, tag_raise
2111 # (similar to tag_bind, and similar to the Text widget);
2112 # unfortunately can't delete the old ones yet (maybe in 1.6)
2113 def tag_lower(self, *args):
2114 """Lower an item TAGORID given in ARGS
2115 (optional below another item)."""
2116 self.tk.call((self._w, 'lower') + args)
2117 lower = tag_lower
2118 def move(self, *args):
2119 """Move an item TAGORID given in ARGS."""
2120 self.tk.call((self._w, 'move') + args)
2121 def postscript(self, cnf={}, **kw):
2122 """Print the contents of the canvas to a postscript
2123 file. Valid options: colormap, colormode, file, fontmap,
2124 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2125 rotate, witdh, x, y."""
2126 return self.tk.call((self._w, 'postscript') +
2127 self._options(cnf, kw))
2128 def tag_raise(self, *args):
2129 """Raise an item TAGORID given in ARGS
2130 (optional above another item)."""
2131 self.tk.call((self._w, 'raise') + args)
2132 lift = tkraise = tag_raise
2133 def scale(self, *args):
2134 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2135 self.tk.call((self._w, 'scale') + args)
2136 def scan_mark(self, x, y):
2137 """Remember the current X, Y coordinates."""
2138 self.tk.call(self._w, 'scan', 'mark', x, y)
2139 def scan_dragto(self, x, y):
2140 """Adjust the view of the canvas to 10 times the
2141 difference between X and Y and the coordinates given in
2142 scan_mark."""
2143 self.tk.call(self._w, 'scan', 'dragto', x, y)
2144 def select_adjust(self, tagOrId, index):
2145 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2146 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2147 def select_clear(self):
2148 """Clear the selection if it is in this widget."""
2149 self.tk.call(self._w, 'select', 'clear')
2150 def select_from(self, tagOrId, index):
2151 """Set the fixed end of a selection in item TAGORID to INDEX."""
2152 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2153 def select_item(self):
2154 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002155 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002156 def select_to(self, tagOrId, index):
2157 """Set the variable end of a selection in item TAGORID to INDEX."""
2158 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2159 def type(self, tagOrId):
2160 """Return the type of the item TAGORID."""
2161 return self.tk.call(self._w, 'type', tagOrId) or None
2162 def xview(self, *args):
2163 """Query and change horizontal position of the view."""
2164 if not args:
2165 return self._getdoubles(self.tk.call(self._w, 'xview'))
2166 self.tk.call((self._w, 'xview') + args)
2167 def xview_moveto(self, fraction):
2168 """Adjusts the view in the window so that FRACTION of the
2169 total width of the canvas is off-screen to the left."""
2170 self.tk.call(self._w, 'xview', 'moveto', fraction)
2171 def xview_scroll(self, number, what):
2172 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2173 self.tk.call(self._w, 'xview', 'scroll', number, what)
2174 def yview(self, *args):
2175 """Query and change vertical position of the view."""
2176 if not args:
2177 return self._getdoubles(self.tk.call(self._w, 'yview'))
2178 self.tk.call((self._w, 'yview') + args)
2179 def yview_moveto(self, fraction):
2180 """Adjusts the view in the window so that FRACTION of the
2181 total height of the canvas is off-screen to the top."""
2182 self.tk.call(self._w, 'yview', 'moveto', fraction)
2183 def yview_scroll(self, number, what):
2184 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2185 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002186
2187class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002188 """Checkbutton widget which is either in on- or off-state."""
2189 def __init__(self, master=None, cnf={}, **kw):
2190 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002191
Fredrik Lundh06d28152000-08-09 18:03:12 +00002192 Valid resource names: activebackground, activeforeground, anchor,
2193 background, bd, bg, bitmap, borderwidth, command, cursor,
2194 disabledforeground, fg, font, foreground, height,
2195 highlightbackground, highlightcolor, highlightthickness, image,
2196 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2197 selectcolor, selectimage, state, takefocus, text, textvariable,
2198 underline, variable, width, wraplength."""
2199 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2200 def deselect(self):
2201 """Put the button in off-state."""
2202 self.tk.call(self._w, 'deselect')
2203 def flash(self):
2204 """Flash the button."""
2205 self.tk.call(self._w, 'flash')
2206 def invoke(self):
2207 """Toggle the button and invoke a command if given as resource."""
2208 return self.tk.call(self._w, 'invoke')
2209 def select(self):
2210 """Put the button in on-state."""
2211 self.tk.call(self._w, 'select')
2212 def toggle(self):
2213 """Toggle the button."""
2214 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002215
2216class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002217 """Entry widget which allows to display simple text."""
2218 def __init__(self, master=None, cnf={}, **kw):
2219 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002220
Fredrik Lundh06d28152000-08-09 18:03:12 +00002221 Valid resource names: background, bd, bg, borderwidth, cursor,
2222 exportselection, fg, font, foreground, highlightbackground,
2223 highlightcolor, highlightthickness, insertbackground,
2224 insertborderwidth, insertofftime, insertontime, insertwidth,
2225 invalidcommand, invcmd, justify, relief, selectbackground,
2226 selectborderwidth, selectforeground, show, state, takefocus,
2227 textvariable, validate, validatecommand, vcmd, width,
2228 xscrollcommand."""
2229 Widget.__init__(self, master, 'entry', cnf, kw)
2230 def delete(self, first, last=None):
2231 """Delete text from FIRST to LAST (not included)."""
2232 self.tk.call(self._w, 'delete', first, last)
2233 def get(self):
2234 """Return the text."""
2235 return self.tk.call(self._w, 'get')
2236 def icursor(self, index):
2237 """Insert cursor at INDEX."""
2238 self.tk.call(self._w, 'icursor', index)
2239 def index(self, index):
2240 """Return position of cursor."""
2241 return getint(self.tk.call(
2242 self._w, 'index', index))
2243 def insert(self, index, string):
2244 """Insert STRING at INDEX."""
2245 self.tk.call(self._w, 'insert', index, string)
2246 def scan_mark(self, x):
2247 """Remember the current X, Y coordinates."""
2248 self.tk.call(self._w, 'scan', 'mark', x)
2249 def scan_dragto(self, x):
2250 """Adjust the view of the canvas to 10 times the
2251 difference between X and Y and the coordinates given in
2252 scan_mark."""
2253 self.tk.call(self._w, 'scan', 'dragto', x)
2254 def selection_adjust(self, index):
2255 """Adjust the end of the selection near the cursor to INDEX."""
2256 self.tk.call(self._w, 'selection', 'adjust', index)
2257 select_adjust = selection_adjust
2258 def selection_clear(self):
2259 """Clear the selection if it is in this widget."""
2260 self.tk.call(self._w, 'selection', 'clear')
2261 select_clear = selection_clear
2262 def selection_from(self, index):
2263 """Set the fixed end of a selection to INDEX."""
2264 self.tk.call(self._w, 'selection', 'from', index)
2265 select_from = selection_from
2266 def selection_present(self):
2267 """Return whether the widget has the selection."""
2268 return self.tk.getboolean(
2269 self.tk.call(self._w, 'selection', 'present'))
2270 select_present = selection_present
2271 def selection_range(self, start, end):
2272 """Set the selection from START to END (not included)."""
2273 self.tk.call(self._w, 'selection', 'range', start, end)
2274 select_range = selection_range
2275 def selection_to(self, index):
2276 """Set the variable end of a selection to INDEX."""
2277 self.tk.call(self._w, 'selection', 'to', index)
2278 select_to = selection_to
2279 def xview(self, index):
2280 """Query and change horizontal position of the view."""
2281 self.tk.call(self._w, 'xview', index)
2282 def xview_moveto(self, fraction):
2283 """Adjust the view in the window so that FRACTION of the
2284 total width of the entry is off-screen to the left."""
2285 self.tk.call(self._w, 'xview', 'moveto', fraction)
2286 def xview_scroll(self, number, what):
2287 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2288 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002289
2290class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002291 """Frame widget which may contain other widgets and can have a 3D border."""
2292 def __init__(self, master=None, cnf={}, **kw):
2293 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002294
Fredrik Lundh06d28152000-08-09 18:03:12 +00002295 Valid resource names: background, bd, bg, borderwidth, class,
2296 colormap, container, cursor, height, highlightbackground,
2297 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2298 cnf = _cnfmerge((cnf, kw))
2299 extra = ()
2300 if cnf.has_key('class_'):
2301 extra = ('-class', cnf['class_'])
2302 del cnf['class_']
2303 elif cnf.has_key('class'):
2304 extra = ('-class', cnf['class'])
2305 del cnf['class']
2306 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002307
2308class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002309 """Label widget which can display text and bitmaps."""
2310 def __init__(self, master=None, cnf={}, **kw):
2311 """Construct a label widget with the parent MASTER.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002312
2313 STANDARD OPTIONS
2314
2315 activebackground, activeforeground, anchor,
2316 background, bitmap, borderwidth, cursor,
2317 disabledforeground, font, foreground,
2318 highlightbackground, highlightcolor,
2319 highlightthickness, image, justify,
2320 padx, pady, relief, takefocus, text,
2321 textvariable, underline, wraplength
2322
2323 WIDGET-SPECIFIC OPTIONS
2324
2325 height, state, width
2326
2327 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002328 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002329
Guido van Rossum18468821994-06-20 07:49:28 +00002330class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002331 """Listbox widget which can display a list of strings."""
2332 def __init__(self, master=None, cnf={}, **kw):
2333 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002334
Fredrik Lundh06d28152000-08-09 18:03:12 +00002335 Valid resource names: background, bd, bg, borderwidth, cursor,
2336 exportselection, fg, font, foreground, height, highlightbackground,
2337 highlightcolor, highlightthickness, relief, selectbackground,
2338 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2339 width, xscrollcommand, yscrollcommand, listvariable."""
2340 Widget.__init__(self, master, 'listbox', cnf, kw)
2341 def activate(self, index):
2342 """Activate item identified by INDEX."""
2343 self.tk.call(self._w, 'activate', index)
2344 def bbox(self, *args):
2345 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2346 which encloses the item identified by index in ARGS."""
2347 return self._getints(
2348 self.tk.call((self._w, 'bbox') + args)) or None
2349 def curselection(self):
2350 """Return list of indices of currently selected item."""
2351 # XXX Ought to apply self._getints()...
2352 return self.tk.splitlist(self.tk.call(
2353 self._w, 'curselection'))
2354 def delete(self, first, last=None):
2355 """Delete items from FIRST to LAST (not included)."""
2356 self.tk.call(self._w, 'delete', first, last)
2357 def get(self, first, last=None):
2358 """Get list of items from FIRST to LAST (not included)."""
2359 if last:
2360 return self.tk.splitlist(self.tk.call(
2361 self._w, 'get', first, last))
2362 else:
2363 return self.tk.call(self._w, 'get', first)
2364 def index(self, index):
2365 """Return index of item identified with INDEX."""
2366 i = self.tk.call(self._w, 'index', index)
2367 if i == 'none': return None
2368 return getint(i)
2369 def insert(self, index, *elements):
2370 """Insert ELEMENTS at INDEX."""
2371 self.tk.call((self._w, 'insert', index) + elements)
2372 def nearest(self, y):
2373 """Get index of item which is nearest to y coordinate Y."""
2374 return getint(self.tk.call(
2375 self._w, 'nearest', y))
2376 def scan_mark(self, x, y):
2377 """Remember the current X, Y coordinates."""
2378 self.tk.call(self._w, 'scan', 'mark', x, y)
2379 def scan_dragto(self, x, y):
2380 """Adjust the view of the listbox to 10 times the
2381 difference between X and Y and the coordinates given in
2382 scan_mark."""
2383 self.tk.call(self._w, 'scan', 'dragto', x, y)
2384 def see(self, index):
2385 """Scroll such that INDEX is visible."""
2386 self.tk.call(self._w, 'see', index)
2387 def selection_anchor(self, index):
2388 """Set the fixed end oft the selection to INDEX."""
2389 self.tk.call(self._w, 'selection', 'anchor', index)
2390 select_anchor = selection_anchor
2391 def selection_clear(self, first, last=None):
2392 """Clear the selection from FIRST to LAST (not included)."""
2393 self.tk.call(self._w,
2394 'selection', 'clear', first, last)
2395 select_clear = selection_clear
2396 def selection_includes(self, index):
2397 """Return 1 if INDEX is part of the selection."""
2398 return self.tk.getboolean(self.tk.call(
2399 self._w, 'selection', 'includes', index))
2400 select_includes = selection_includes
2401 def selection_set(self, first, last=None):
2402 """Set the selection from FIRST to LAST (not included) without
2403 changing the currently selected elements."""
2404 self.tk.call(self._w, 'selection', 'set', first, last)
2405 select_set = selection_set
2406 def size(self):
2407 """Return the number of elements in the listbox."""
2408 return getint(self.tk.call(self._w, 'size'))
2409 def xview(self, *what):
2410 """Query and change horizontal position of the view."""
2411 if not what:
2412 return self._getdoubles(self.tk.call(self._w, 'xview'))
2413 self.tk.call((self._w, 'xview') + what)
2414 def xview_moveto(self, fraction):
2415 """Adjust the view in the window so that FRACTION of the
2416 total width of the entry is off-screen to the left."""
2417 self.tk.call(self._w, 'xview', 'moveto', fraction)
2418 def xview_scroll(self, number, what):
2419 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2420 self.tk.call(self._w, 'xview', 'scroll', number, what)
2421 def yview(self, *what):
2422 """Query and change vertical position of the view."""
2423 if not what:
2424 return self._getdoubles(self.tk.call(self._w, 'yview'))
2425 self.tk.call((self._w, 'yview') + what)
2426 def yview_moveto(self, fraction):
2427 """Adjust the view in the window so that FRACTION of the
2428 total width of the entry is off-screen to the top."""
2429 self.tk.call(self._w, 'yview', 'moveto', fraction)
2430 def yview_scroll(self, number, what):
2431 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2432 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002433 def itemcget(self, index, option):
2434 """Return the resource value for an ITEM and an OPTION."""
2435 return self.tk.call(
2436 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002437 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002438 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002439
2440 The values for resources are specified as keyword arguments.
2441 To get an overview about the allowed keyword arguments
2442 call the method without arguments.
2443 Valid resource names: background, bg, foreground, fg,
2444 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002445 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002446 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002447
2448class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002449 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2450 def __init__(self, master=None, cnf={}, **kw):
2451 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002452
Fredrik Lundh06d28152000-08-09 18:03:12 +00002453 Valid resource names: activebackground, activeborderwidth,
2454 activeforeground, background, bd, bg, borderwidth, cursor,
2455 disabledforeground, fg, font, foreground, postcommand, relief,
2456 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2457 Widget.__init__(self, master, 'menu', cnf, kw)
2458 def tk_bindForTraversal(self):
2459 pass # obsolete since Tk 4.0
2460 def tk_mbPost(self):
2461 self.tk.call('tk_mbPost', self._w)
2462 def tk_mbUnpost(self):
2463 self.tk.call('tk_mbUnpost')
2464 def tk_traverseToMenu(self, char):
2465 self.tk.call('tk_traverseToMenu', self._w, char)
2466 def tk_traverseWithinMenu(self, char):
2467 self.tk.call('tk_traverseWithinMenu', self._w, char)
2468 def tk_getMenuButtons(self):
2469 return self.tk.call('tk_getMenuButtons', self._w)
2470 def tk_nextMenu(self, count):
2471 self.tk.call('tk_nextMenu', count)
2472 def tk_nextMenuEntry(self, count):
2473 self.tk.call('tk_nextMenuEntry', count)
2474 def tk_invokeMenu(self):
2475 self.tk.call('tk_invokeMenu', self._w)
2476 def tk_firstMenu(self):
2477 self.tk.call('tk_firstMenu', self._w)
2478 def tk_mbButtonDown(self):
2479 self.tk.call('tk_mbButtonDown', self._w)
2480 def tk_popup(self, x, y, entry=""):
2481 """Post the menu at position X,Y with entry ENTRY."""
2482 self.tk.call('tk_popup', self._w, x, y, entry)
2483 def activate(self, index):
2484 """Activate entry at INDEX."""
2485 self.tk.call(self._w, 'activate', index)
2486 def add(self, itemType, cnf={}, **kw):
2487 """Internal function."""
2488 self.tk.call((self._w, 'add', itemType) +
2489 self._options(cnf, kw))
2490 def add_cascade(self, cnf={}, **kw):
2491 """Add hierarchical menu item."""
2492 self.add('cascade', cnf or kw)
2493 def add_checkbutton(self, cnf={}, **kw):
2494 """Add checkbutton menu item."""
2495 self.add('checkbutton', cnf or kw)
2496 def add_command(self, cnf={}, **kw):
2497 """Add command menu item."""
2498 self.add('command', cnf or kw)
2499 def add_radiobutton(self, cnf={}, **kw):
2500 """Addd radio menu item."""
2501 self.add('radiobutton', cnf or kw)
2502 def add_separator(self, cnf={}, **kw):
2503 """Add separator."""
2504 self.add('separator', cnf or kw)
2505 def insert(self, index, itemType, cnf={}, **kw):
2506 """Internal function."""
2507 self.tk.call((self._w, 'insert', index, itemType) +
2508 self._options(cnf, kw))
2509 def insert_cascade(self, index, cnf={}, **kw):
2510 """Add hierarchical menu item at INDEX."""
2511 self.insert(index, 'cascade', cnf or kw)
2512 def insert_checkbutton(self, index, cnf={}, **kw):
2513 """Add checkbutton menu item at INDEX."""
2514 self.insert(index, 'checkbutton', cnf or kw)
2515 def insert_command(self, index, cnf={}, **kw):
2516 """Add command menu item at INDEX."""
2517 self.insert(index, 'command', cnf or kw)
2518 def insert_radiobutton(self, index, cnf={}, **kw):
2519 """Addd radio menu item at INDEX."""
2520 self.insert(index, 'radiobutton', cnf or kw)
2521 def insert_separator(self, index, cnf={}, **kw):
2522 """Add separator at INDEX."""
2523 self.insert(index, 'separator', cnf or kw)
2524 def delete(self, index1, index2=None):
2525 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2526 self.tk.call(self._w, 'delete', index1, index2)
2527 def entrycget(self, index, option):
2528 """Return the resource value of an menu item for OPTION at INDEX."""
2529 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2530 def entryconfigure(self, index, cnf=None, **kw):
2531 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002532 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002533 entryconfig = entryconfigure
2534 def index(self, index):
2535 """Return the index of a menu item identified by INDEX."""
2536 i = self.tk.call(self._w, 'index', index)
2537 if i == 'none': return None
2538 return getint(i)
2539 def invoke(self, index):
2540 """Invoke a menu item identified by INDEX and execute
2541 the associated command."""
2542 return self.tk.call(self._w, 'invoke', index)
2543 def post(self, x, y):
2544 """Display a menu at position X,Y."""
2545 self.tk.call(self._w, 'post', x, y)
2546 def type(self, index):
2547 """Return the type of the menu item at INDEX."""
2548 return self.tk.call(self._w, 'type', index)
2549 def unpost(self):
2550 """Unmap a menu."""
2551 self.tk.call(self._w, 'unpost')
2552 def yposition(self, index):
2553 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2554 return getint(self.tk.call(
2555 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002556
2557class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002558 """Menubutton widget, obsolete since Tk8.0."""
2559 def __init__(self, master=None, cnf={}, **kw):
2560 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002561
2562class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002563 """Message widget to display multiline text. Obsolete since Label does it too."""
2564 def __init__(self, master=None, cnf={}, **kw):
2565 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002566
2567class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002568 """Radiobutton widget which shows only one of several buttons in on-state."""
2569 def __init__(self, master=None, cnf={}, **kw):
2570 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002571
Fredrik Lundh06d28152000-08-09 18:03:12 +00002572 Valid resource names: activebackground, activeforeground, anchor,
2573 background, bd, bg, bitmap, borderwidth, command, cursor,
2574 disabledforeground, fg, font, foreground, height,
2575 highlightbackground, highlightcolor, highlightthickness, image,
2576 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2577 state, takefocus, text, textvariable, underline, value, variable,
2578 width, wraplength."""
2579 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2580 def deselect(self):
2581 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002582
Fredrik Lundh06d28152000-08-09 18:03:12 +00002583 self.tk.call(self._w, 'deselect')
2584 def flash(self):
2585 """Flash the button."""
2586 self.tk.call(self._w, 'flash')
2587 def invoke(self):
2588 """Toggle the button and invoke a command if given as resource."""
2589 return self.tk.call(self._w, 'invoke')
2590 def select(self):
2591 """Put the button in on-state."""
2592 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002593
2594class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002595 """Scale widget which can display a numerical scale."""
2596 def __init__(self, master=None, cnf={}, **kw):
2597 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002598
Fredrik Lundh06d28152000-08-09 18:03:12 +00002599 Valid resource names: activebackground, background, bigincrement, bd,
2600 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2601 highlightbackground, highlightcolor, highlightthickness, label,
2602 length, orient, relief, repeatdelay, repeatinterval, resolution,
2603 showvalue, sliderlength, sliderrelief, state, takefocus,
2604 tickinterval, to, troughcolor, variable, width."""
2605 Widget.__init__(self, master, 'scale', cnf, kw)
2606 def get(self):
2607 """Get the current value as integer or float."""
2608 value = self.tk.call(self._w, 'get')
2609 try:
2610 return getint(value)
2611 except ValueError:
2612 return getdouble(value)
2613 def set(self, value):
2614 """Set the value to VALUE."""
2615 self.tk.call(self._w, 'set', value)
2616 def coords(self, value=None):
2617 """Return a tuple (X,Y) of the point along the centerline of the
2618 trough that corresponds to VALUE or the current value if None is
2619 given."""
2620
2621 return self._getints(self.tk.call(self._w, 'coords', value))
2622 def identify(self, x, y):
2623 """Return where the point X,Y lies. Valid return values are "slider",
2624 "though1" and "though2"."""
2625 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002626
2627class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002628 """Scrollbar widget which displays a slider at a certain position."""
2629 def __init__(self, master=None, cnf={}, **kw):
2630 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002631
Fredrik Lundh06d28152000-08-09 18:03:12 +00002632 Valid resource names: activebackground, activerelief,
2633 background, bd, bg, borderwidth, command, cursor,
2634 elementborderwidth, highlightbackground,
2635 highlightcolor, highlightthickness, jump, orient,
2636 relief, repeatdelay, repeatinterval, takefocus,
2637 troughcolor, width."""
2638 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2639 def activate(self, index):
2640 """Display the element at INDEX with activebackground and activerelief.
2641 INDEX can be "arrow1","slider" or "arrow2"."""
2642 self.tk.call(self._w, 'activate', index)
2643 def delta(self, deltax, deltay):
2644 """Return the fractional change of the scrollbar setting if it
2645 would be moved by DELTAX or DELTAY pixels."""
2646 return getdouble(
2647 self.tk.call(self._w, 'delta', deltax, deltay))
2648 def fraction(self, x, y):
2649 """Return the fractional value which corresponds to a slider
2650 position of X,Y."""
2651 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2652 def identify(self, x, y):
2653 """Return the element under position X,Y as one of
2654 "arrow1","slider","arrow2" or ""."""
2655 return self.tk.call(self._w, 'identify', x, y)
2656 def get(self):
2657 """Return the current fractional values (upper and lower end)
2658 of the slider position."""
2659 return self._getdoubles(self.tk.call(self._w, 'get'))
2660 def set(self, *args):
2661 """Set the fractional values of the slider position (upper and
2662 lower ends as value between 0 and 1)."""
2663 self.tk.call((self._w, 'set') + args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002664
2665
2666
Guido van Rossum18468821994-06-20 07:49:28 +00002667class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002668 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002669 def __init__(self, master=None, cnf={}, **kw):
2670 """Construct a text widget with the parent MASTER.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002671
2672 STANDARD OPTIONS
2673
2674 background, borderwidth, cursor,
2675 exportselection, font, foreground,
2676 highlightbackground, highlightcolor,
2677 highlightthickness, insertbackground,
2678 insertborderwidth, insertofftime,
2679 insertontime, insertwidth, padx, pady,
2680 relief, selectbackground,
2681 selectborderwidth, selectforeground,
2682 setgrid, takefocus,
2683 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002684
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002685 WIDGET-SPECIFIC OPTIONS
2686
2687 autoseparators, height, maxundo,
2688 spacing1, spacing2, spacing3,
2689 state, tabs, undo, width, wrap,
2690
2691 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002692 Widget.__init__(self, master, 'text', cnf, kw)
2693 def bbox(self, *args):
2694 """Return a tuple of (x,y,width,height) which gives the bounding
2695 box of the visible part of the character at the index in ARGS."""
2696 return self._getints(
2697 self.tk.call((self._w, 'bbox') + args)) or None
2698 def tk_textSelectTo(self, index):
2699 self.tk.call('tk_textSelectTo', self._w, index)
2700 def tk_textBackspace(self):
2701 self.tk.call('tk_textBackspace', self._w)
2702 def tk_textIndexCloser(self, a, b, c):
2703 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2704 def tk_textResetAnchor(self, index):
2705 self.tk.call('tk_textResetAnchor', self._w, index)
2706 def compare(self, index1, op, index2):
2707 """Return whether between index INDEX1 and index INDEX2 the
2708 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2709 return self.tk.getboolean(self.tk.call(
2710 self._w, 'compare', index1, op, index2))
2711 def debug(self, boolean=None):
2712 """Turn on the internal consistency checks of the B-Tree inside the text
2713 widget according to BOOLEAN."""
2714 return self.tk.getboolean(self.tk.call(
2715 self._w, 'debug', boolean))
2716 def delete(self, index1, index2=None):
2717 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2718 self.tk.call(self._w, 'delete', index1, index2)
2719 def dlineinfo(self, index):
2720 """Return tuple (x,y,width,height,baseline) giving the bounding box
2721 and baseline position of the visible part of the line containing
2722 the character at INDEX."""
2723 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002724 def dump(self, index1, index2=None, command=None, **kw):
2725 """Return the contents of the widget between index1 and index2.
2726
2727 The type of contents returned in filtered based on the keyword
2728 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2729 given and true, then the corresponding items are returned. The result
2730 is a list of triples of the form (key, value, index). If none of the
2731 keywords are true then 'all' is used by default.
2732
2733 If the 'command' argument is given, it is called once for each element
2734 of the list of triples, with the values of each triple serving as the
2735 arguments to the function. In this case the list is not returned."""
2736 args = []
2737 func_name = None
2738 result = None
2739 if not command:
2740 # Never call the dump command without the -command flag, since the
2741 # output could involve Tcl quoting and would be a pain to parse
2742 # right. Instead just set the command to build a list of triples
2743 # as if we had done the parsing.
2744 result = []
2745 def append_triple(key, value, index, result=result):
2746 result.append((key, value, index))
2747 command = append_triple
2748 try:
2749 if not isinstance(command, str):
2750 func_name = command = self._register(command)
2751 args += ["-command", command]
2752 for key in kw:
2753 if kw[key]: args.append("-" + key)
2754 args.append(index1)
2755 if index2:
2756 args.append(index2)
2757 self.tk.call(self._w, "dump", *args)
2758 return result
2759 finally:
2760 if func_name:
2761 self.deletecommand(func_name)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002762
2763 ## new in tk8.4
2764 def edit(self, *args):
2765 """Internal method
2766
2767 This method controls the undo mechanism and
2768 the modified flag. The exact behavior of the
2769 command depends on the option argument that
2770 follows the edit argument. The following forms
2771 of the command are currently supported:
2772
2773 edit_modified, edit_redo, edit_reset, edit_separator
2774 and edit_undo
2775
2776 """
2777 return self._getints(
2778 self.tk.call((self._w, 'edit') + args)) or ()
2779
2780 def edit_modified(self, arg=None):
2781 """Get or Set the modified flag
2782
2783 If arg is not specified, returns the modified
2784 flag of the widget. The insert, delete, edit undo and
2785 edit redo commands or the user can set or clear the
2786 modified flag. If boolean is specified, sets the
2787 modified flag of the widget to arg.
2788 """
2789 return self.edit("modified", arg)
2790
2791 def edit_redo(self):
2792 """Redo the last undone edit
2793
2794 When the undo option is true, reapplies the last
2795 undone edits provided no other edits were done since
2796 then. Generates an error when the redo stack is empty.
2797 Does nothing when the undo option is false.
2798 """
2799 return self.edit("redo")
2800
2801 def edit_reset(self):
2802 """Clears the undo and redo stacks
2803 """
2804 return self.edit("reset")
2805
2806 def edit_separator(self):
2807 """Inserts a separator (boundary) on the undo stack.
2808
2809 Does nothing when the undo option is false
2810 """
2811 return self.edit("separator")
2812
2813 def edit_undo(self):
2814 """Undoes the last edit action
2815
2816 If the undo option is true. An edit action is defined
2817 as all the insert and delete commands that are recorded
2818 on the undo stack in between two separators. Generates
2819 an error when the undo stack is empty. Does nothing
2820 when the undo option is false
2821 """
2822 return self.edit("undo")
2823
Fredrik Lundh06d28152000-08-09 18:03:12 +00002824 def get(self, index1, index2=None):
2825 """Return the text from INDEX1 to INDEX2 (not included)."""
2826 return self.tk.call(self._w, 'get', index1, index2)
2827 # (Image commands are new in 8.0)
2828 def image_cget(self, index, option):
2829 """Return the value of OPTION of an embedded image at INDEX."""
2830 if option[:1] != "-":
2831 option = "-" + option
2832 if option[-1:] == "_":
2833 option = option[:-1]
2834 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002835 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002836 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002837 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002838 def image_create(self, index, cnf={}, **kw):
2839 """Create an embedded image at INDEX."""
2840 return apply(self.tk.call,
2841 (self._w, "image", "create", index)
2842 + self._options(cnf, kw))
2843 def image_names(self):
2844 """Return all names of embedded images in this widget."""
2845 return self.tk.call(self._w, "image", "names")
2846 def index(self, index):
2847 """Return the index in the form line.char for INDEX."""
2848 return self.tk.call(self._w, 'index', index)
2849 def insert(self, index, chars, *args):
2850 """Insert CHARS before the characters at INDEX. An additional
2851 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2852 self.tk.call((self._w, 'insert', index, chars) + args)
2853 def mark_gravity(self, markName, direction=None):
2854 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2855 Return the current value if None is given for DIRECTION."""
2856 return self.tk.call(
2857 (self._w, 'mark', 'gravity', markName, direction))
2858 def mark_names(self):
2859 """Return all mark names."""
2860 return self.tk.splitlist(self.tk.call(
2861 self._w, 'mark', 'names'))
2862 def mark_set(self, markName, index):
2863 """Set mark MARKNAME before the character at INDEX."""
2864 self.tk.call(self._w, 'mark', 'set', markName, index)
2865 def mark_unset(self, *markNames):
2866 """Delete all marks in MARKNAMES."""
2867 self.tk.call((self._w, 'mark', 'unset') + markNames)
2868 def mark_next(self, index):
2869 """Return the name of the next mark after INDEX."""
2870 return self.tk.call(self._w, 'mark', 'next', index) or None
2871 def mark_previous(self, index):
2872 """Return the name of the previous mark before INDEX."""
2873 return self.tk.call(self._w, 'mark', 'previous', index) or None
2874 def scan_mark(self, x, y):
2875 """Remember the current X, Y coordinates."""
2876 self.tk.call(self._w, 'scan', 'mark', x, y)
2877 def scan_dragto(self, x, y):
2878 """Adjust the view of the text to 10 times the
2879 difference between X and Y and the coordinates given in
2880 scan_mark."""
2881 self.tk.call(self._w, 'scan', 'dragto', x, y)
2882 def search(self, pattern, index, stopindex=None,
2883 forwards=None, backwards=None, exact=None,
2884 regexp=None, nocase=None, count=None):
2885 """Search PATTERN beginning from INDEX until STOPINDEX.
2886 Return the index of the first character of a match or an empty string."""
2887 args = [self._w, 'search']
2888 if forwards: args.append('-forwards')
2889 if backwards: args.append('-backwards')
2890 if exact: args.append('-exact')
2891 if regexp: args.append('-regexp')
2892 if nocase: args.append('-nocase')
2893 if count: args.append('-count'); args.append(count)
2894 if pattern[0] == '-': args.append('--')
2895 args.append(pattern)
2896 args.append(index)
2897 if stopindex: args.append(stopindex)
2898 return self.tk.call(tuple(args))
2899 def see(self, index):
2900 """Scroll such that the character at INDEX is visible."""
2901 self.tk.call(self._w, 'see', index)
2902 def tag_add(self, tagName, index1, *args):
2903 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2904 Additional pairs of indices may follow in ARGS."""
2905 self.tk.call(
2906 (self._w, 'tag', 'add', tagName, index1) + args)
2907 def tag_unbind(self, tagName, sequence, funcid=None):
2908 """Unbind for all characters with TAGNAME for event SEQUENCE the
2909 function identified with FUNCID."""
2910 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2911 if funcid:
2912 self.deletecommand(funcid)
2913 def tag_bind(self, tagName, sequence, func, add=None):
2914 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002915
Fredrik Lundh06d28152000-08-09 18:03:12 +00002916 An additional boolean parameter ADD specifies whether FUNC will be
2917 called additionally to the other bound function or whether it will
2918 replace the previous function. See bind for the return value."""
2919 return self._bind((self._w, 'tag', 'bind', tagName),
2920 sequence, func, add)
2921 def tag_cget(self, tagName, option):
2922 """Return the value of OPTION for tag TAGNAME."""
2923 if option[:1] != '-':
2924 option = '-' + option
2925 if option[-1:] == '_':
2926 option = option[:-1]
2927 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002928 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002929 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002930 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002931 tag_config = tag_configure
2932 def tag_delete(self, *tagNames):
2933 """Delete all tags in TAGNAMES."""
2934 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2935 def tag_lower(self, tagName, belowThis=None):
2936 """Change the priority of tag TAGNAME such that it is lower
2937 than the priority of BELOWTHIS."""
2938 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2939 def tag_names(self, index=None):
2940 """Return a list of all tag names."""
2941 return self.tk.splitlist(
2942 self.tk.call(self._w, 'tag', 'names', index))
2943 def tag_nextrange(self, tagName, index1, index2=None):
2944 """Return a list of start and end index for the first sequence of
2945 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2946 The text is searched forward from INDEX1."""
2947 return self.tk.splitlist(self.tk.call(
2948 self._w, 'tag', 'nextrange', tagName, index1, index2))
2949 def tag_prevrange(self, tagName, index1, index2=None):
2950 """Return a list of start and end index for the first sequence of
2951 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2952 The text is searched backwards from INDEX1."""
2953 return self.tk.splitlist(self.tk.call(
2954 self._w, 'tag', 'prevrange', tagName, index1, index2))
2955 def tag_raise(self, tagName, aboveThis=None):
2956 """Change the priority of tag TAGNAME such that it is higher
2957 than the priority of ABOVETHIS."""
2958 self.tk.call(
2959 self._w, 'tag', 'raise', tagName, aboveThis)
2960 def tag_ranges(self, tagName):
2961 """Return a list of ranges of text which have tag TAGNAME."""
2962 return self.tk.splitlist(self.tk.call(
2963 self._w, 'tag', 'ranges', tagName))
2964 def tag_remove(self, tagName, index1, index2=None):
2965 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2966 self.tk.call(
2967 self._w, 'tag', 'remove', tagName, index1, index2)
2968 def window_cget(self, index, option):
2969 """Return the value of OPTION of an embedded window at INDEX."""
2970 if option[:1] != '-':
2971 option = '-' + option
2972 if option[-1:] == '_':
2973 option = option[:-1]
2974 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002975 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002976 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002977 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002978 window_config = window_configure
2979 def window_create(self, index, cnf={}, **kw):
2980 """Create a window at INDEX."""
2981 self.tk.call(
2982 (self._w, 'window', 'create', index)
2983 + self._options(cnf, kw))
2984 def window_names(self):
2985 """Return all names of embedded windows in this widget."""
2986 return self.tk.splitlist(
2987 self.tk.call(self._w, 'window', 'names'))
2988 def xview(self, *what):
2989 """Query and change horizontal position of the view."""
2990 if not what:
2991 return self._getdoubles(self.tk.call(self._w, 'xview'))
2992 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002993 def xview_moveto(self, fraction):
2994 """Adjusts the view in the window so that FRACTION of the
2995 total width of the canvas is off-screen to the left."""
2996 self.tk.call(self._w, 'xview', 'moveto', fraction)
2997 def xview_scroll(self, number, what):
2998 """Shift the x-view according to NUMBER which is measured
2999 in "units" or "pages" (WHAT)."""
3000 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003001 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003002 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003003 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003004 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003005 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003006 def yview_moveto(self, fraction):
3007 """Adjusts the view in the window so that FRACTION of the
3008 total height of the canvas is off-screen to the top."""
3009 self.tk.call(self._w, 'yview', 'moveto', fraction)
3010 def yview_scroll(self, number, what):
3011 """Shift the y-view according to NUMBER which is measured
3012 in "units" or "pages" (WHAT)."""
3013 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003014 def yview_pickplace(self, *what):
3015 """Obsolete function, use see."""
3016 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003017
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003018
Guido van Rossum28574b51996-10-21 15:16:51 +00003019class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003020 """Internal class. It wraps the command in the widget OptionMenu."""
3021 def __init__(self, var, value, callback=None):
3022 self.__value = value
3023 self.__var = var
3024 self.__callback = callback
3025 def __call__(self, *args):
3026 self.__var.set(self.__value)
3027 if self.__callback:
3028 apply(self.__callback, (self.__value,)+args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003029
3030class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003031 """OptionMenu which allows the user to select a value from a menu."""
3032 def __init__(self, master, variable, value, *values, **kwargs):
3033 """Construct an optionmenu widget with the parent MASTER, with
3034 the resource textvariable set to VARIABLE, the initially selected
3035 value VALUE, the other menu values VALUES and an additional
3036 keyword argument command."""
3037 kw = {"borderwidth": 2, "textvariable": variable,
3038 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3039 "highlightthickness": 2}
3040 Widget.__init__(self, master, "menubutton", kw)
3041 self.widgetName = 'tk_optionMenu'
3042 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3043 self.menuname = menu._w
3044 # 'command' is the only supported keyword
3045 callback = kwargs.get('command')
3046 if kwargs.has_key('command'):
3047 del kwargs['command']
3048 if kwargs:
3049 raise TclError, 'unknown option -'+kwargs.keys()[0]
3050 menu.add_command(label=value,
3051 command=_setit(variable, value, callback))
3052 for v in values:
3053 menu.add_command(label=v,
3054 command=_setit(variable, v, callback))
3055 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003056
Fredrik Lundh06d28152000-08-09 18:03:12 +00003057 def __getitem__(self, name):
3058 if name == 'menu':
3059 return self.__menu
3060 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003061
Fredrik Lundh06d28152000-08-09 18:03:12 +00003062 def destroy(self):
3063 """Destroy this widget and the associated menu."""
3064 Menubutton.destroy(self)
3065 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003066
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003067class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003068 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003069 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003070 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3071 self.name = None
3072 if not master:
3073 master = _default_root
3074 if not master:
3075 raise RuntimeError, 'Too early to create image'
3076 self.tk = master.tk
3077 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003078 Image._last_id += 1
3079 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003080 # The following is needed for systems where id(x)
3081 # can return a negative number, such as Linux/m68k:
3082 if name[0] == '-': name = '_' + name[1:]
3083 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3084 elif kw: cnf = kw
3085 options = ()
3086 for k, v in cnf.items():
3087 if callable(v):
3088 v = self._register(v)
3089 options = options + ('-'+k, v)
3090 self.tk.call(('image', 'create', imgtype, name,) + options)
3091 self.name = name
3092 def __str__(self): return self.name
3093 def __del__(self):
3094 if self.name:
3095 try:
3096 self.tk.call('image', 'delete', self.name)
3097 except TclError:
3098 # May happen if the root was destroyed
3099 pass
3100 def __setitem__(self, key, value):
3101 self.tk.call(self.name, 'configure', '-'+key, value)
3102 def __getitem__(self, key):
3103 return self.tk.call(self.name, 'configure', '-'+key)
3104 def configure(self, **kw):
3105 """Configure the image."""
3106 res = ()
3107 for k, v in _cnfmerge(kw).items():
3108 if v is not None:
3109 if k[-1] == '_': k = k[:-1]
3110 if callable(v):
3111 v = self._register(v)
3112 res = res + ('-'+k, v)
3113 self.tk.call((self.name, 'config') + res)
3114 config = configure
3115 def height(self):
3116 """Return the height of the image."""
3117 return getint(
3118 self.tk.call('image', 'height', self.name))
3119 def type(self):
3120 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3121 return self.tk.call('image', 'type', self.name)
3122 def width(self):
3123 """Return the width of the image."""
3124 return getint(
3125 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003126
3127class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003128 """Widget which can display colored images in GIF, PPM/PGM format."""
3129 def __init__(self, name=None, cnf={}, master=None, **kw):
3130 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003131
Fredrik Lundh06d28152000-08-09 18:03:12 +00003132 Valid resource names: data, format, file, gamma, height, palette,
3133 width."""
3134 apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
3135 def blank(self):
3136 """Display a transparent image."""
3137 self.tk.call(self.name, 'blank')
3138 def cget(self, option):
3139 """Return the value of OPTION."""
3140 return self.tk.call(self.name, 'cget', '-' + option)
3141 # XXX config
3142 def __getitem__(self, key):
3143 return self.tk.call(self.name, 'cget', '-' + key)
3144 # XXX copy -from, -to, ...?
3145 def copy(self):
3146 """Return a new PhotoImage with the same image as this widget."""
3147 destImage = PhotoImage()
3148 self.tk.call(destImage, 'copy', self.name)
3149 return destImage
3150 def zoom(self,x,y=''):
3151 """Return a new PhotoImage with the same image as this widget
3152 but zoom it with X and Y."""
3153 destImage = PhotoImage()
3154 if y=='': y=x
3155 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3156 return destImage
3157 def subsample(self,x,y=''):
3158 """Return a new PhotoImage based on the same image as this widget
3159 but use only every Xth or Yth pixel."""
3160 destImage = PhotoImage()
3161 if y=='': y=x
3162 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3163 return destImage
3164 def get(self, x, y):
3165 """Return the color (red, green, blue) of the pixel at X,Y."""
3166 return self.tk.call(self.name, 'get', x, y)
3167 def put(self, data, to=None):
3168 """Put row formated colors to image starting from
3169 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3170 args = (self.name, 'put', data)
3171 if to:
3172 if to[0] == '-to':
3173 to = to[1:]
3174 args = args + ('-to',) + tuple(to)
3175 self.tk.call(args)
3176 # XXX read
3177 def write(self, filename, format=None, from_coords=None):
3178 """Write image to file FILENAME in FORMAT starting from
3179 position FROM_COORDS."""
3180 args = (self.name, 'write', filename)
3181 if format:
3182 args = args + ('-format', format)
3183 if from_coords:
3184 args = args + ('-from',) + tuple(from_coords)
3185 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003186
3187class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003188 """Widget which can display a bitmap."""
3189 def __init__(self, name=None, cnf={}, master=None, **kw):
3190 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003191
Fredrik Lundh06d28152000-08-09 18:03:12 +00003192 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3193 apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003194
3195def image_names(): return _default_root.tk.call('image', 'names')
3196def image_types(): return _default_root.tk.call('image', 'types')
3197
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003198
3199class Spinbox(Widget):
3200 """spinbox widget."""
3201 def __init__(self, master=None, cnf={}, **kw):
3202 """Construct a spinbox widget with the parent MASTER.
3203
3204 STANDARD OPTIONS
3205
3206 activebackground, background, borderwidth,
3207 cursor, exportselection, font, foreground,
3208 highlightbackground, highlightcolor,
3209 highlightthickness, insertbackground,
3210 insertborderwidth, insertofftime,
3211 insertontime, insertwidth, justify, relief,
3212 repeatdelay, repeatinterval,
3213 selectbackground, selectborderwidth
3214 selectforeground, takefocus, textvariable
3215 xscrollcommand.
3216
3217 WIDGET-SPECIFIC OPTIONS
3218
3219 buttonbackground, buttoncursor,
3220 buttondownrelief, buttonuprelief,
3221 command, disabledbackground,
3222 disabledforeground, format, from,
3223 invalidcommand, increment,
3224 readonlybackground, state, to,
3225 validate, validatecommand values,
3226 width, wrap,
3227 """
3228 Widget.__init__(self, master, 'spinbox', cnf, kw)
3229
3230 def bbox(self, index):
3231 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3232 rectangle which encloses the character given by index.
3233
3234 The first two elements of the list give the x and y
3235 coordinates of the upper-left corner of the screen
3236 area covered by the character (in pixels relative
3237 to the widget) and the last two elements give the
3238 width and height of the character, in pixels. The
3239 bounding box may refer to a region outside the
3240 visible area of the window.
3241 """
3242 return self.tk.call(self._w, 'bbox', index)
3243
3244 def delete(self, first, last=None):
3245 """Delete one or more elements of the spinbox.
3246
3247 First is the index of the first character to delete,
3248 and last is the index of the character just after
3249 the last one to delete. If last isn't specified it
3250 defaults to first+1, i.e. a single character is
3251 deleted. This command returns an empty string.
3252 """
3253 return self.tk.call(self._w, 'delete', first, last)
3254
3255 def get(self):
3256 """Returns the spinbox's string"""
3257 return self.tk.call(self._w, 'get')
3258
3259 def icursor(self, index):
3260 """Alter the position of the insertion cursor.
3261
3262 The insertion cursor will be displayed just before
3263 the character given by index. Returns an empty string
3264 """
3265 return self.tk.call(self._w, 'icursor', index)
3266
3267 def identify(self, x, y):
3268 """Returns the name of the widget at position x, y
3269
3270 Return value is one of: none, buttondown, buttonup, entry
3271 """
3272 return self.tk.call(self._w, 'identify', x, y)
3273
3274 def index(self, index):
3275 """Returns the numerical index corresponding to index
3276 """
3277 return self.tk.call(self._w, 'index', index)
3278
3279 def insert(self, index, s):
3280 """Insert string s at index
3281
3282 Returns an empty string.
3283 """
3284 return self.tk.call(self._w, 'insert', index, s)
3285
3286 def invoke(self, element):
3287 """Causes the specified element to be invoked
3288
3289 The element could be buttondown or buttonup
3290 triggering the action associated with it.
3291 """
3292 return self.tk.call(self._w, 'invoke', element)
3293
3294 def scan(self, *args):
3295 """Internal function."""
3296 return self._getints(
3297 self.tk.call((self._w, 'scan') + args)) or ()
3298
3299 def scan_mark(self, x):
3300 """Records x and the current view in the spinbox window;
3301
3302 used in conjunction with later scan dragto commands.
3303 Typically this command is associated with a mouse button
3304 press in the widget. It returns an empty string.
3305 """
3306 return self.scan("mark", x)
3307
3308 def scan_dragto(self, x):
3309 """Compute the difference between the given x argument
3310 and the x argument to the last scan mark command
3311
3312 It then adjusts the view left or right by 10 times the
3313 difference in x-coordinates. This command is typically
3314 associated with mouse motion events in the widget, to
3315 produce the effect of dragging the spinbox at high speed
3316 through the window. The return value is an empty string.
3317 """
3318 return self.scan("dragto", x)
3319
3320 def selection(self, *args):
3321 """Internal function."""
3322 return self._getints(
3323 self.tk.call((self._w, 'selection') + args)) or ()
3324
3325 def selection_adjust(self, index):
3326 """Locate the end of the selection nearest to the character
3327 given by index,
3328
3329 Then adjust that end of the selection to be at index
3330 (i.e including but not going beyond index). The other
3331 end of the selection is made the anchor point for future
3332 select to commands. If the selection isn't currently in
3333 the spinbox, then a new selection is created to include
3334 the characters between index and the most recent selection
3335 anchor point, inclusive. Returns an empty string.
3336 """
3337 return self.selection("adjust", index)
3338
3339 def selection_clear(self):
3340 """Clear the selection
3341
3342 If the selection isn't in this widget then the
3343 command has no effect. Returns an empty string.
3344 """
3345 return self.selection("clear")
3346
3347 def selection_element(self, element=None):
3348 """Sets or gets the currently selected element.
3349
3350 If a spinbutton element is specified, it will be
3351 displayed depressed
3352 """
3353 return self.selection("element", element)
3354
3355###########################################################################
3356
3357class LabelFrame(Widget):
3358 """labelframe widget."""
3359 def __init__(self, master=None, cnf={}, **kw):
3360 """Construct a labelframe widget with the parent MASTER.
3361
3362 STANDARD OPTIONS
3363
3364 borderwidth, cursor, font, foreground,
3365 highlightbackground, highlightcolor,
3366 highlightthickness, padx, pady, relief,
3367 takefocus, text
3368
3369 WIDGET-SPECIFIC OPTIONS
3370
3371 background, class, colormap, container,
3372 height, labelanchor, labelwidget,
3373 visual, width
3374 """
3375 Widget.__init__(self, master, 'labelframe', cnf, kw)
3376
3377########################################################################
3378
3379class PanedWindow(Widget):
3380 """panedwindow widget."""
3381 def __init__(self, master=None, cnf={}, **kw):
3382 """Construct a panedwindow widget with the parent MASTER.
3383
3384 STANDARD OPTIONS
3385
3386 background, borderwidth, cursor, height,
3387 orient, relief, width
3388
3389 WIDGET-SPECIFIC OPTIONS
3390
3391 handlepad, handlesize, opaqueresize,
3392 sashcursor, sashpad, sashrelief,
3393 sashwidth, showhandle,
3394 """
3395 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3396
3397 def add(self, child, **kw):
3398 """Add a child widget to the panedwindow in a new pane.
3399
3400 The child argument is the name of the child widget
3401 followed by pairs of arguments that specify how to
3402 manage the windows. Options may have any of the values
3403 accepted by the configure subcommand.
3404 """
3405 self.tk.call((self._w, 'add', child) + self._options(kw))
3406
3407 def remove(self, child):
3408 """Remove the pane containing child from the panedwindow
3409
3410 All geometry management options for child will be forgotten.
3411 """
3412 self.tk.call(self._w, 'forget', child)
3413 forget=remove
3414
3415 def identify(self, x, y):
3416 """Identify the panedwindow component at point x, y
3417
3418 If the point is over a sash or a sash handle, the result
3419 is a two element list containing the index of the sash or
3420 handle, and a word indicating whether it is over a sash
3421 or a handle, such as {0 sash} or {2 handle}. If the point
3422 is over any other part of the panedwindow, the result is
3423 an empty list.
3424 """
3425 return self.tk.call(self._w, 'identify', x, y)
3426
3427 def proxy(self, *args):
3428 """Internal function."""
3429 return self._getints(
3430 self.tk.call((self._w, 'proxy') + args)) or ()
3431
3432 def proxy_coord(self):
3433 """Return the x and y pair of the most recent proxy location
3434 """
3435 return self.proxy("coord")
3436
3437 def proxy_forget(self):
3438 """Remove the proxy from the display.
3439 """
3440 return self.proxy("forget")
3441
3442 def proxy_place(self, x, y):
3443 """Place the proxy at the given x and y coordinates.
3444 """
3445 return self.proxy("place", x, y)
3446
3447 def sash(self, *args):
3448 """Internal function."""
3449 return self._getints(
3450 self.tk.call((self._w, 'sash') + args)) or ()
3451
3452 def sash_coord(self, index):
3453 """Return the current x and y pair for the sash given by index.
3454
3455 Index must be an integer between 0 and 1 less than the
3456 number of panes in the panedwindow. The coordinates given are
3457 those of the top left corner of the region containing the sash.
3458 pathName sash dragto index x y This command computes the
3459 difference between the given coordinates and the coordinates
3460 given to the last sash coord command for the given sash. It then
3461 moves that sash the computed difference. The return value is the
3462 empty string.
3463 """
3464 return self.sash("coord", index)
3465
3466 def sash_mark(self, index):
3467 """Records x and y for the sash given by index;
3468
3469 Used in conjunction with later dragto commands to move the sash.
3470 """
3471 return self.sash("mark", index)
3472
3473 def sash_place(self, index, x, y):
3474 """Place the sash given by index at the given coordinates
3475 """
3476 return self.sash("place", index, x, y)
3477
3478 def panecget(self, child, option):
3479 """Query a management option for window.
3480
3481 Option may be any value allowed by the paneconfigure subcommand
3482 """
3483 return self.tk.call(
3484 (self._w, 'panecget') + (child, '-'+option))
3485
3486 def paneconfigure(self, tagOrId, cnf=None, **kw):
3487 """Query or modify the management options for window.
3488
3489 If no option is specified, returns a list describing all
3490 of the available options for pathName. If option is
3491 specified with no value, then the command returns a list
3492 describing the one named option (this list will be identical
3493 to the corresponding sublist of the value returned if no
3494 option is specified). If one or more option-value pairs are
3495 specified, then the command modifies the given widget
3496 option(s) to have the given value(s); in this case the
3497 command returns an empty string. The following options
3498 are supported:
3499
3500 after window
3501 Insert the window after the window specified. window
3502 should be the name of a window already managed by pathName.
3503 before window
3504 Insert the window before the window specified. window
3505 should be the name of a window already managed by pathName.
3506 height size
3507 Specify a height for the window. The height will be the
3508 outer dimension of the window including its border, if
3509 any. If size is an empty string, or if -height is not
3510 specified, then the height requested internally by the
3511 window will be used initially; the height may later be
3512 adjusted by the movement of sashes in the panedwindow.
3513 Size may be any value accepted by Tk_GetPixels.
3514 minsize n
3515 Specifies that the size of the window cannot be made
3516 less than n. This constraint only affects the size of
3517 the widget in the paned dimension -- the x dimension
3518 for horizontal panedwindows, the y dimension for
3519 vertical panedwindows. May be any value accepted by
3520 Tk_GetPixels.
3521 padx n
3522 Specifies a non-negative value indicating how much
3523 extra space to leave on each side of the window in
3524 the X-direction. The value may have any of the forms
3525 accepted by Tk_GetPixels.
3526 pady n
3527 Specifies a non-negative value indicating how much
3528 extra space to leave on each side of the window in
3529 the Y-direction. The value may have any of the forms
3530 accepted by Tk_GetPixels.
3531 sticky style
3532 If a window's pane is larger than the requested
3533 dimensions of the window, this option may be used
3534 to position (or stretch) the window within its pane.
3535 Style is a string that contains zero or more of the
3536 characters n, s, e or w. The string can optionally
3537 contains spaces or commas, but they are ignored. Each
3538 letter refers to a side (north, south, east, or west)
3539 that the window will "stick" to. If both n and s
3540 (or e and w) are specified, the window will be
3541 stretched to fill the entire height (or width) of
3542 its cavity.
3543 width size
3544 Specify a width for the window. The width will be
3545 the outer dimension of the window including its
3546 border, if any. If size is an empty string, or
3547 if -width is not specified, then the width requested
3548 internally by the window will be used initially; the
3549 width may later be adjusted by the movement of sashes
3550 in the panedwindow. Size may be any value accepted by
3551 Tk_GetPixels.
3552
3553 """
3554 if cnf is None and not kw:
3555 cnf = {}
3556 for x in self.tk.split(
3557 self.tk.call(self._w,
3558 'paneconfigure', tagOrId)):
3559 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3560 return cnf
3561 if type(cnf) == StringType and not kw:
3562 x = self.tk.split(self.tk.call(
3563 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3564 return (x[0][1:],) + x[1:]
3565 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3566 self._options(cnf, kw))
3567 paneconfig = paneconfigure
3568
3569 def panes(self):
3570 """Returns an ordered list of the child panes."""
3571 return self.tk.call(self._w, 'panes')
3572
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003573######################################################################
3574# Extensions:
3575
3576class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003577 def __init__(self, master=None, cnf={}, **kw):
3578 Widget.__init__(self, master, 'studbutton', cnf, kw)
3579 self.bind('<Any-Enter>', self.tkButtonEnter)
3580 self.bind('<Any-Leave>', self.tkButtonLeave)
3581 self.bind('<1>', self.tkButtonDown)
3582 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003583
3584class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003585 def __init__(self, master=None, cnf={}, **kw):
3586 Widget.__init__(self, master, 'tributton', cnf, kw)
3587 self.bind('<Any-Enter>', self.tkButtonEnter)
3588 self.bind('<Any-Leave>', self.tkButtonLeave)
3589 self.bind('<1>', self.tkButtonDown)
3590 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3591 self['fg'] = self['bg']
3592 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003593
Guido van Rossumc417ef81996-08-21 23:38:59 +00003594######################################################################
3595# Test:
3596
3597def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003598 root = Tk()
3599 text = "This is Tcl/Tk version %s" % TclVersion
3600 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003601 try:
3602 text = text + unicode("\nThis should be a cedilla: \347",
3603 "iso-8859-1")
3604 except NameError:
3605 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003606 label = Label(root, text=text)
3607 label.pack()
3608 test = Button(root, text="Click me!",
3609 command=lambda root=root: root.test.configure(
3610 text="[%s]" % root.test['text']))
3611 test.pack()
3612 root.test = test
3613 quit = Button(root, text="QUIT", command=root.destroy)
3614 quit.pack()
3615 # The following three commands are needed so the window pops
3616 # up on top on Windows...
3617 root.iconify()
3618 root.update()
3619 root.deiconify()
3620 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003621
3622if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003623 _test()