blob: e2f09a5a72b4033e6ffc7918c23ab6ca98d2e911 [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,
6Checkbutton, Scale, Listbox, Scrollbar, OptionMenu. Properties of the widgets are
7specified with keyword arguments. Keyword arguments have the same
8name as the corresponding resource under Tk.
9
10Widgets are positioned with one of the geometry managers Place, Pack
11or Grid. These managers can be called with methods place, pack, grid
12available in every Widget.
13
14Actions are bound to events by resources (e.g. keyword argument command) or
15with the method bind.
16
17Example (Hello, World):
18import Tkinter
19from Tkconstants import *
20tk = Tkinter.Tk()
21frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
22frame.pack(fill=BOTH,expand=1)
23label = Tkinter.Label(frame, text="Hello, World")
24label.pack(fill=X, expand=1)
25button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
26button.pack(side=BOTTOM)
27tk.mainloop()
28"""
Guido van Rossum2dcf5291994-07-06 09:23:20 +000029
Guido van Rossum37dcab11996-05-16 16:00:19 +000030__version__ = "$Revision$"
31
Guido van Rossumf8d579c1999-01-04 18:06:45 +000032import sys
33if sys.platform == "win32":
Fredrik Lundh06d28152000-08-09 18:03:12 +000034 import FixTk # Attempt to configure Tcl/Tk without requiring PATH
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000036tkinter = _tkinter # b/w compat for export
37TclError = _tkinter.TclError
Guido van Rossum7e9394a1995-03-17 16:21:33 +000038from types import *
Guido van Rossuma5773dd1995-09-07 19:22:00 +000039from Tkconstants import *
Guido van Rossum37dcab11996-05-16 16:00:19 +000040import string; _string = string; del string
Guido van Rossumf0c891a1998-04-29 21:43:36 +000041try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000042 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000043except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000044 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000045
Guido van Rossum95806091997-02-15 18:33:24 +000046TkVersion = _string.atof(_tkinter.TK_VERSION)
47TclVersion = _string.atof(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000048
Guido van Rossumd6615ab1997-08-05 02:35:01 +000049READABLE = _tkinter.READABLE
50WRITABLE = _tkinter.WRITABLE
51EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000052
53# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
54try: _tkinter.createfilehandler
55except AttributeError: _tkinter.createfilehandler = None
56try: _tkinter.deletefilehandler
57except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000058
59
Guido van Rossum2dcf5291994-07-06 09:23:20 +000060def _flatten(tuple):
Fredrik Lundh06d28152000-08-09 18:03:12 +000061 """Internal function."""
62 res = ()
63 for item in tuple:
64 if type(item) in (TupleType, ListType):
65 res = res + _flatten(item)
66 elif item is not None:
67 res = res + (item,)
68 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000069
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000070try: _flatten = _tkinter._flatten
71except AttributeError: pass
72
Guido van Rossum2dcf5291994-07-06 09:23:20 +000073def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000074 """Internal function."""
75 if type(cnfs) is DictionaryType:
76 return cnfs
77 elif type(cnfs) in (NoneType, StringType):
78 return cnfs
79 else:
80 cnf = {}
81 for c in _flatten(cnfs):
82 try:
83 cnf.update(c)
84 except (AttributeError, TypeError), msg:
85 print "_cnfmerge: fallback due to:", msg
86 for k, v in c.items():
87 cnf[k] = v
88 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000089
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000090try: _cnfmerge = _tkinter._cnfmerge
91except AttributeError: pass
92
Guido van Rossum2dcf5291994-07-06 09:23:20 +000093class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000094 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000095
Fredrik Lundh06d28152000-08-09 18:03:12 +000096 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +000097
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 KeyPress, KeyRelease - for keyboard events
99 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
100 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
101 Colormap, Gravity, Reparent, Property, Destroy, Activate,
102 Deactivate - for window events.
103
104 If a callback function for one of these events is registered
105 using bind, bind_all, bind_class, or tag_bind, the callback is
106 called with an Event as first argument. It will have the
107 following attributes (in braces are the event types for which
108 the attribute is valid):
109
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000110 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000111 num - mouse button pressed (ButtonPress, ButtonRelease)
112 focus - whether the window has the focus (Enter, Leave)
113 height - height of the exposed window (Configure, Expose)
114 width - width of the exposed window (Configure, Expose)
115 keycode - keycode of the pressed key (KeyPress, KeyRelease)
116 state - state of the event as a number (ButtonPress, ButtonRelease,
117 Enter, KeyPress, KeyRelease,
118 Leave, Motion)
119 state - state as a string (Visibility)
120 time - when the event occurred
121 x - x-position of the mouse
122 y - y-position of the mouse
123 x_root - x-position of the mouse on the screen
124 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
125 y_root - y-position of the mouse on the screen
126 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
127 char - pressed character (KeyPress, KeyRelease)
128 send_event - see X/Windows documentation
129 keysym - keysym of the the event as a string (KeyPress, KeyRelease)
130 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
131 type - type of the event as a number
132 widget - widget in which the event occurred
133 delta - delta of wheel movement (MouseWheel)
134 """
135 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000136
Guido van Rossumc4570481998-03-20 20:45:49 +0000137_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000138_default_root = None
139
Guido van Rossumc4570481998-03-20 20:45:49 +0000140def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000141 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000142
Fredrik Lundh06d28152000-08-09 18:03:12 +0000143 Call this function to inhibit that the first instance of
144 Tk is used for windows without an explicit parent window.
145 """
146 global _support_default_root
147 _support_default_root = 0
148 global _default_root
149 _default_root = None
150 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000151
Guido van Rossum45853db1994-06-20 12:19:19 +0000152def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000153 """Internal function."""
154 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000155
Guido van Rossum97aeca11994-07-07 13:12:12 +0000156def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000157 """Internal function. Calling it will throw the exception SystemExit."""
158 raise SystemExit, code
Guido van Rossum97aeca11994-07-07 13:12:12 +0000159
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000160_varnum = 0
161class Variable:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000162 """Internal class. Base class to define value holders for e.g. buttons."""
163 _default = ""
164 def __init__(self, master=None):
165 """Construct a variable with an optional MASTER as master widget.
166 The variable is named PY_VAR_number in Tcl.
167 """
168 global _varnum
169 if not master:
170 master = _default_root
171 self._master = master
172 self._tk = master.tk
173 self._name = 'PY_VAR' + `_varnum`
174 _varnum = _varnum + 1
175 self.set(self._default)
176 def __del__(self):
177 """Unset the variable in Tcl."""
178 self._tk.globalunsetvar(self._name)
179 def __str__(self):
180 """Return the name of the variable in Tcl."""
181 return self._name
182 def set(self, value):
183 """Set the variable to VALUE."""
184 return self._tk.globalsetvar(self._name, value)
185 def trace_variable(self, mode, callback):
186 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000187
Fredrik Lundh06d28152000-08-09 18:03:12 +0000188 MODE is one of "r", "w", "u" for read, write, undefine.
189 CALLBACK must be a function which is called when
190 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000191
Fredrik Lundh06d28152000-08-09 18:03:12 +0000192 Return the name of the callback.
193 """
194 cbname = self._master._register(callback)
195 self._tk.call("trace", "variable", self._name, mode, cbname)
196 return cbname
197 trace = trace_variable
198 def trace_vdelete(self, mode, cbname):
199 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000200
Fredrik Lundh06d28152000-08-09 18:03:12 +0000201 MODE is one of "r", "w", "u" for read, write, undefine.
202 CBNAME is the name of the callback returned from trace_variable or trace.
203 """
204 self._tk.call("trace", "vdelete", self._name, mode, cbname)
205 self._master.deletecommand(cbname)
206 def trace_vinfo(self):
207 """Return all trace callback information."""
208 return map(self._tk.split, self._tk.splitlist(
209 self._tk.call("trace", "vinfo", self._name)))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000210
211class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000212 """Value holder for strings variables."""
213 _default = ""
214 def __init__(self, master=None):
215 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000216
Fredrik Lundh06d28152000-08-09 18:03:12 +0000217 MASTER can be given as master widget."""
218 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000219
Fredrik Lundh06d28152000-08-09 18:03:12 +0000220 def get(self):
221 """Return value of variable as string."""
222 return self._tk.globalgetvar(self._name)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000223
224class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000225 """Value holder for integer variables."""
226 _default = 0
227 def __init__(self, master=None):
228 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000229
Fredrik Lundh06d28152000-08-09 18:03:12 +0000230 MASTER can be given as master widget."""
231 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000232
Fredrik Lundh06d28152000-08-09 18:03:12 +0000233 def get(self):
234 """Return the value of the variable as an integer."""
235 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000236
237class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000238 """Value holder for float variables."""
239 _default = 0.0
240 def __init__(self, master=None):
241 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000242
Fredrik Lundh06d28152000-08-09 18:03:12 +0000243 MASTER can be given as a master widget."""
244 Variable.__init__(self, master)
245
246 def get(self):
247 """Return the value of the variable as a float."""
248 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000249
250class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000251 """Value holder for boolean variables."""
252 _default = "false"
253 def __init__(self, master=None):
254 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000255
Fredrik Lundh06d28152000-08-09 18:03:12 +0000256 MASTER can be given as a master widget."""
257 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000258
Fredrik Lundh06d28152000-08-09 18:03:12 +0000259 def get(self):
260 """Return the value of the variable as 0 or 1."""
261 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000262
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000263def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000264 """Run the main loop of Tcl."""
265 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000266
Guido van Rossum0132f691998-04-30 17:50:36 +0000267getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000268
Guido van Rossum0132f691998-04-30 17:50:36 +0000269getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000270
271def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000272 """Convert true and false to integer values 1 and 0."""
273 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000274
Guido van Rossum368e06b1997-11-07 20:38:49 +0000275# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000276class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000277 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000278
Fredrik Lundh06d28152000-08-09 18:03:12 +0000279 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000280
Fredrik Lundh06d28152000-08-09 18:03:12 +0000281 # XXX font command?
282 _tclCommands = None
283 def destroy(self):
284 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000285
Fredrik Lundh06d28152000-08-09 18:03:12 +0000286 Delete all Tcl commands created for
287 this widget in the Tcl interpreter."""
288 if self._tclCommands is not None:
289 for name in self._tclCommands:
290 #print '- Tkinter: deleted command', name
291 self.tk.deletecommand(name)
292 self._tclCommands = None
293 def deletecommand(self, name):
294 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000295
Fredrik Lundh06d28152000-08-09 18:03:12 +0000296 Delete the Tcl command provided in NAME."""
297 #print '- Tkinter: deleted command', name
298 self.tk.deletecommand(name)
299 try:
300 self._tclCommands.remove(name)
301 except ValueError:
302 pass
303 def tk_strictMotif(self, boolean=None):
304 """Set Tcl internal variable, whether the look and feel
305 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000306
Fredrik Lundh06d28152000-08-09 18:03:12 +0000307 A parameter of 1 means adhere to Motif (e.g. no color
308 change if mouse passes over slider).
309 Returns the set value."""
310 return self.tk.getboolean(self.tk.call(
311 'set', 'tk_strictMotif', boolean))
312 def tk_bisque(self):
313 """Change the color scheme to light brown as used in Tk 3.6 and before."""
314 self.tk.call('tk_bisque')
315 def tk_setPalette(self, *args, **kw):
316 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000317
Fredrik Lundh06d28152000-08-09 18:03:12 +0000318 A single color as argument will cause that all colors of Tk
319 widget elements are derived from this.
320 Alternatively several keyword parameters and its associated
321 colors can be given. The following keywords are valid:
322 activeBackground, foreground, selectColor,
323 activeForeground, highlightBackground, selectBackground,
324 background, highlightColor, selectForeground,
325 disabledForeground, insertBackground, troughColor."""
326 self.tk.call(('tk_setPalette',)
327 + _flatten(args) + _flatten(kw.items()))
328 def tk_menuBar(self, *args):
329 """Do not use. Needed in Tk 3.6 and earlier."""
330 pass # obsolete since Tk 4.0
331 def wait_variable(self, name='PY_VAR'):
332 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000333
Fredrik Lundh06d28152000-08-09 18:03:12 +0000334 A parameter of type IntVar, StringVar, DoubleVar or
335 BooleanVar must be given."""
336 self.tk.call('tkwait', 'variable', name)
337 waitvar = wait_variable # XXX b/w compat
338 def wait_window(self, window=None):
339 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000340
Fredrik Lundh06d28152000-08-09 18:03:12 +0000341 If no parameter is given self is used."""
342 if window == None:
343 window = self
344 self.tk.call('tkwait', 'window', window._w)
345 def wait_visibility(self, window=None):
346 """Wait until the visibility of a WIDGET changes
347 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000348
Fredrik Lundh06d28152000-08-09 18:03:12 +0000349 If no parameter is given self is used."""
350 if window == None:
351 window = self
352 self.tk.call('tkwait', 'visibility', window._w)
353 def setvar(self, name='PY_VAR', value='1'):
354 """Set Tcl variable NAME to VALUE."""
355 self.tk.setvar(name, value)
356 def getvar(self, name='PY_VAR'):
357 """Return value of Tcl variable NAME."""
358 return self.tk.getvar(name)
359 getint = int
360 getdouble = float
361 def getboolean(self, s):
362 """Return 0 or 1 for Tcl boolean values true and false given as parameter."""
363 return self.tk.getboolean(s)
364 def focus_set(self):
365 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000366
Fredrik Lundh06d28152000-08-09 18:03:12 +0000367 If the application currently does not have the focus
368 this widget will get the focus if the application gets
369 the focus through the window manager."""
370 self.tk.call('focus', self._w)
371 focus = focus_set # XXX b/w compat?
372 def focus_force(self):
373 """Direct input focus to this widget even if the
374 application does not have the focus. Use with
375 caution!"""
376 self.tk.call('focus', '-force', self._w)
377 def focus_get(self):
378 """Return the widget which has currently the focus in the
379 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000380
Fredrik Lundh06d28152000-08-09 18:03:12 +0000381 Use focus_displayof to allow working with several
382 displays. Return None if application does not have
383 the focus."""
384 name = self.tk.call('focus')
385 if name == 'none' or not name: return None
386 return self._nametowidget(name)
387 def focus_displayof(self):
388 """Return the widget which has currently the focus on the
389 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000390
Fredrik Lundh06d28152000-08-09 18:03:12 +0000391 Return None if the application does not have the focus."""
392 name = self.tk.call('focus', '-displayof', self._w)
393 if name == 'none' or not name: return None
394 return self._nametowidget(name)
395 def focus_lastfor(self):
396 """Return the widget which would have the focus if top level
397 for this widget gets the focus from the window manager."""
398 name = self.tk.call('focus', '-lastfor', self._w)
399 if name == 'none' or not name: return None
400 return self._nametowidget(name)
401 def tk_focusFollowsMouse(self):
402 """The widget under mouse will get automatically focus. Can not
403 be disabled easily."""
404 self.tk.call('tk_focusFollowsMouse')
405 def tk_focusNext(self):
406 """Return the next widget in the focus order which follows
407 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000408
Fredrik Lundh06d28152000-08-09 18:03:12 +0000409 The focus order first goes to the next child, then to
410 the children of the child recursively and then to the
411 next sibling which is higher in the stacking order. A
412 widget is omitted if it has the takefocus resource set
413 to 0."""
414 name = self.tk.call('tk_focusNext', self._w)
415 if not name: return None
416 return self._nametowidget(name)
417 def tk_focusPrev(self):
418 """Return previous widget in the focus order. See tk_focusNext for details."""
419 name = self.tk.call('tk_focusPrev', self._w)
420 if not name: return None
421 return self._nametowidget(name)
422 def after(self, ms, func=None, *args):
423 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000424
Fredrik Lundh06d28152000-08-09 18:03:12 +0000425 MS specifies the time in milliseconds. FUNC gives the
426 function which shall be called. Additional parameters
427 are given as parameters to the function call. Return
428 identifier to cancel scheduling with after_cancel."""
429 if not func:
430 # I'd rather use time.sleep(ms*0.001)
431 self.tk.call('after', ms)
432 else:
433 # XXX Disgusting hack to clean up after calling func
434 tmp = []
435 def callit(func=func, args=args, self=self, tmp=tmp):
436 try:
437 apply(func, args)
438 finally:
439 try:
440 self.deletecommand(tmp[0])
441 except TclError:
442 pass
443 name = self._register(callit)
444 tmp.append(name)
445 return self.tk.call('after', ms, name)
446 def after_idle(self, func, *args):
447 """Call FUNC once if the Tcl main loop has no event to
448 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000449
Fredrik Lundh06d28152000-08-09 18:03:12 +0000450 Return an identifier to cancel the scheduling with
451 after_cancel."""
452 return apply(self.after, ('idle', func) + args)
453 def after_cancel(self, id):
454 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000455
Fredrik Lundh06d28152000-08-09 18:03:12 +0000456 Identifier returned by after or after_idle must be
457 given as first parameter."""
458 self.tk.call('after', 'cancel', id)
459 def bell(self, displayof=0):
460 """Ring a display's bell."""
461 self.tk.call(('bell',) + self._displayof(displayof))
462 # Clipboard handling:
463 def clipboard_clear(self, **kw):
464 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000465
Fredrik Lundh06d28152000-08-09 18:03:12 +0000466 A widget specified for the optional displayof keyword
467 argument specifies the target display."""
468 if not kw.has_key('displayof'): kw['displayof'] = self._w
469 self.tk.call(('clipboard', 'clear') + self._options(kw))
470 def clipboard_append(self, string, **kw):
471 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000472
Fredrik Lundh06d28152000-08-09 18:03:12 +0000473 A widget specified at the optional displayof keyword
474 argument specifies the target display. The clipboard
475 can be retrieved with selection_get."""
476 if not kw.has_key('displayof'): kw['displayof'] = self._w
477 self.tk.call(('clipboard', 'append') + self._options(kw)
478 + ('--', string))
479 # XXX grab current w/o window argument
480 def grab_current(self):
481 """Return widget which has currently the grab in this application
482 or None."""
483 name = self.tk.call('grab', 'current', self._w)
484 if not name: return None
485 return self._nametowidget(name)
486 def grab_release(self):
487 """Release grab for this widget if currently set."""
488 self.tk.call('grab', 'release', self._w)
489 def grab_set(self):
490 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000491
Fredrik Lundh06d28152000-08-09 18:03:12 +0000492 A grab directs all events to this and descendant
493 widgets in the application."""
494 self.tk.call('grab', 'set', self._w)
495 def grab_set_global(self):
496 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000497
Fredrik Lundh06d28152000-08-09 18:03:12 +0000498 A global grab directs all events to this and
499 descendant widgets on the display. Use with caution -
500 other applications do not get events anymore."""
501 self.tk.call('grab', 'set', '-global', self._w)
502 def grab_status(self):
503 """Return None, "local" or "global" if this widget has
504 no, a local or a global grab."""
505 status = self.tk.call('grab', 'status', self._w)
506 if status == 'none': status = None
507 return status
508 def lower(self, belowThis=None):
509 """Lower this widget in the stacking order."""
510 self.tk.call('lower', self._w, belowThis)
511 def option_add(self, pattern, value, priority = None):
512 """Set a VALUE (second parameter) for an option
513 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000514
Fredrik Lundh06d28152000-08-09 18:03:12 +0000515 An optional third parameter gives the numeric priority
516 (defaults to 80)."""
517 self.tk.call('option', 'add', pattern, value, priority)
518 def option_clear(self):
519 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000520
Fredrik Lundh06d28152000-08-09 18:03:12 +0000521 It will be reloaded if option_add is called."""
522 self.tk.call('option', 'clear')
523 def option_get(self, name, className):
524 """Return the value for an option NAME for this widget
525 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000526
Fredrik Lundh06d28152000-08-09 18:03:12 +0000527 Values with higher priority override lower values."""
528 return self.tk.call('option', 'get', self._w, name, className)
529 def option_readfile(self, fileName, priority = None):
530 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000531
Fredrik Lundh06d28152000-08-09 18:03:12 +0000532 An optional second parameter gives the numeric
533 priority."""
534 self.tk.call('option', 'readfile', fileName, priority)
535 def selection_clear(self, **kw):
536 """Clear the current X selection."""
537 if not kw.has_key('displayof'): kw['displayof'] = self._w
538 self.tk.call(('selection', 'clear') + self._options(kw))
539 def selection_get(self, **kw):
540 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000541
Fredrik Lundh06d28152000-08-09 18:03:12 +0000542 A keyword parameter selection specifies the name of
543 the selection and defaults to PRIMARY. A keyword
544 parameter displayof specifies a widget on the display
545 to use."""
546 if not kw.has_key('displayof'): kw['displayof'] = self._w
547 return self.tk.call(('selection', 'get') + self._options(kw))
548 def selection_handle(self, command, **kw):
549 """Specify a function COMMAND to call if the X
550 selection owned by this widget is queried by another
551 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000552
Fredrik Lundh06d28152000-08-09 18:03:12 +0000553 This function must return the contents of the
554 selection. The function will be called with the
555 arguments OFFSET and LENGTH which allows the chunking
556 of very long selections. The following keyword
557 parameters can be provided:
558 selection - name of the selection (default PRIMARY),
559 type - type of the selection (e.g. STRING, FILE_NAME)."""
560 name = self._register(command)
561 self.tk.call(('selection', 'handle') + self._options(kw)
562 + (self._w, name))
563 def selection_own(self, **kw):
564 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000565
Fredrik Lundh06d28152000-08-09 18:03:12 +0000566 A keyword parameter selection specifies the name of
567 the selection (default PRIMARY)."""
568 self.tk.call(('selection', 'own') +
569 self._options(kw) + (self._w,))
570 def selection_own_get(self, **kw):
571 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000572
Fredrik Lundh06d28152000-08-09 18:03:12 +0000573 The following keyword parameter can
574 be provided:
575 selection - name of the selection (default PRIMARY),
576 type - type of the selection (e.g. STRING, FILE_NAME)."""
577 if not kw.has_key('displayof'): kw['displayof'] = self._w
578 name = self.tk.call(('selection', 'own') + self._options(kw))
579 if not name: return None
580 return self._nametowidget(name)
581 def send(self, interp, cmd, *args):
582 """Send Tcl command CMD to different interpreter INTERP to be executed."""
583 return self.tk.call(('send', interp, cmd) + args)
584 def lower(self, belowThis=None):
585 """Lower this widget in the stacking order."""
586 self.tk.call('lower', self._w, belowThis)
587 def tkraise(self, aboveThis=None):
588 """Raise this widget in the stacking order."""
589 self.tk.call('raise', self._w, aboveThis)
590 lift = tkraise
591 def colormodel(self, value=None):
592 """Useless. Not implemented in Tk."""
593 return self.tk.call('tk', 'colormodel', self._w, value)
594 def winfo_atom(self, name, displayof=0):
595 """Return integer which represents atom NAME."""
596 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
597 return getint(self.tk.call(args))
598 def winfo_atomname(self, id, displayof=0):
599 """Return name of atom with identifier ID."""
600 args = ('winfo', 'atomname') \
601 + self._displayof(displayof) + (id,)
602 return self.tk.call(args)
603 def winfo_cells(self):
604 """Return number of cells in the colormap for this widget."""
605 return getint(
606 self.tk.call('winfo', 'cells', self._w))
607 def winfo_children(self):
608 """Return a list of all widgets which are children of this widget."""
609 return map(self._nametowidget,
610 self.tk.splitlist(self.tk.call(
611 'winfo', 'children', self._w)))
612 def winfo_class(self):
613 """Return window class name of this widget."""
614 return self.tk.call('winfo', 'class', self._w)
615 def winfo_colormapfull(self):
616 """Return true if at the last color request the colormap was full."""
617 return self.tk.getboolean(
618 self.tk.call('winfo', 'colormapfull', self._w))
619 def winfo_containing(self, rootX, rootY, displayof=0):
620 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
621 args = ('winfo', 'containing') \
622 + self._displayof(displayof) + (rootX, rootY)
623 name = self.tk.call(args)
624 if not name: return None
625 return self._nametowidget(name)
626 def winfo_depth(self):
627 """Return the number of bits per pixel."""
628 return getint(self.tk.call('winfo', 'depth', self._w))
629 def winfo_exists(self):
630 """Return true if this widget exists."""
631 return getint(
632 self.tk.call('winfo', 'exists', self._w))
633 def winfo_fpixels(self, number):
634 """Return the number of pixels for the given distance NUMBER
635 (e.g. "3c") as float."""
636 return getdouble(self.tk.call(
637 'winfo', 'fpixels', self._w, number))
638 def winfo_geometry(self):
639 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
640 return self.tk.call('winfo', 'geometry', self._w)
641 def winfo_height(self):
642 """Return height of this widget."""
643 return getint(
644 self.tk.call('winfo', 'height', self._w))
645 def winfo_id(self):
646 """Return identifier ID for this widget."""
647 return self.tk.getint(
648 self.tk.call('winfo', 'id', self._w))
649 def winfo_interps(self, displayof=0):
650 """Return the name of all Tcl interpreters for this display."""
651 args = ('winfo', 'interps') + self._displayof(displayof)
652 return self.tk.splitlist(self.tk.call(args))
653 def winfo_ismapped(self):
654 """Return true if this widget is mapped."""
655 return getint(
656 self.tk.call('winfo', 'ismapped', self._w))
657 def winfo_manager(self):
658 """Return the window mananger name for this widget."""
659 return self.tk.call('winfo', 'manager', self._w)
660 def winfo_name(self):
661 """Return the name of this widget."""
662 return self.tk.call('winfo', 'name', self._w)
663 def winfo_parent(self):
664 """Return the name of the parent of this widget."""
665 return self.tk.call('winfo', 'parent', self._w)
666 def winfo_pathname(self, id, displayof=0):
667 """Return the pathname of the widget given by ID."""
668 args = ('winfo', 'pathname') \
669 + self._displayof(displayof) + (id,)
670 return self.tk.call(args)
671 def winfo_pixels(self, number):
672 """Rounded integer value of winfo_fpixels."""
673 return getint(
674 self.tk.call('winfo', 'pixels', self._w, number))
675 def winfo_pointerx(self):
676 """Return the x coordinate of the pointer on the root window."""
677 return getint(
678 self.tk.call('winfo', 'pointerx', self._w))
679 def winfo_pointerxy(self):
680 """Return a tuple of x and y coordinates of the pointer on the root window."""
681 return self._getints(
682 self.tk.call('winfo', 'pointerxy', self._w))
683 def winfo_pointery(self):
684 """Return the y coordinate of the pointer on the root window."""
685 return getint(
686 self.tk.call('winfo', 'pointery', self._w))
687 def winfo_reqheight(self):
688 """Return requested height of this widget."""
689 return getint(
690 self.tk.call('winfo', 'reqheight', self._w))
691 def winfo_reqwidth(self):
692 """Return requested width of this widget."""
693 return getint(
694 self.tk.call('winfo', 'reqwidth', self._w))
695 def winfo_rgb(self, color):
696 """Return tuple of decimal values for red, green, blue for
697 COLOR in this widget."""
698 return self._getints(
699 self.tk.call('winfo', 'rgb', self._w, color))
700 def winfo_rootx(self):
701 """Return x coordinate of upper left corner of this widget on the
702 root window."""
703 return getint(
704 self.tk.call('winfo', 'rootx', self._w))
705 def winfo_rooty(self):
706 """Return y coordinate of upper left corner of this widget on the
707 root window."""
708 return getint(
709 self.tk.call('winfo', 'rooty', self._w))
710 def winfo_screen(self):
711 """Return the screen name of this widget."""
712 return self.tk.call('winfo', 'screen', self._w)
713 def winfo_screencells(self):
714 """Return the number of the cells in the colormap of the screen
715 of this widget."""
716 return getint(
717 self.tk.call('winfo', 'screencells', self._w))
718 def winfo_screendepth(self):
719 """Return the number of bits per pixel of the root window of the
720 screen of this widget."""
721 return getint(
722 self.tk.call('winfo', 'screendepth', self._w))
723 def winfo_screenheight(self):
724 """Return the number of pixels of the height of the screen of this widget
725 in pixel."""
726 return getint(
727 self.tk.call('winfo', 'screenheight', self._w))
728 def winfo_screenmmheight(self):
729 """Return the number of pixels of the height of the screen of
730 this widget in mm."""
731 return getint(
732 self.tk.call('winfo', 'screenmmheight', self._w))
733 def winfo_screenmmwidth(self):
734 """Return the number of pixels of the width of the screen of
735 this widget in mm."""
736 return getint(
737 self.tk.call('winfo', 'screenmmwidth', self._w))
738 def winfo_screenvisual(self):
739 """Return one of the strings directcolor, grayscale, pseudocolor,
740 staticcolor, staticgray, or truecolor for the default
741 colormodel of this screen."""
742 return self.tk.call('winfo', 'screenvisual', self._w)
743 def winfo_screenwidth(self):
744 """Return the number of pixels of the width of the screen of
745 this widget in pixel."""
746 return getint(
747 self.tk.call('winfo', 'screenwidth', self._w))
748 def winfo_server(self):
749 """Return information of the X-Server of the screen of this widget in
750 the form "XmajorRminor vendor vendorVersion"."""
751 return self.tk.call('winfo', 'server', self._w)
752 def winfo_toplevel(self):
753 """Return the toplevel widget of this widget."""
754 return self._nametowidget(self.tk.call(
755 'winfo', 'toplevel', self._w))
756 def winfo_viewable(self):
757 """Return true if the widget and all its higher ancestors are mapped."""
758 return getint(
759 self.tk.call('winfo', 'viewable', self._w))
760 def winfo_visual(self):
761 """Return one of the strings directcolor, grayscale, pseudocolor,
762 staticcolor, staticgray, or truecolor for the
763 colormodel of this widget."""
764 return self.tk.call('winfo', 'visual', self._w)
765 def winfo_visualid(self):
766 """Return the X identifier for the visual for this widget."""
767 return self.tk.call('winfo', 'visualid', self._w)
768 def winfo_visualsavailable(self, includeids=0):
769 """Return a list of all visuals available for the screen
770 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000771
Fredrik Lundh06d28152000-08-09 18:03:12 +0000772 Each item in the list consists of a visual name (see winfo_visual), a
773 depth and if INCLUDEIDS=1 is given also the X identifier."""
774 data = self.tk.split(
775 self.tk.call('winfo', 'visualsavailable', self._w,
776 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000777 if type(data) is StringType:
778 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000779 return map(self.__winfo_parseitem, data)
780 def __winfo_parseitem(self, t):
781 """Internal function."""
782 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
783 def __winfo_getint(self, x):
784 """Internal function."""
785 return _string.atoi(x, 0)
786 def winfo_vrootheight(self):
787 """Return the height of the virtual root window associated with this
788 widget in pixels. If there is no virtual root window return the
789 height of the screen."""
790 return getint(
791 self.tk.call('winfo', 'vrootheight', self._w))
792 def winfo_vrootwidth(self):
793 """Return the width of the virtual root window associated with this
794 widget in pixel. If there is no virtual root window return the
795 width of the screen."""
796 return getint(
797 self.tk.call('winfo', 'vrootwidth', self._w))
798 def winfo_vrootx(self):
799 """Return the x offset of the virtual root relative to the root
800 window of the screen of this widget."""
801 return getint(
802 self.tk.call('winfo', 'vrootx', self._w))
803 def winfo_vrooty(self):
804 """Return the y offset of the virtual root relative to the root
805 window of the screen of this widget."""
806 return getint(
807 self.tk.call('winfo', 'vrooty', self._w))
808 def winfo_width(self):
809 """Return the width of this widget."""
810 return getint(
811 self.tk.call('winfo', 'width', self._w))
812 def winfo_x(self):
813 """Return the x coordinate of the upper left corner of this widget
814 in the parent."""
815 return getint(
816 self.tk.call('winfo', 'x', self._w))
817 def winfo_y(self):
818 """Return the y coordinate of the upper left corner of this widget
819 in the parent."""
820 return getint(
821 self.tk.call('winfo', 'y', self._w))
822 def update(self):
823 """Enter event loop until all pending events have been processed by Tcl."""
824 self.tk.call('update')
825 def update_idletasks(self):
826 """Enter event loop until all idle callbacks have been called. This
827 will update the display of windows but not process events caused by
828 the user."""
829 self.tk.call('update', 'idletasks')
830 def bindtags(self, tagList=None):
831 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000832
Fredrik Lundh06d28152000-08-09 18:03:12 +0000833 With no argument return the list of all bindtags associated with
834 this widget. With a list of strings as argument the bindtags are
835 set to this list. The bindtags determine in which order events are
836 processed (see bind)."""
837 if tagList is None:
838 return self.tk.splitlist(
839 self.tk.call('bindtags', self._w))
840 else:
841 self.tk.call('bindtags', self._w, tagList)
842 def _bind(self, what, sequence, func, add, needcleanup=1):
843 """Internal function."""
844 if type(func) is StringType:
845 self.tk.call(what + (sequence, func))
846 elif func:
847 funcid = self._register(func, self._substitute,
848 needcleanup)
849 cmd = ('%sif {"[%s %s]" == "break"} break\n'
850 %
851 (add and '+' or '',
852 funcid,
853 _string.join(self._subst_format)))
854 self.tk.call(what + (sequence, cmd))
855 return funcid
856 elif sequence:
857 return self.tk.call(what + (sequence,))
858 else:
859 return self.tk.splitlist(self.tk.call(what))
860 def bind(self, sequence=None, func=None, add=None):
861 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000862
Fredrik Lundh06d28152000-08-09 18:03:12 +0000863 SEQUENCE is a string of concatenated event
864 patterns. An event pattern is of the form
865 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
866 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
867 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
868 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
869 Mod1, M1. TYPE is one of Activate, Enter, Map,
870 ButtonPress, Button, Expose, Motion, ButtonRelease
871 FocusIn, MouseWheel, Circulate, FocusOut, Property,
872 Colormap, Gravity Reparent, Configure, KeyPress, Key,
873 Unmap, Deactivate, KeyRelease Visibility, Destroy,
874 Leave and DETAIL is the button number for ButtonPress,
875 ButtonRelease and DETAIL is the Keysym for KeyPress and
876 KeyRelease. Examples are
877 <Control-Button-1> for pressing Control and mouse button 1 or
878 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
879 An event pattern can also be a virtual event of the form
880 <<AString>> where AString can be arbitrary. This
881 event can be generated by event_generate.
882 If events are concatenated they must appear shortly
883 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000884
Fredrik Lundh06d28152000-08-09 18:03:12 +0000885 FUNC will be called if the event sequence occurs with an
886 instance of Event as argument. If the return value of FUNC is
887 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000888
Fredrik Lundh06d28152000-08-09 18:03:12 +0000889 An additional boolean parameter ADD specifies whether FUNC will
890 be called additionally to the other bound function or whether
891 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000892
Fredrik Lundh06d28152000-08-09 18:03:12 +0000893 Bind will return an identifier to allow deletion of the bound function with
894 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000895
Fredrik Lundh06d28152000-08-09 18:03:12 +0000896 If FUNC or SEQUENCE is omitted the bound function or list
897 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000898
Fredrik Lundh06d28152000-08-09 18:03:12 +0000899 return self._bind(('bind', self._w), sequence, func, add)
900 def unbind(self, sequence, funcid=None):
901 """Unbind for this widget for event SEQUENCE the
902 function identified with FUNCID."""
903 self.tk.call('bind', self._w, sequence, '')
904 if funcid:
905 self.deletecommand(funcid)
906 def bind_all(self, sequence=None, func=None, add=None):
907 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
908 An additional boolean parameter ADD specifies whether FUNC will
909 be called additionally to the other bound function or whether
910 it will replace the previous function. See bind for the return value."""
911 return self._bind(('bind', 'all'), sequence, func, add, 0)
912 def unbind_all(self, sequence):
913 """Unbind for all widgets for event SEQUENCE all functions."""
914 self.tk.call('bind', 'all' , sequence, '')
915 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000916
Fredrik Lundh06d28152000-08-09 18:03:12 +0000917 """Bind to widgets with bindtag CLASSNAME at event
918 SEQUENCE a call of function FUNC. An additional
919 boolean parameter ADD specifies whether FUNC will be
920 called additionally to the other bound function or
921 whether it will replace the previous function. See bind for
922 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000923
Fredrik Lundh06d28152000-08-09 18:03:12 +0000924 return self._bind(('bind', className), sequence, func, add, 0)
925 def unbind_class(self, className, sequence):
926 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
927 all functions."""
928 self.tk.call('bind', className , sequence, '')
929 def mainloop(self, n=0):
930 """Call the mainloop of Tk."""
931 self.tk.mainloop(n)
932 def quit(self):
933 """Quit the Tcl interpreter. All widgets will be destroyed."""
934 self.tk.quit()
935 def _getints(self, string):
936 """Internal function."""
937 if string:
938 return tuple(map(getint, self.tk.splitlist(string)))
939 def _getdoubles(self, string):
940 """Internal function."""
941 if string:
942 return tuple(map(getdouble, self.tk.splitlist(string)))
943 def _getboolean(self, string):
944 """Internal function."""
945 if string:
946 return self.tk.getboolean(string)
947 def _displayof(self, displayof):
948 """Internal function."""
949 if displayof:
950 return ('-displayof', displayof)
951 if displayof is None:
952 return ('-displayof', self._w)
953 return ()
954 def _options(self, cnf, kw = None):
955 """Internal function."""
956 if kw:
957 cnf = _cnfmerge((cnf, kw))
958 else:
959 cnf = _cnfmerge(cnf)
960 res = ()
961 for k, v in cnf.items():
962 if v is not None:
963 if k[-1] == '_': k = k[:-1]
964 if callable(v):
965 v = self._register(v)
966 res = res + ('-'+k, v)
967 return res
968 def nametowidget(self, name):
969 """Return the Tkinter instance of a widget identified by
970 its Tcl name NAME."""
971 w = self
972 if name[0] == '.':
973 w = w._root()
974 name = name[1:]
975 find = _string.find
976 while name:
977 i = find(name, '.')
978 if i >= 0:
979 name, tail = name[:i], name[i+1:]
980 else:
981 tail = ''
982 w = w.children[name]
983 name = tail
984 return w
985 _nametowidget = nametowidget
986 def _register(self, func, subst=None, needcleanup=1):
987 """Return a newly created Tcl function. If this
988 function is called, the Python function FUNC will
989 be executed. An optional function SUBST can
990 be given which will be executed before FUNC."""
991 f = CallWrapper(func, subst, self).__call__
992 name = `id(f)`
993 try:
994 func = func.im_func
995 except AttributeError:
996 pass
997 try:
998 name = name + func.__name__
999 except AttributeError:
1000 pass
1001 self.tk.createcommand(name, f)
1002 if needcleanup:
1003 if self._tclCommands is None:
1004 self._tclCommands = []
1005 self._tclCommands.append(name)
1006 #print '+ Tkinter created command', name
1007 return name
1008 register = _register
1009 def _root(self):
1010 """Internal function."""
1011 w = self
1012 while w.master: w = w.master
1013 return w
1014 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1015 '%s', '%t', '%w', '%x', '%y',
1016 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1017 def _substitute(self, *args):
1018 """Internal function."""
1019 if len(args) != len(self._subst_format): return args
1020 getboolean = self.tk.getboolean
1021 getint = int
1022 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1023 # Missing: (a, c, d, m, o, v, B, R)
1024 e = Event()
1025 e.serial = getint(nsign)
1026 e.num = getint(b)
1027 try: e.focus = getboolean(f)
1028 except TclError: pass
1029 e.height = getint(h)
1030 e.keycode = getint(k)
1031 # For Visibility events, event state is a string and
1032 # not an integer:
1033 try:
1034 e.state = getint(s)
1035 except ValueError:
1036 e.state = s
1037 e.time = getint(t)
1038 e.width = getint(w)
1039 e.x = getint(x)
1040 e.y = getint(y)
1041 e.char = A
1042 try: e.send_event = getboolean(E)
1043 except TclError: pass
1044 e.keysym = K
1045 e.keysym_num = getint(N)
1046 e.type = T
1047 try:
1048 e.widget = self._nametowidget(W)
1049 except KeyError:
1050 e.widget = W
1051 e.x_root = getint(X)
1052 e.y_root = getint(Y)
1053 e.delta = getint(D)
1054 return (e,)
1055 def _report_exception(self):
1056 """Internal function."""
1057 import sys
1058 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1059 root = self._root()
1060 root.report_callback_exception(exc, val, tb)
1061 # These used to be defined in Widget:
1062 def configure(self, cnf=None, **kw):
1063 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001064
Fredrik Lundh06d28152000-08-09 18:03:12 +00001065 The values for resources are specified as keyword
1066 arguments. To get an overview about
1067 the allowed keyword arguments call the method keys.
1068 """
1069 # XXX ought to generalize this so tag_config etc. can use it
1070 if kw:
1071 cnf = _cnfmerge((cnf, kw))
1072 elif cnf:
1073 cnf = _cnfmerge(cnf)
1074 if cnf is None:
1075 cnf = {}
1076 for x in self.tk.split(
1077 self.tk.call(self._w, 'configure')):
1078 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1079 return cnf
1080 if type(cnf) is StringType:
1081 x = self.tk.split(self.tk.call(
1082 self._w, 'configure', '-'+cnf))
1083 return (x[0][1:],) + x[1:]
1084 self.tk.call((self._w, 'configure')
1085 + self._options(cnf))
1086 config = configure
1087 def cget(self, key):
1088 """Return the resource value for a KEY given as string."""
1089 return self.tk.call(self._w, 'cget', '-' + key)
1090 __getitem__ = cget
1091 def __setitem__(self, key, value):
1092 self.configure({key: value})
1093 def keys(self):
1094 """Return a list of all resource names of this widget."""
1095 return map(lambda x: x[0][1:],
1096 self.tk.split(self.tk.call(self._w, 'configure')))
1097 def __str__(self):
1098 """Return the window path name of this widget."""
1099 return self._w
1100 # Pack methods that apply to the master
1101 _noarg_ = ['_noarg_']
1102 def pack_propagate(self, flag=_noarg_):
1103 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001104
Fredrik Lundh06d28152000-08-09 18:03:12 +00001105 A boolean argument specifies whether the geometry information
1106 of the slaves will determine the size of this widget. If no argument
1107 is given the current setting will be returned.
1108 """
1109 if flag is Misc._noarg_:
1110 return self._getboolean(self.tk.call(
1111 'pack', 'propagate', self._w))
1112 else:
1113 self.tk.call('pack', 'propagate', self._w, flag)
1114 propagate = pack_propagate
1115 def pack_slaves(self):
1116 """Return a list of all slaves of this widget
1117 in its packing order."""
1118 return map(self._nametowidget,
1119 self.tk.splitlist(
1120 self.tk.call('pack', 'slaves', self._w)))
1121 slaves = pack_slaves
1122 # Place method that applies to the master
1123 def place_slaves(self):
1124 """Return a list of all slaves of this widget
1125 in its packing order."""
1126 return map(self._nametowidget,
1127 self.tk.splitlist(
1128 self.tk.call(
1129 'place', 'slaves', self._w)))
1130 # Grid methods that apply to the master
1131 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1132 """Return a tuple of integer coordinates for the bounding
1133 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001134
Fredrik Lundh06d28152000-08-09 18:03:12 +00001135 If COLUMN, ROW is given the bounding box applies from
1136 the cell with row and column 0 to the specified
1137 cell. If COL2 and ROW2 are given the bounding box
1138 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001139
Fredrik Lundh06d28152000-08-09 18:03:12 +00001140 The returned integers specify the offset of the upper left
1141 corner in the master widget and the width and height.
1142 """
1143 args = ('grid', 'bbox', self._w)
1144 if column is not None and row is not None:
1145 args = args + (column, row)
1146 if col2 is not None and row2 is not None:
1147 args = args + (col2, row2)
1148 return self._getints(apply(self.tk.call, args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001149
Fredrik Lundh06d28152000-08-09 18:03:12 +00001150 bbox = grid_bbox
1151 def _grid_configure(self, command, index, cnf, kw):
1152 """Internal function."""
1153 if type(cnf) is StringType and not kw:
1154 if cnf[-1:] == '_':
1155 cnf = cnf[:-1]
1156 if cnf[:1] != '-':
1157 cnf = '-'+cnf
1158 options = (cnf,)
1159 else:
1160 options = self._options(cnf, kw)
1161 if not options:
1162 res = self.tk.call('grid',
1163 command, self._w, index)
1164 words = self.tk.splitlist(res)
1165 dict = {}
1166 for i in range(0, len(words), 2):
1167 key = words[i][1:]
1168 value = words[i+1]
1169 if not value:
1170 value = None
1171 elif '.' in value:
1172 value = getdouble(value)
1173 else:
1174 value = getint(value)
1175 dict[key] = value
1176 return dict
1177 res = self.tk.call(
1178 ('grid', command, self._w, index)
1179 + options)
1180 if len(options) == 1:
1181 if not res: return None
1182 # In Tk 7.5, -width can be a float
1183 if '.' in res: return getdouble(res)
1184 return getint(res)
1185 def grid_columnconfigure(self, index, cnf={}, **kw):
1186 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001187
Fredrik Lundh06d28152000-08-09 18:03:12 +00001188 Valid resources are minsize (minimum size of the column),
1189 weight (how much does additional space propagate to this column)
1190 and pad (how much space to let additionally)."""
1191 return self._grid_configure('columnconfigure', index, cnf, kw)
1192 columnconfigure = grid_columnconfigure
1193 def grid_propagate(self, flag=_noarg_):
1194 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001195
Fredrik Lundh06d28152000-08-09 18:03:12 +00001196 A boolean argument specifies whether the geometry information
1197 of the slaves will determine the size of this widget. If no argument
1198 is given, the current setting will be returned.
1199 """
1200 if flag is Misc._noarg_:
1201 return self._getboolean(self.tk.call(
1202 'grid', 'propagate', self._w))
1203 else:
1204 self.tk.call('grid', 'propagate', self._w, flag)
1205 def grid_rowconfigure(self, index, cnf={}, **kw):
1206 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001207
Fredrik Lundh06d28152000-08-09 18:03:12 +00001208 Valid resources are minsize (minimum size of the row),
1209 weight (how much does additional space propagate to this row)
1210 and pad (how much space to let additionally)."""
1211 return self._grid_configure('rowconfigure', index, cnf, kw)
1212 rowconfigure = grid_rowconfigure
1213 def grid_size(self):
1214 """Return a tuple of the number of column and rows in the grid."""
1215 return self._getints(
1216 self.tk.call('grid', 'size', self._w)) or None
1217 size = grid_size
1218 def grid_slaves(self, row=None, column=None):
1219 """Return a list of all slaves of this widget
1220 in its packing order."""
1221 args = ()
1222 if row is not None:
1223 args = args + ('-row', row)
1224 if column is not None:
1225 args = args + ('-column', column)
1226 return map(self._nametowidget,
1227 self.tk.splitlist(self.tk.call(
1228 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001229
Fredrik Lundh06d28152000-08-09 18:03:12 +00001230 # Support for the "event" command, new in Tk 4.2.
1231 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001232
Fredrik Lundh06d28152000-08-09 18:03:12 +00001233 def event_add(self, virtual, *sequences):
1234 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1235 to an event SEQUENCE such that the virtual event is triggered
1236 whenever SEQUENCE occurs."""
1237 args = ('event', 'add', virtual) + sequences
1238 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001239
Fredrik Lundh06d28152000-08-09 18:03:12 +00001240 def event_delete(self, virtual, *sequences):
1241 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1242 args = ('event', 'delete', virtual) + sequences
1243 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001244
Fredrik Lundh06d28152000-08-09 18:03:12 +00001245 def event_generate(self, sequence, **kw):
1246 """Generate an event SEQUENCE. Additional
1247 keyword arguments specify parameter of the event
1248 (e.g. x, y, rootx, rooty)."""
1249 args = ('event', 'generate', self._w, sequence)
1250 for k, v in kw.items():
1251 args = args + ('-%s' % k, str(v))
1252 self.tk.call(args)
1253
1254 def event_info(self, virtual=None):
1255 """Return a list of all virtual events or the information
1256 about the SEQUENCE bound to the virtual event VIRTUAL."""
1257 return self.tk.splitlist(
1258 self.tk.call('event', 'info', virtual))
1259
1260 # Image related commands
1261
1262 def image_names(self):
1263 """Return a list of all existing image names."""
1264 return self.tk.call('image', 'names')
1265
1266 def image_types(self):
1267 """Return a list of all available image types (e.g. phote bitmap)."""
1268 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001269
Guido van Rossum80f8be81997-12-02 19:51:39 +00001270
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001271class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001272 """Internal class. Stores function to call when some user
1273 defined Tcl function is called e.g. after an event occurred."""
1274 def __init__(self, func, subst, widget):
1275 """Store FUNC, SUBST and WIDGET as members."""
1276 self.func = func
1277 self.subst = subst
1278 self.widget = widget
1279 def __call__(self, *args):
1280 """Apply first function SUBST to arguments, than FUNC."""
1281 try:
1282 if self.subst:
1283 args = apply(self.subst, args)
1284 return apply(self.func, args)
1285 except SystemExit, msg:
1286 raise SystemExit, msg
1287 except:
1288 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001289
Guido van Rossume365a591998-05-01 19:48:20 +00001290
Guido van Rossum18468821994-06-20 07:49:28 +00001291class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001292 """Provides functions for the communication with the window manager."""
1293 def wm_aspect(self,
1294 minNumer=None, minDenom=None,
1295 maxNumer=None, maxDenom=None):
1296 """Instruct the window manager to set the aspect ratio (width/height)
1297 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1298 of the actual values if no argument is given."""
1299 return self._getints(
1300 self.tk.call('wm', 'aspect', self._w,
1301 minNumer, minDenom,
1302 maxNumer, maxDenom))
1303 aspect = wm_aspect
1304 def wm_client(self, name=None):
1305 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1306 current value."""
1307 return self.tk.call('wm', 'client', self._w, name)
1308 client = wm_client
1309 def wm_colormapwindows(self, *wlist):
1310 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1311 of this widget. This list contains windows whose colormaps differ from their
1312 parents. Return current list of widgets if WLIST is empty."""
1313 if len(wlist) > 1:
1314 wlist = (wlist,) # Tk needs a list of windows here
1315 args = ('wm', 'colormapwindows', self._w) + wlist
1316 return map(self._nametowidget, self.tk.call(args))
1317 colormapwindows = wm_colormapwindows
1318 def wm_command(self, value=None):
1319 """Store VALUE in WM_COMMAND property. It is the command
1320 which shall be used to invoke the application. Return current
1321 command if VALUE is None."""
1322 return self.tk.call('wm', 'command', self._w, value)
1323 command = wm_command
1324 def wm_deiconify(self):
1325 """Deiconify this widget. If it was never mapped it will not be mapped.
1326 On Windows it will raise this widget and give it the focus."""
1327 return self.tk.call('wm', 'deiconify', self._w)
1328 deiconify = wm_deiconify
1329 def wm_focusmodel(self, model=None):
1330 """Set focus model to MODEL. "active" means that this widget will claim
1331 the focus itself, "passive" means that the window manager shall give
1332 the focus. Return current focus model if MODEL is None."""
1333 return self.tk.call('wm', 'focusmodel', self._w, model)
1334 focusmodel = wm_focusmodel
1335 def wm_frame(self):
1336 """Return identifier for decorative frame of this widget if present."""
1337 return self.tk.call('wm', 'frame', self._w)
1338 frame = wm_frame
1339 def wm_geometry(self, newGeometry=None):
1340 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1341 current value if None is given."""
1342 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1343 geometry = wm_geometry
1344 def wm_grid(self,
1345 baseWidth=None, baseHeight=None,
1346 widthInc=None, heightInc=None):
1347 """Instruct the window manager that this widget shall only be
1348 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1349 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1350 number of grid units requested in Tk_GeometryRequest."""
1351 return self._getints(self.tk.call(
1352 'wm', 'grid', self._w,
1353 baseWidth, baseHeight, widthInc, heightInc))
1354 grid = wm_grid
1355 def wm_group(self, pathName=None):
1356 """Set the group leader widgets for related widgets to PATHNAME. Return
1357 the group leader of this widget if None is given."""
1358 return self.tk.call('wm', 'group', self._w, pathName)
1359 group = wm_group
1360 def wm_iconbitmap(self, bitmap=None):
1361 """Set bitmap for the iconified widget to BITMAP. Return
1362 the bitmap if None is given."""
1363 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1364 iconbitmap = wm_iconbitmap
1365 def wm_iconify(self):
1366 """Display widget as icon."""
1367 return self.tk.call('wm', 'iconify', self._w)
1368 iconify = wm_iconify
1369 def wm_iconmask(self, bitmap=None):
1370 """Set mask for the icon bitmap of this widget. Return the
1371 mask if None is given."""
1372 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1373 iconmask = wm_iconmask
1374 def wm_iconname(self, newName=None):
1375 """Set the name of the icon for this widget. Return the name if
1376 None is given."""
1377 return self.tk.call('wm', 'iconname', self._w, newName)
1378 iconname = wm_iconname
1379 def wm_iconposition(self, x=None, y=None):
1380 """Set the position of the icon of this widget to X and Y. Return
1381 a tuple of the current values of X and X if None is given."""
1382 return self._getints(self.tk.call(
1383 'wm', 'iconposition', self._w, x, y))
1384 iconposition = wm_iconposition
1385 def wm_iconwindow(self, pathName=None):
1386 """Set widget PATHNAME to be displayed instead of icon. Return the current
1387 value if None is given."""
1388 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1389 iconwindow = wm_iconwindow
1390 def wm_maxsize(self, width=None, height=None):
1391 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1392 the values are given in grid units. Return the current values if None
1393 is given."""
1394 return self._getints(self.tk.call(
1395 'wm', 'maxsize', self._w, width, height))
1396 maxsize = wm_maxsize
1397 def wm_minsize(self, width=None, height=None):
1398 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1399 the values are given in grid units. Return the current values if None
1400 is given."""
1401 return self._getints(self.tk.call(
1402 'wm', 'minsize', self._w, width, height))
1403 minsize = wm_minsize
1404 def wm_overrideredirect(self, boolean=None):
1405 """Instruct the window manager to ignore this widget
1406 if BOOLEAN is given with 1. Return the current value if None
1407 is given."""
1408 return self._getboolean(self.tk.call(
1409 'wm', 'overrideredirect', self._w, boolean))
1410 overrideredirect = wm_overrideredirect
1411 def wm_positionfrom(self, who=None):
1412 """Instruct the window manager that the position of this widget shall
1413 be defined by the user if WHO is "user", and by its own policy if WHO is
1414 "program"."""
1415 return self.tk.call('wm', 'positionfrom', self._w, who)
1416 positionfrom = wm_positionfrom
1417 def wm_protocol(self, name=None, func=None):
1418 """Bind function FUNC to command NAME for this widget.
1419 Return the function bound to NAME if None is given. NAME could be
1420 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1421 if callable(func):
1422 command = self._register(func)
1423 else:
1424 command = func
1425 return self.tk.call(
1426 'wm', 'protocol', self._w, name, command)
1427 protocol = wm_protocol
1428 def wm_resizable(self, width=None, height=None):
1429 """Instruct the window manager whether this width can be resized
1430 in WIDTH or HEIGHT. Both values are boolean values."""
1431 return self.tk.call('wm', 'resizable', self._w, width, height)
1432 resizable = wm_resizable
1433 def wm_sizefrom(self, who=None):
1434 """Instruct the window manager that the size of this widget shall
1435 be defined by the user if WHO is "user", and by its own policy if WHO is
1436 "program"."""
1437 return self.tk.call('wm', 'sizefrom', self._w, who)
1438 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001439 def wm_state(self, newstate=None):
1440 """Query or set the state of this widget as one of normal, icon,
1441 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1442 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001443 state = wm_state
1444 def wm_title(self, string=None):
1445 """Set the title of this widget."""
1446 return self.tk.call('wm', 'title', self._w, string)
1447 title = wm_title
1448 def wm_transient(self, master=None):
1449 """Instruct the window manager that this widget is transient
1450 with regard to widget MASTER."""
1451 return self.tk.call('wm', 'transient', self._w, master)
1452 transient = wm_transient
1453 def wm_withdraw(self):
1454 """Withdraw this widget from the screen such that it is unmapped
1455 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1456 return self.tk.call('wm', 'withdraw', self._w)
1457 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001458
Guido van Rossum18468821994-06-20 07:49:28 +00001459
1460class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001461 """Toplevel widget of Tk which represents mostly the main window
1462 of an appliation. It has an associated Tcl interpreter."""
1463 _w = '.'
1464 def __init__(self, screenName=None, baseName=None, className='Tk'):
1465 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1466 be created. BASENAME will be used for the identification of the profile file (see
1467 readprofile).
1468 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1469 is the name of the widget class."""
1470 global _default_root
1471 self.master = None
1472 self.children = {}
1473 if baseName is None:
1474 import sys, os
1475 baseName = os.path.basename(sys.argv[0])
1476 baseName, ext = os.path.splitext(baseName)
1477 if ext not in ('.py', '.pyc', '.pyo'):
1478 baseName = baseName + ext
1479 self.tk = _tkinter.create(screenName, baseName, className)
1480 if _MacOS:
1481 # Disable event scanning except for Command-Period
1482 _MacOS.SchedParams(1, 0)
1483 # Work around nasty MacTk bug
1484 # XXX Is this one still needed?
1485 self.update()
1486 # Version sanity checks
1487 tk_version = self.tk.getvar('tk_version')
1488 if tk_version != _tkinter.TK_VERSION:
1489 raise RuntimeError, \
1490 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1491 % (_tkinter.TK_VERSION, tk_version)
1492 tcl_version = self.tk.getvar('tcl_version')
1493 if tcl_version != _tkinter.TCL_VERSION:
1494 raise RuntimeError, \
1495 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1496 % (_tkinter.TCL_VERSION, tcl_version)
1497 if TkVersion < 4.0:
1498 raise RuntimeError, \
1499 "Tk 4.0 or higher is required; found Tk %s" \
1500 % str(TkVersion)
1501 self.tk.createcommand('tkerror', _tkerror)
1502 self.tk.createcommand('exit', _exit)
1503 self.readprofile(baseName, className)
1504 if _support_default_root and not _default_root:
1505 _default_root = self
1506 self.protocol("WM_DELETE_WINDOW", self.destroy)
1507 def destroy(self):
1508 """Destroy this and all descendants widgets. This will
1509 end the application of this Tcl interpreter."""
1510 for c in self.children.values(): c.destroy()
1511 self.tk.call('destroy', self._w)
1512 Misc.destroy(self)
1513 global _default_root
1514 if _support_default_root and _default_root is self:
1515 _default_root = None
1516 def readprofile(self, baseName, className):
1517 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1518 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1519 such a file exists in the home directory."""
1520 import os
1521 if os.environ.has_key('HOME'): home = os.environ['HOME']
1522 else: home = os.curdir
1523 class_tcl = os.path.join(home, '.%s.tcl' % className)
1524 class_py = os.path.join(home, '.%s.py' % className)
1525 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1526 base_py = os.path.join(home, '.%s.py' % baseName)
1527 dir = {'self': self}
1528 exec 'from Tkinter import *' in dir
1529 if os.path.isfile(class_tcl):
1530 print 'source', `class_tcl`
1531 self.tk.call('source', class_tcl)
1532 if os.path.isfile(class_py):
1533 print 'execfile', `class_py`
1534 execfile(class_py, dir)
1535 if os.path.isfile(base_tcl):
1536 print 'source', `base_tcl`
1537 self.tk.call('source', base_tcl)
1538 if os.path.isfile(base_py):
1539 print 'execfile', `base_py`
1540 execfile(base_py, dir)
1541 def report_callback_exception(self, exc, val, tb):
1542 """Internal function. It reports exception on sys.stderr."""
1543 import traceback, sys
1544 sys.stderr.write("Exception in Tkinter callback\n")
1545 sys.last_type = exc
1546 sys.last_value = val
1547 sys.last_traceback = tb
1548 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001549
Guido van Rossum368e06b1997-11-07 20:38:49 +00001550# Ideally, the classes Pack, Place and Grid disappear, the
1551# pack/place/grid methods are defined on the Widget class, and
1552# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1553# ...), with pack(), place() and grid() being short for
1554# pack_configure(), place_configure() and grid_columnconfigure(), and
1555# forget() being short for pack_forget(). As a practical matter, I'm
1556# afraid that there is too much code out there that may be using the
1557# Pack, Place or Grid class, so I leave them intact -- but only as
1558# backwards compatibility features. Also note that those methods that
1559# take a master as argument (e.g. pack_propagate) have been moved to
1560# the Misc class (which now incorporates all methods common between
1561# toplevel and interior widgets). Again, for compatibility, these are
1562# copied into the Pack, Place or Grid class.
1563
Guido van Rossum18468821994-06-20 07:49:28 +00001564class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001565 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001566
Fredrik Lundh06d28152000-08-09 18:03:12 +00001567 Base class to use the methods pack_* in every widget."""
1568 def pack_configure(self, cnf={}, **kw):
1569 """Pack a widget in the parent widget. Use as options:
1570 after=widget - pack it after you have packed widget
1571 anchor=NSEW (or subset) - position widget according to
1572 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001573 before=widget - pack it before you will pack widget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001574 expand=1 or 0 - expand widget if parent size grows
1575 fill=NONE or X or Y or BOTH - fill widget if widget grows
1576 in=master - use master to contain this widget
1577 ipadx=amount - add internal padding in x direction
1578 ipady=amount - add internal padding in y direction
1579 padx=amount - add padding in x direction
1580 pady=amount - add padding in y direction
1581 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1582 """
1583 self.tk.call(
1584 ('pack', 'configure', self._w)
1585 + self._options(cnf, kw))
1586 pack = configure = config = pack_configure
1587 def pack_forget(self):
1588 """Unmap this widget and do not use it for the packing order."""
1589 self.tk.call('pack', 'forget', self._w)
1590 forget = pack_forget
1591 def pack_info(self):
1592 """Return information about the packing options
1593 for this widget."""
1594 words = self.tk.splitlist(
1595 self.tk.call('pack', 'info', self._w))
1596 dict = {}
1597 for i in range(0, len(words), 2):
1598 key = words[i][1:]
1599 value = words[i+1]
1600 if value[:1] == '.':
1601 value = self._nametowidget(value)
1602 dict[key] = value
1603 return dict
1604 info = pack_info
1605 propagate = pack_propagate = Misc.pack_propagate
1606 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001607
1608class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001609 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001610
Fredrik Lundh06d28152000-08-09 18:03:12 +00001611 Base class to use the methods place_* in every widget."""
1612 def place_configure(self, cnf={}, **kw):
1613 """Place a widget in the parent widget. Use as options:
1614 in=master - master relative to which the widget is placed.
1615 x=amount - locate anchor of this widget at position x of master
1616 y=amount - locate anchor of this widget at position y of master
1617 relx=amount - locate anchor of this widget between 0.0 and 1.0
1618 relative to width of master (1.0 is right edge)
1619 rely=amount - locate anchor of this widget between 0.0 and 1.0
1620 relative to height of master (1.0 is bottom edge)
1621 anchor=NSEW (or subset) - position anchor according to given direction
1622 width=amount - width of this widget in pixel
1623 height=amount - height of this widget in pixel
1624 relwidth=amount - width of this widget between 0.0 and 1.0
1625 relative to width of master (1.0 is the same width
1626 as the master)
1627 relheight=amount - height of this widget between 0.0 and 1.0
1628 relative to height of master (1.0 is the same
1629 height as the master)
1630 bordermode="inside" or "outside" - whether to take border width of master widget
1631 into account
1632 """
1633 for k in ['in_']:
1634 if kw.has_key(k):
1635 kw[k[:-1]] = kw[k]
1636 del kw[k]
1637 self.tk.call(
1638 ('place', 'configure', self._w)
1639 + self._options(cnf, kw))
1640 place = configure = config = place_configure
1641 def place_forget(self):
1642 """Unmap this widget."""
1643 self.tk.call('place', 'forget', self._w)
1644 forget = place_forget
1645 def place_info(self):
1646 """Return information about the placing options
1647 for this widget."""
1648 words = self.tk.splitlist(
1649 self.tk.call('place', 'info', self._w))
1650 dict = {}
1651 for i in range(0, len(words), 2):
1652 key = words[i][1:]
1653 value = words[i+1]
1654 if value[:1] == '.':
1655 value = self._nametowidget(value)
1656 dict[key] = value
1657 return dict
1658 info = place_info
1659 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001660
Guido van Rossum37dcab11996-05-16 16:00:19 +00001661class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001662 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001663
Fredrik Lundh06d28152000-08-09 18:03:12 +00001664 Base class to use the methods grid_* in every widget."""
1665 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1666 def grid_configure(self, cnf={}, **kw):
1667 """Position a widget in the parent widget in a grid. Use as options:
1668 column=number - use cell identified with given column (starting with 0)
1669 columnspan=number - this widget will span several columns
1670 in=master - use master to contain this widget
1671 ipadx=amount - add internal padding in x direction
1672 ipady=amount - add internal padding in y direction
1673 padx=amount - add padding in x direction
1674 pady=amount - add padding in y direction
1675 row=number - use cell identified with given row (starting with 0)
1676 rowspan=number - this widget will span several rows
1677 sticky=NSEW - if cell is larger on which sides will this
1678 widget stick to the cell boundary
1679 """
1680 self.tk.call(
1681 ('grid', 'configure', self._w)
1682 + self._options(cnf, kw))
1683 grid = configure = config = grid_configure
1684 bbox = grid_bbox = Misc.grid_bbox
1685 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1686 def grid_forget(self):
1687 """Unmap this widget."""
1688 self.tk.call('grid', 'forget', self._w)
1689 forget = grid_forget
1690 def grid_remove(self):
1691 """Unmap this widget but remember the grid options."""
1692 self.tk.call('grid', 'remove', self._w)
1693 def grid_info(self):
1694 """Return information about the options
1695 for positioning this widget in a grid."""
1696 words = self.tk.splitlist(
1697 self.tk.call('grid', 'info', self._w))
1698 dict = {}
1699 for i in range(0, len(words), 2):
1700 key = words[i][1:]
1701 value = words[i+1]
1702 if value[:1] == '.':
1703 value = self._nametowidget(value)
1704 dict[key] = value
1705 return dict
1706 info = grid_info
1707 def grid_location(self, x, y):
1708 """Return a tuple of column and row which identify the cell
1709 at which the pixel at position X and Y inside the master
1710 widget is located."""
1711 return self._getints(
1712 self.tk.call(
1713 'grid', 'location', self._w, x, y)) or None
1714 location = grid_location
1715 propagate = grid_propagate = Misc.grid_propagate
1716 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1717 size = grid_size = Misc.grid_size
1718 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001719
Guido van Rossum368e06b1997-11-07 20:38:49 +00001720class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001721 """Internal class."""
1722 def _setup(self, master, cnf):
1723 """Internal function. Sets up information about children."""
1724 if _support_default_root:
1725 global _default_root
1726 if not master:
1727 if not _default_root:
1728 _default_root = Tk()
1729 master = _default_root
1730 self.master = master
1731 self.tk = master.tk
1732 name = None
1733 if cnf.has_key('name'):
1734 name = cnf['name']
1735 del cnf['name']
1736 if not name:
1737 name = `id(self)`
1738 self._name = name
1739 if master._w=='.':
1740 self._w = '.' + name
1741 else:
1742 self._w = master._w + '.' + name
1743 self.children = {}
1744 if self.master.children.has_key(self._name):
1745 self.master.children[self._name].destroy()
1746 self.master.children[self._name] = self
1747 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1748 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1749 and appropriate options."""
1750 if kw:
1751 cnf = _cnfmerge((cnf, kw))
1752 self.widgetName = widgetName
1753 BaseWidget._setup(self, master, cnf)
1754 classes = []
1755 for k in cnf.keys():
1756 if type(k) is ClassType:
1757 classes.append((k, cnf[k]))
1758 del cnf[k]
1759 self.tk.call(
1760 (widgetName, self._w) + extra + self._options(cnf))
1761 for k, v in classes:
1762 k.configure(self, v)
1763 def destroy(self):
1764 """Destroy this and all descendants widgets."""
1765 for c in self.children.values(): c.destroy()
1766 if self.master.children.has_key(self._name):
1767 del self.master.children[self._name]
1768 self.tk.call('destroy', self._w)
1769 Misc.destroy(self)
1770 def _do(self, name, args=()):
1771 # XXX Obsolete -- better use self.tk.call directly!
1772 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001773
Guido van Rossum368e06b1997-11-07 20:38:49 +00001774class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001775 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001776
Fredrik Lundh06d28152000-08-09 18:03:12 +00001777 Base class for a widget which can be positioned with the geometry managers
1778 Pack, Place or Grid."""
1779 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001780
1781class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001782 """Toplevel widget, e.g. for dialogs."""
1783 def __init__(self, master=None, cnf={}, **kw):
1784 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001785
Fredrik Lundh06d28152000-08-09 18:03:12 +00001786 Valid resource names: background, bd, bg, borderwidth, class,
1787 colormap, container, cursor, height, highlightbackground,
1788 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1789 use, visual, width."""
1790 if kw:
1791 cnf = _cnfmerge((cnf, kw))
1792 extra = ()
1793 for wmkey in ['screen', 'class_', 'class', 'visual',
1794 'colormap']:
1795 if cnf.has_key(wmkey):
1796 val = cnf[wmkey]
1797 # TBD: a hack needed because some keys
1798 # are not valid as keyword arguments
1799 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1800 else: opt = '-'+wmkey
1801 extra = extra + (opt, val)
1802 del cnf[wmkey]
1803 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1804 root = self._root()
1805 self.iconname(root.iconname())
1806 self.title(root.title())
1807 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001808
1809class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001810 """Button widget."""
1811 def __init__(self, master=None, cnf={}, **kw):
1812 """Construct a button widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001813
Fredrik Lundh06d28152000-08-09 18:03:12 +00001814 Valid resource names: activebackground, activeforeground, anchor,
1815 background, bd, bg, bitmap, borderwidth, command, cursor, default,
1816 disabledforeground, fg, font, foreground, height,
1817 highlightbackground, highlightcolor, highlightthickness, image,
1818 justify, padx, pady, relief, state, takefocus, text, textvariable,
1819 underline, width, wraplength."""
1820 Widget.__init__(self, master, 'button', cnf, kw)
1821 def tkButtonEnter(self, *dummy):
1822 self.tk.call('tkButtonEnter', self._w)
1823 def tkButtonLeave(self, *dummy):
1824 self.tk.call('tkButtonLeave', self._w)
1825 def tkButtonDown(self, *dummy):
1826 self.tk.call('tkButtonDown', self._w)
1827 def tkButtonUp(self, *dummy):
1828 self.tk.call('tkButtonUp', self._w)
1829 def tkButtonInvoke(self, *dummy):
1830 self.tk.call('tkButtonInvoke', self._w)
1831 def flash(self):
1832 self.tk.call(self._w, 'flash')
1833 def invoke(self):
1834 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001835
1836# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001837# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001838def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001839 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001840def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001841 s = 'insert'
1842 for a in args:
1843 if a: s = s + (' ' + a)
1844 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001845def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001846 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001847def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001848 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001849def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001850 if y is None:
1851 return '@' + `x`
1852 else:
1853 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001854
1855class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001856 """Canvas widget to display graphical elements like lines or text."""
1857 def __init__(self, master=None, cnf={}, **kw):
1858 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001859
Fredrik Lundh06d28152000-08-09 18:03:12 +00001860 Valid resource names: background, bd, bg, borderwidth, closeenough,
1861 confine, cursor, height, highlightbackground, highlightcolor,
1862 highlightthickness, insertbackground, insertborderwidth,
1863 insertofftime, insertontime, insertwidth, offset, relief,
1864 scrollregion, selectbackground, selectborderwidth, selectforeground,
1865 state, takefocus, width, xscrollcommand, xscrollincrement,
1866 yscrollcommand, yscrollincrement."""
1867 Widget.__init__(self, master, 'canvas', cnf, kw)
1868 def addtag(self, *args):
1869 """Internal function."""
1870 self.tk.call((self._w, 'addtag') + args)
1871 def addtag_above(self, newtag, tagOrId):
1872 """Add tag NEWTAG to all items above TAGORID."""
1873 self.addtag(newtag, 'above', tagOrId)
1874 def addtag_all(self, newtag):
1875 """Add tag NEWTAG to all items."""
1876 self.addtag(newtag, 'all')
1877 def addtag_below(self, newtag, tagOrId):
1878 """Add tag NEWTAG to all items below TAGORID."""
1879 self.addtag(newtag, 'below', tagOrId)
1880 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1881 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1882 If several match take the top-most.
1883 All items closer than HALO are considered overlapping (all are
1884 closests). If START is specified the next below this tag is taken."""
1885 self.addtag(newtag, 'closest', x, y, halo, start)
1886 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1887 """Add tag NEWTAG to all items in the rectangle defined
1888 by X1,Y1,X2,Y2."""
1889 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1890 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1891 """Add tag NEWTAG to all items which overlap the rectangle
1892 defined by X1,Y1,X2,Y2."""
1893 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1894 def addtag_withtag(self, newtag, tagOrId):
1895 """Add tag NEWTAG to all items with TAGORID."""
1896 self.addtag(newtag, 'withtag', tagOrId)
1897 def bbox(self, *args):
1898 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1899 which encloses all items with tags specified as arguments."""
1900 return self._getints(
1901 self.tk.call((self._w, 'bbox') + args)) or None
1902 def tag_unbind(self, tagOrId, sequence, funcid=None):
1903 """Unbind for all items with TAGORID for event SEQUENCE the
1904 function identified with FUNCID."""
1905 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
1906 if funcid:
1907 self.deletecommand(funcid)
1908 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
1909 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001910
Fredrik Lundh06d28152000-08-09 18:03:12 +00001911 An additional boolean parameter ADD specifies whether FUNC will be
1912 called additionally to the other bound function or whether it will
1913 replace the previous function. See bind for the return value."""
1914 return self._bind((self._w, 'bind', tagOrId),
1915 sequence, func, add)
1916 def canvasx(self, screenx, gridspacing=None):
1917 """Return the canvas x coordinate of pixel position SCREENX rounded
1918 to nearest multiple of GRIDSPACING units."""
1919 return getdouble(self.tk.call(
1920 self._w, 'canvasx', screenx, gridspacing))
1921 def canvasy(self, screeny, gridspacing=None):
1922 """Return the canvas y coordinate of pixel position SCREENY rounded
1923 to nearest multiple of GRIDSPACING units."""
1924 return getdouble(self.tk.call(
1925 self._w, 'canvasy', screeny, gridspacing))
1926 def coords(self, *args):
1927 """Return a list of coordinates for the item given in ARGS."""
1928 # XXX Should use _flatten on args
1929 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00001930 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001931 self.tk.call((self._w, 'coords') + args)))
1932 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
1933 """Internal function."""
1934 args = _flatten(args)
1935 cnf = args[-1]
1936 if type(cnf) in (DictionaryType, TupleType):
1937 args = args[:-1]
1938 else:
1939 cnf = {}
1940 return getint(apply(
1941 self.tk.call,
1942 (self._w, 'create', itemType)
1943 + args + self._options(cnf, kw)))
1944 def create_arc(self, *args, **kw):
1945 """Create arc shaped region with coordinates x1,y1,x2,y2."""
1946 return self._create('arc', args, kw)
1947 def create_bitmap(self, *args, **kw):
1948 """Create bitmap with coordinates x1,y1."""
1949 return self._create('bitmap', args, kw)
1950 def create_image(self, *args, **kw):
1951 """Create image item with coordinates x1,y1."""
1952 return self._create('image', args, kw)
1953 def create_line(self, *args, **kw):
1954 """Create line with coordinates x1,y1,...,xn,yn."""
1955 return self._create('line', args, kw)
1956 def create_oval(self, *args, **kw):
1957 """Create oval with coordinates x1,y1,x2,y2."""
1958 return self._create('oval', args, kw)
1959 def create_polygon(self, *args, **kw):
1960 """Create polygon with coordinates x1,y1,...,xn,yn."""
1961 return self._create('polygon', args, kw)
1962 def create_rectangle(self, *args, **kw):
1963 """Create rectangle with coordinates x1,y1,x2,y2."""
1964 return self._create('rectangle', args, kw)
1965 def create_text(self, *args, **kw):
1966 """Create text with coordinates x1,y1."""
1967 return self._create('text', args, kw)
1968 def create_window(self, *args, **kw):
1969 """Create window with coordinates x1,y1,x2,y2."""
1970 return self._create('window', args, kw)
1971 def dchars(self, *args):
1972 """Delete characters of text items identified by tag or id in ARGS (possibly
1973 several times) from FIRST to LAST character (including)."""
1974 self.tk.call((self._w, 'dchars') + args)
1975 def delete(self, *args):
1976 """Delete items identified by all tag or ids contained in ARGS."""
1977 self.tk.call((self._w, 'delete') + args)
1978 def dtag(self, *args):
1979 """Delete tag or id given as last arguments in ARGS from items
1980 identified by first argument in ARGS."""
1981 self.tk.call((self._w, 'dtag') + args)
1982 def find(self, *args):
1983 """Internal function."""
1984 return self._getints(
1985 self.tk.call((self._w, 'find') + args)) or ()
1986 def find_above(self, tagOrId):
1987 """Return items above TAGORID."""
1988 return self.find('above', tagOrId)
1989 def find_all(self):
1990 """Return all items."""
1991 return self.find('all')
1992 def find_below(self, tagOrId):
1993 """Return all items below TAGORID."""
1994 return self.find('below', tagOrId)
1995 def find_closest(self, x, y, halo=None, start=None):
1996 """Return item which is closest to pixel at X, Y.
1997 If several match take the top-most.
1998 All items closer than HALO are considered overlapping (all are
1999 closests). If START is specified the next below this tag is taken."""
2000 return self.find('closest', x, y, halo, start)
2001 def find_enclosed(self, x1, y1, x2, y2):
2002 """Return all items in rectangle defined
2003 by X1,Y1,X2,Y2."""
2004 return self.find('enclosed', x1, y1, x2, y2)
2005 def find_overlapping(self, x1, y1, x2, y2):
2006 """Return all items which overlap the rectangle
2007 defined by X1,Y1,X2,Y2."""
2008 return self.find('overlapping', x1, y1, x2, y2)
2009 def find_withtag(self, tagOrId):
2010 """Return all items with TAGORID."""
2011 return self.find('withtag', tagOrId)
2012 def focus(self, *args):
2013 """Set focus to the first item specified in ARGS."""
2014 return self.tk.call((self._w, 'focus') + args)
2015 def gettags(self, *args):
2016 """Return tags associated with the first item specified in ARGS."""
2017 return self.tk.splitlist(
2018 self.tk.call((self._w, 'gettags') + args))
2019 def icursor(self, *args):
2020 """Set cursor at position POS in the item identified by TAGORID.
2021 In ARGS TAGORID must be first."""
2022 self.tk.call((self._w, 'icursor') + args)
2023 def index(self, *args):
2024 """Return position of cursor as integer in item specified in ARGS."""
2025 return getint(self.tk.call((self._w, 'index') + args))
2026 def insert(self, *args):
2027 """Insert TEXT in item TAGORID at position POS. ARGS must
2028 be TAGORID POS TEXT."""
2029 self.tk.call((self._w, 'insert') + args)
2030 def itemcget(self, tagOrId, option):
2031 """Return the resource value for an OPTION for item TAGORID."""
2032 return self.tk.call(
2033 (self._w, 'itemcget') + (tagOrId, '-'+option))
2034 def itemconfigure(self, tagOrId, cnf=None, **kw):
2035 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002036
Fredrik Lundh06d28152000-08-09 18:03:12 +00002037 The values for resources are specified as keyword
2038 arguments. To get an overview about
2039 the allowed keyword arguments call the method without arguments.
2040 """
2041 if cnf is None and not kw:
2042 cnf = {}
2043 for x in self.tk.split(
2044 self.tk.call(self._w,
2045 'itemconfigure', tagOrId)):
2046 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2047 return cnf
2048 if type(cnf) == StringType and not kw:
2049 x = self.tk.split(self.tk.call(
2050 self._w, 'itemconfigure', tagOrId, '-'+cnf))
2051 return (x[0][1:],) + x[1:]
2052 self.tk.call((self._w, 'itemconfigure', tagOrId) +
2053 self._options(cnf, kw))
2054 itemconfig = itemconfigure
2055 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2056 # so the preferred name for them is tag_lower, tag_raise
2057 # (similar to tag_bind, and similar to the Text widget);
2058 # unfortunately can't delete the old ones yet (maybe in 1.6)
2059 def tag_lower(self, *args):
2060 """Lower an item TAGORID given in ARGS
2061 (optional below another item)."""
2062 self.tk.call((self._w, 'lower') + args)
2063 lower = tag_lower
2064 def move(self, *args):
2065 """Move an item TAGORID given in ARGS."""
2066 self.tk.call((self._w, 'move') + args)
2067 def postscript(self, cnf={}, **kw):
2068 """Print the contents of the canvas to a postscript
2069 file. Valid options: colormap, colormode, file, fontmap,
2070 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2071 rotate, witdh, x, y."""
2072 return self.tk.call((self._w, 'postscript') +
2073 self._options(cnf, kw))
2074 def tag_raise(self, *args):
2075 """Raise an item TAGORID given in ARGS
2076 (optional above another item)."""
2077 self.tk.call((self._w, 'raise') + args)
2078 lift = tkraise = tag_raise
2079 def scale(self, *args):
2080 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2081 self.tk.call((self._w, 'scale') + args)
2082 def scan_mark(self, x, y):
2083 """Remember the current X, Y coordinates."""
2084 self.tk.call(self._w, 'scan', 'mark', x, y)
2085 def scan_dragto(self, x, y):
2086 """Adjust the view of the canvas to 10 times the
2087 difference between X and Y and the coordinates given in
2088 scan_mark."""
2089 self.tk.call(self._w, 'scan', 'dragto', x, y)
2090 def select_adjust(self, tagOrId, index):
2091 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2092 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2093 def select_clear(self):
2094 """Clear the selection if it is in this widget."""
2095 self.tk.call(self._w, 'select', 'clear')
2096 def select_from(self, tagOrId, index):
2097 """Set the fixed end of a selection in item TAGORID to INDEX."""
2098 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2099 def select_item(self):
2100 """Return the item which has the selection."""
2101 self.tk.call(self._w, 'select', 'item')
2102 def select_to(self, tagOrId, index):
2103 """Set the variable end of a selection in item TAGORID to INDEX."""
2104 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2105 def type(self, tagOrId):
2106 """Return the type of the item TAGORID."""
2107 return self.tk.call(self._w, 'type', tagOrId) or None
2108 def xview(self, *args):
2109 """Query and change horizontal position of the view."""
2110 if not args:
2111 return self._getdoubles(self.tk.call(self._w, 'xview'))
2112 self.tk.call((self._w, 'xview') + args)
2113 def xview_moveto(self, fraction):
2114 """Adjusts the view in the window so that FRACTION of the
2115 total width of the canvas is off-screen to the left."""
2116 self.tk.call(self._w, 'xview', 'moveto', fraction)
2117 def xview_scroll(self, number, what):
2118 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2119 self.tk.call(self._w, 'xview', 'scroll', number, what)
2120 def yview(self, *args):
2121 """Query and change vertical position of the view."""
2122 if not args:
2123 return self._getdoubles(self.tk.call(self._w, 'yview'))
2124 self.tk.call((self._w, 'yview') + args)
2125 def yview_moveto(self, fraction):
2126 """Adjusts the view in the window so that FRACTION of the
2127 total height of the canvas is off-screen to the top."""
2128 self.tk.call(self._w, 'yview', 'moveto', fraction)
2129 def yview_scroll(self, number, what):
2130 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2131 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002132
2133class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002134 """Checkbutton widget which is either in on- or off-state."""
2135 def __init__(self, master=None, cnf={}, **kw):
2136 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002137
Fredrik Lundh06d28152000-08-09 18:03:12 +00002138 Valid resource names: activebackground, activeforeground, anchor,
2139 background, bd, bg, bitmap, borderwidth, command, cursor,
2140 disabledforeground, fg, font, foreground, height,
2141 highlightbackground, highlightcolor, highlightthickness, image,
2142 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2143 selectcolor, selectimage, state, takefocus, text, textvariable,
2144 underline, variable, width, wraplength."""
2145 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2146 def deselect(self):
2147 """Put the button in off-state."""
2148 self.tk.call(self._w, 'deselect')
2149 def flash(self):
2150 """Flash the button."""
2151 self.tk.call(self._w, 'flash')
2152 def invoke(self):
2153 """Toggle the button and invoke a command if given as resource."""
2154 return self.tk.call(self._w, 'invoke')
2155 def select(self):
2156 """Put the button in on-state."""
2157 self.tk.call(self._w, 'select')
2158 def toggle(self):
2159 """Toggle the button."""
2160 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002161
2162class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002163 """Entry widget which allows to display simple text."""
2164 def __init__(self, master=None, cnf={}, **kw):
2165 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002166
Fredrik Lundh06d28152000-08-09 18:03:12 +00002167 Valid resource names: background, bd, bg, borderwidth, cursor,
2168 exportselection, fg, font, foreground, highlightbackground,
2169 highlightcolor, highlightthickness, insertbackground,
2170 insertborderwidth, insertofftime, insertontime, insertwidth,
2171 invalidcommand, invcmd, justify, relief, selectbackground,
2172 selectborderwidth, selectforeground, show, state, takefocus,
2173 textvariable, validate, validatecommand, vcmd, width,
2174 xscrollcommand."""
2175 Widget.__init__(self, master, 'entry', cnf, kw)
2176 def delete(self, first, last=None):
2177 """Delete text from FIRST to LAST (not included)."""
2178 self.tk.call(self._w, 'delete', first, last)
2179 def get(self):
2180 """Return the text."""
2181 return self.tk.call(self._w, 'get')
2182 def icursor(self, index):
2183 """Insert cursor at INDEX."""
2184 self.tk.call(self._w, 'icursor', index)
2185 def index(self, index):
2186 """Return position of cursor."""
2187 return getint(self.tk.call(
2188 self._w, 'index', index))
2189 def insert(self, index, string):
2190 """Insert STRING at INDEX."""
2191 self.tk.call(self._w, 'insert', index, string)
2192 def scan_mark(self, x):
2193 """Remember the current X, Y coordinates."""
2194 self.tk.call(self._w, 'scan', 'mark', x)
2195 def scan_dragto(self, x):
2196 """Adjust the view of the canvas to 10 times the
2197 difference between X and Y and the coordinates given in
2198 scan_mark."""
2199 self.tk.call(self._w, 'scan', 'dragto', x)
2200 def selection_adjust(self, index):
2201 """Adjust the end of the selection near the cursor to INDEX."""
2202 self.tk.call(self._w, 'selection', 'adjust', index)
2203 select_adjust = selection_adjust
2204 def selection_clear(self):
2205 """Clear the selection if it is in this widget."""
2206 self.tk.call(self._w, 'selection', 'clear')
2207 select_clear = selection_clear
2208 def selection_from(self, index):
2209 """Set the fixed end of a selection to INDEX."""
2210 self.tk.call(self._w, 'selection', 'from', index)
2211 select_from = selection_from
2212 def selection_present(self):
2213 """Return whether the widget has the selection."""
2214 return self.tk.getboolean(
2215 self.tk.call(self._w, 'selection', 'present'))
2216 select_present = selection_present
2217 def selection_range(self, start, end):
2218 """Set the selection from START to END (not included)."""
2219 self.tk.call(self._w, 'selection', 'range', start, end)
2220 select_range = selection_range
2221 def selection_to(self, index):
2222 """Set the variable end of a selection to INDEX."""
2223 self.tk.call(self._w, 'selection', 'to', index)
2224 select_to = selection_to
2225 def xview(self, index):
2226 """Query and change horizontal position of the view."""
2227 self.tk.call(self._w, 'xview', index)
2228 def xview_moveto(self, fraction):
2229 """Adjust the view in the window so that FRACTION of the
2230 total width of the entry is off-screen to the left."""
2231 self.tk.call(self._w, 'xview', 'moveto', fraction)
2232 def xview_scroll(self, number, what):
2233 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2234 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002235
2236class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002237 """Frame widget which may contain other widgets and can have a 3D border."""
2238 def __init__(self, master=None, cnf={}, **kw):
2239 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002240
Fredrik Lundh06d28152000-08-09 18:03:12 +00002241 Valid resource names: background, bd, bg, borderwidth, class,
2242 colormap, container, cursor, height, highlightbackground,
2243 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2244 cnf = _cnfmerge((cnf, kw))
2245 extra = ()
2246 if cnf.has_key('class_'):
2247 extra = ('-class', cnf['class_'])
2248 del cnf['class_']
2249 elif cnf.has_key('class'):
2250 extra = ('-class', cnf['class'])
2251 del cnf['class']
2252 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002253
2254class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002255 """Label widget which can display text and bitmaps."""
2256 def __init__(self, master=None, cnf={}, **kw):
2257 """Construct a label widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002258
Fredrik Lundh06d28152000-08-09 18:03:12 +00002259 Valid resource names: anchor, background, bd, bg, bitmap,
2260 borderwidth, cursor, fg, font, foreground, height,
2261 highlightbackground, highlightcolor, highlightthickness, image,
2262 justify, padx, pady, relief, takefocus, text, textvariable,
2263 underline, width, wraplength."""
2264 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002265
Guido van Rossum18468821994-06-20 07:49:28 +00002266class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002267 """Listbox widget which can display a list of strings."""
2268 def __init__(self, master=None, cnf={}, **kw):
2269 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002270
Fredrik Lundh06d28152000-08-09 18:03:12 +00002271 Valid resource names: background, bd, bg, borderwidth, cursor,
2272 exportselection, fg, font, foreground, height, highlightbackground,
2273 highlightcolor, highlightthickness, relief, selectbackground,
2274 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2275 width, xscrollcommand, yscrollcommand, listvariable."""
2276 Widget.__init__(self, master, 'listbox', cnf, kw)
2277 def activate(self, index):
2278 """Activate item identified by INDEX."""
2279 self.tk.call(self._w, 'activate', index)
2280 def bbox(self, *args):
2281 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2282 which encloses the item identified by index in ARGS."""
2283 return self._getints(
2284 self.tk.call((self._w, 'bbox') + args)) or None
2285 def curselection(self):
2286 """Return list of indices of currently selected item."""
2287 # XXX Ought to apply self._getints()...
2288 return self.tk.splitlist(self.tk.call(
2289 self._w, 'curselection'))
2290 def delete(self, first, last=None):
2291 """Delete items from FIRST to LAST (not included)."""
2292 self.tk.call(self._w, 'delete', first, last)
2293 def get(self, first, last=None):
2294 """Get list of items from FIRST to LAST (not included)."""
2295 if last:
2296 return self.tk.splitlist(self.tk.call(
2297 self._w, 'get', first, last))
2298 else:
2299 return self.tk.call(self._w, 'get', first)
2300 def index(self, index):
2301 """Return index of item identified with INDEX."""
2302 i = self.tk.call(self._w, 'index', index)
2303 if i == 'none': return None
2304 return getint(i)
2305 def insert(self, index, *elements):
2306 """Insert ELEMENTS at INDEX."""
2307 self.tk.call((self._w, 'insert', index) + elements)
2308 def nearest(self, y):
2309 """Get index of item which is nearest to y coordinate Y."""
2310 return getint(self.tk.call(
2311 self._w, 'nearest', y))
2312 def scan_mark(self, x, y):
2313 """Remember the current X, Y coordinates."""
2314 self.tk.call(self._w, 'scan', 'mark', x, y)
2315 def scan_dragto(self, x, y):
2316 """Adjust the view of the listbox to 10 times the
2317 difference between X and Y and the coordinates given in
2318 scan_mark."""
2319 self.tk.call(self._w, 'scan', 'dragto', x, y)
2320 def see(self, index):
2321 """Scroll such that INDEX is visible."""
2322 self.tk.call(self._w, 'see', index)
2323 def selection_anchor(self, index):
2324 """Set the fixed end oft the selection to INDEX."""
2325 self.tk.call(self._w, 'selection', 'anchor', index)
2326 select_anchor = selection_anchor
2327 def selection_clear(self, first, last=None):
2328 """Clear the selection from FIRST to LAST (not included)."""
2329 self.tk.call(self._w,
2330 'selection', 'clear', first, last)
2331 select_clear = selection_clear
2332 def selection_includes(self, index):
2333 """Return 1 if INDEX is part of the selection."""
2334 return self.tk.getboolean(self.tk.call(
2335 self._w, 'selection', 'includes', index))
2336 select_includes = selection_includes
2337 def selection_set(self, first, last=None):
2338 """Set the selection from FIRST to LAST (not included) without
2339 changing the currently selected elements."""
2340 self.tk.call(self._w, 'selection', 'set', first, last)
2341 select_set = selection_set
2342 def size(self):
2343 """Return the number of elements in the listbox."""
2344 return getint(self.tk.call(self._w, 'size'))
2345 def xview(self, *what):
2346 """Query and change horizontal position of the view."""
2347 if not what:
2348 return self._getdoubles(self.tk.call(self._w, 'xview'))
2349 self.tk.call((self._w, 'xview') + what)
2350 def xview_moveto(self, fraction):
2351 """Adjust the view in the window so that FRACTION of the
2352 total width of the entry is off-screen to the left."""
2353 self.tk.call(self._w, 'xview', 'moveto', fraction)
2354 def xview_scroll(self, number, what):
2355 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2356 self.tk.call(self._w, 'xview', 'scroll', number, what)
2357 def yview(self, *what):
2358 """Query and change vertical position of the view."""
2359 if not what:
2360 return self._getdoubles(self.tk.call(self._w, 'yview'))
2361 self.tk.call((self._w, 'yview') + what)
2362 def yview_moveto(self, fraction):
2363 """Adjust the view in the window so that FRACTION of the
2364 total width of the entry is off-screen to the top."""
2365 self.tk.call(self._w, 'yview', 'moveto', fraction)
2366 def yview_scroll(self, number, what):
2367 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2368 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002369
2370class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002371 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2372 def __init__(self, master=None, cnf={}, **kw):
2373 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002374
Fredrik Lundh06d28152000-08-09 18:03:12 +00002375 Valid resource names: activebackground, activeborderwidth,
2376 activeforeground, background, bd, bg, borderwidth, cursor,
2377 disabledforeground, fg, font, foreground, postcommand, relief,
2378 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2379 Widget.__init__(self, master, 'menu', cnf, kw)
2380 def tk_bindForTraversal(self):
2381 pass # obsolete since Tk 4.0
2382 def tk_mbPost(self):
2383 self.tk.call('tk_mbPost', self._w)
2384 def tk_mbUnpost(self):
2385 self.tk.call('tk_mbUnpost')
2386 def tk_traverseToMenu(self, char):
2387 self.tk.call('tk_traverseToMenu', self._w, char)
2388 def tk_traverseWithinMenu(self, char):
2389 self.tk.call('tk_traverseWithinMenu', self._w, char)
2390 def tk_getMenuButtons(self):
2391 return self.tk.call('tk_getMenuButtons', self._w)
2392 def tk_nextMenu(self, count):
2393 self.tk.call('tk_nextMenu', count)
2394 def tk_nextMenuEntry(self, count):
2395 self.tk.call('tk_nextMenuEntry', count)
2396 def tk_invokeMenu(self):
2397 self.tk.call('tk_invokeMenu', self._w)
2398 def tk_firstMenu(self):
2399 self.tk.call('tk_firstMenu', self._w)
2400 def tk_mbButtonDown(self):
2401 self.tk.call('tk_mbButtonDown', self._w)
2402 def tk_popup(self, x, y, entry=""):
2403 """Post the menu at position X,Y with entry ENTRY."""
2404 self.tk.call('tk_popup', self._w, x, y, entry)
2405 def activate(self, index):
2406 """Activate entry at INDEX."""
2407 self.tk.call(self._w, 'activate', index)
2408 def add(self, itemType, cnf={}, **kw):
2409 """Internal function."""
2410 self.tk.call((self._w, 'add', itemType) +
2411 self._options(cnf, kw))
2412 def add_cascade(self, cnf={}, **kw):
2413 """Add hierarchical menu item."""
2414 self.add('cascade', cnf or kw)
2415 def add_checkbutton(self, cnf={}, **kw):
2416 """Add checkbutton menu item."""
2417 self.add('checkbutton', cnf or kw)
2418 def add_command(self, cnf={}, **kw):
2419 """Add command menu item."""
2420 self.add('command', cnf or kw)
2421 def add_radiobutton(self, cnf={}, **kw):
2422 """Addd radio menu item."""
2423 self.add('radiobutton', cnf or kw)
2424 def add_separator(self, cnf={}, **kw):
2425 """Add separator."""
2426 self.add('separator', cnf or kw)
2427 def insert(self, index, itemType, cnf={}, **kw):
2428 """Internal function."""
2429 self.tk.call((self._w, 'insert', index, itemType) +
2430 self._options(cnf, kw))
2431 def insert_cascade(self, index, cnf={}, **kw):
2432 """Add hierarchical menu item at INDEX."""
2433 self.insert(index, 'cascade', cnf or kw)
2434 def insert_checkbutton(self, index, cnf={}, **kw):
2435 """Add checkbutton menu item at INDEX."""
2436 self.insert(index, 'checkbutton', cnf or kw)
2437 def insert_command(self, index, cnf={}, **kw):
2438 """Add command menu item at INDEX."""
2439 self.insert(index, 'command', cnf or kw)
2440 def insert_radiobutton(self, index, cnf={}, **kw):
2441 """Addd radio menu item at INDEX."""
2442 self.insert(index, 'radiobutton', cnf or kw)
2443 def insert_separator(self, index, cnf={}, **kw):
2444 """Add separator at INDEX."""
2445 self.insert(index, 'separator', cnf or kw)
2446 def delete(self, index1, index2=None):
2447 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2448 self.tk.call(self._w, 'delete', index1, index2)
2449 def entrycget(self, index, option):
2450 """Return the resource value of an menu item for OPTION at INDEX."""
2451 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2452 def entryconfigure(self, index, cnf=None, **kw):
2453 """Configure a menu item at INDEX."""
2454 if cnf is None and not kw:
2455 cnf = {}
2456 for x in self.tk.split(self.tk.call(
2457 (self._w, 'entryconfigure', index))):
2458 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2459 return cnf
2460 if type(cnf) == StringType and not kw:
2461 x = self.tk.split(self.tk.call(
2462 (self._w, 'entryconfigure', index, '-'+cnf)))
2463 return (x[0][1:],) + x[1:]
2464 self.tk.call((self._w, 'entryconfigure', index)
2465 + self._options(cnf, kw))
2466 entryconfig = entryconfigure
2467 def index(self, index):
2468 """Return the index of a menu item identified by INDEX."""
2469 i = self.tk.call(self._w, 'index', index)
2470 if i == 'none': return None
2471 return getint(i)
2472 def invoke(self, index):
2473 """Invoke a menu item identified by INDEX and execute
2474 the associated command."""
2475 return self.tk.call(self._w, 'invoke', index)
2476 def post(self, x, y):
2477 """Display a menu at position X,Y."""
2478 self.tk.call(self._w, 'post', x, y)
2479 def type(self, index):
2480 """Return the type of the menu item at INDEX."""
2481 return self.tk.call(self._w, 'type', index)
2482 def unpost(self):
2483 """Unmap a menu."""
2484 self.tk.call(self._w, 'unpost')
2485 def yposition(self, index):
2486 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2487 return getint(self.tk.call(
2488 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002489
2490class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002491 """Menubutton widget, obsolete since Tk8.0."""
2492 def __init__(self, master=None, cnf={}, **kw):
2493 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002494
2495class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002496 """Message widget to display multiline text. Obsolete since Label does it too."""
2497 def __init__(self, master=None, cnf={}, **kw):
2498 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002499
2500class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002501 """Radiobutton widget which shows only one of several buttons in on-state."""
2502 def __init__(self, master=None, cnf={}, **kw):
2503 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002504
Fredrik Lundh06d28152000-08-09 18:03:12 +00002505 Valid resource names: activebackground, activeforeground, anchor,
2506 background, bd, bg, bitmap, borderwidth, command, cursor,
2507 disabledforeground, fg, font, foreground, height,
2508 highlightbackground, highlightcolor, highlightthickness, image,
2509 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2510 state, takefocus, text, textvariable, underline, value, variable,
2511 width, wraplength."""
2512 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2513 def deselect(self):
2514 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002515
Fredrik Lundh06d28152000-08-09 18:03:12 +00002516 self.tk.call(self._w, 'deselect')
2517 def flash(self):
2518 """Flash the button."""
2519 self.tk.call(self._w, 'flash')
2520 def invoke(self):
2521 """Toggle the button and invoke a command if given as resource."""
2522 return self.tk.call(self._w, 'invoke')
2523 def select(self):
2524 """Put the button in on-state."""
2525 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002526
2527class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002528 """Scale widget which can display a numerical scale."""
2529 def __init__(self, master=None, cnf={}, **kw):
2530 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002531
Fredrik Lundh06d28152000-08-09 18:03:12 +00002532 Valid resource names: activebackground, background, bigincrement, bd,
2533 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2534 highlightbackground, highlightcolor, highlightthickness, label,
2535 length, orient, relief, repeatdelay, repeatinterval, resolution,
2536 showvalue, sliderlength, sliderrelief, state, takefocus,
2537 tickinterval, to, troughcolor, variable, width."""
2538 Widget.__init__(self, master, 'scale', cnf, kw)
2539 def get(self):
2540 """Get the current value as integer or float."""
2541 value = self.tk.call(self._w, 'get')
2542 try:
2543 return getint(value)
2544 except ValueError:
2545 return getdouble(value)
2546 def set(self, value):
2547 """Set the value to VALUE."""
2548 self.tk.call(self._w, 'set', value)
2549 def coords(self, value=None):
2550 """Return a tuple (X,Y) of the point along the centerline of the
2551 trough that corresponds to VALUE or the current value if None is
2552 given."""
2553
2554 return self._getints(self.tk.call(self._w, 'coords', value))
2555 def identify(self, x, y):
2556 """Return where the point X,Y lies. Valid return values are "slider",
2557 "though1" and "though2"."""
2558 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002559
2560class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002561 """Scrollbar widget which displays a slider at a certain position."""
2562 def __init__(self, master=None, cnf={}, **kw):
2563 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002564
Fredrik Lundh06d28152000-08-09 18:03:12 +00002565 Valid resource names: activebackground, activerelief,
2566 background, bd, bg, borderwidth, command, cursor,
2567 elementborderwidth, highlightbackground,
2568 highlightcolor, highlightthickness, jump, orient,
2569 relief, repeatdelay, repeatinterval, takefocus,
2570 troughcolor, width."""
2571 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2572 def activate(self, index):
2573 """Display the element at INDEX with activebackground and activerelief.
2574 INDEX can be "arrow1","slider" or "arrow2"."""
2575 self.tk.call(self._w, 'activate', index)
2576 def delta(self, deltax, deltay):
2577 """Return the fractional change of the scrollbar setting if it
2578 would be moved by DELTAX or DELTAY pixels."""
2579 return getdouble(
2580 self.tk.call(self._w, 'delta', deltax, deltay))
2581 def fraction(self, x, y):
2582 """Return the fractional value which corresponds to a slider
2583 position of X,Y."""
2584 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2585 def identify(self, x, y):
2586 """Return the element under position X,Y as one of
2587 "arrow1","slider","arrow2" or ""."""
2588 return self.tk.call(self._w, 'identify', x, y)
2589 def get(self):
2590 """Return the current fractional values (upper and lower end)
2591 of the slider position."""
2592 return self._getdoubles(self.tk.call(self._w, 'get'))
2593 def set(self, *args):
2594 """Set the fractional values of the slider position (upper and
2595 lower ends as value between 0 and 1)."""
2596 self.tk.call((self._w, 'set') + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002597
2598class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002599 """Text widget which can display text in various forms."""
2600 # XXX Add dump()
2601 def __init__(self, master=None, cnf={}, **kw):
2602 """Construct a text widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002603
Fredrik Lundh06d28152000-08-09 18:03:12 +00002604 Valid resource names: background, bd, bg, borderwidth, cursor,
2605 exportselection, fg, font, foreground, height,
2606 highlightbackground, highlightcolor, highlightthickness,
2607 insertbackground, insertborderwidth, insertofftime,
2608 insertontime, insertwidth, padx, pady, relief,
2609 selectbackground, selectborderwidth, selectforeground,
2610 setgrid, spacing1, spacing2, spacing3, state, tabs, takefocus,
2611 width, wrap, xscrollcommand, yscrollcommand."""
2612 Widget.__init__(self, master, 'text', cnf, kw)
2613 def bbox(self, *args):
2614 """Return a tuple of (x,y,width,height) which gives the bounding
2615 box of the visible part of the character at the index in ARGS."""
2616 return self._getints(
2617 self.tk.call((self._w, 'bbox') + args)) or None
2618 def tk_textSelectTo(self, index):
2619 self.tk.call('tk_textSelectTo', self._w, index)
2620 def tk_textBackspace(self):
2621 self.tk.call('tk_textBackspace', self._w)
2622 def tk_textIndexCloser(self, a, b, c):
2623 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2624 def tk_textResetAnchor(self, index):
2625 self.tk.call('tk_textResetAnchor', self._w, index)
2626 def compare(self, index1, op, index2):
2627 """Return whether between index INDEX1 and index INDEX2 the
2628 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2629 return self.tk.getboolean(self.tk.call(
2630 self._w, 'compare', index1, op, index2))
2631 def debug(self, boolean=None):
2632 """Turn on the internal consistency checks of the B-Tree inside the text
2633 widget according to BOOLEAN."""
2634 return self.tk.getboolean(self.tk.call(
2635 self._w, 'debug', boolean))
2636 def delete(self, index1, index2=None):
2637 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2638 self.tk.call(self._w, 'delete', index1, index2)
2639 def dlineinfo(self, index):
2640 """Return tuple (x,y,width,height,baseline) giving the bounding box
2641 and baseline position of the visible part of the line containing
2642 the character at INDEX."""
2643 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
2644 def get(self, index1, index2=None):
2645 """Return the text from INDEX1 to INDEX2 (not included)."""
2646 return self.tk.call(self._w, 'get', index1, index2)
2647 # (Image commands are new in 8.0)
2648 def image_cget(self, index, option):
2649 """Return the value of OPTION of an embedded image at INDEX."""
2650 if option[:1] != "-":
2651 option = "-" + option
2652 if option[-1:] == "_":
2653 option = option[:-1]
2654 return self.tk.call(self._w, "image", "cget", index, option)
2655 def image_configure(self, index, cnf={}, **kw):
2656 """Configure an embedded image at INDEX."""
2657 if not cnf and not kw:
2658 cnf = {}
2659 for x in self.tk.split(
2660 self.tk.call(
2661 self._w, "image", "configure", index)):
2662 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2663 return cnf
2664 apply(self.tk.call,
2665 (self._w, "image", "configure", index)
2666 + self._options(cnf, kw))
2667 def image_create(self, index, cnf={}, **kw):
2668 """Create an embedded image at INDEX."""
2669 return apply(self.tk.call,
2670 (self._w, "image", "create", index)
2671 + self._options(cnf, kw))
2672 def image_names(self):
2673 """Return all names of embedded images in this widget."""
2674 return self.tk.call(self._w, "image", "names")
2675 def index(self, index):
2676 """Return the index in the form line.char for INDEX."""
2677 return self.tk.call(self._w, 'index', index)
2678 def insert(self, index, chars, *args):
2679 """Insert CHARS before the characters at INDEX. An additional
2680 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2681 self.tk.call((self._w, 'insert', index, chars) + args)
2682 def mark_gravity(self, markName, direction=None):
2683 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2684 Return the current value if None is given for DIRECTION."""
2685 return self.tk.call(
2686 (self._w, 'mark', 'gravity', markName, direction))
2687 def mark_names(self):
2688 """Return all mark names."""
2689 return self.tk.splitlist(self.tk.call(
2690 self._w, 'mark', 'names'))
2691 def mark_set(self, markName, index):
2692 """Set mark MARKNAME before the character at INDEX."""
2693 self.tk.call(self._w, 'mark', 'set', markName, index)
2694 def mark_unset(self, *markNames):
2695 """Delete all marks in MARKNAMES."""
2696 self.tk.call((self._w, 'mark', 'unset') + markNames)
2697 def mark_next(self, index):
2698 """Return the name of the next mark after INDEX."""
2699 return self.tk.call(self._w, 'mark', 'next', index) or None
2700 def mark_previous(self, index):
2701 """Return the name of the previous mark before INDEX."""
2702 return self.tk.call(self._w, 'mark', 'previous', index) or None
2703 def scan_mark(self, x, y):
2704 """Remember the current X, Y coordinates."""
2705 self.tk.call(self._w, 'scan', 'mark', x, y)
2706 def scan_dragto(self, x, y):
2707 """Adjust the view of the text to 10 times the
2708 difference between X and Y and the coordinates given in
2709 scan_mark."""
2710 self.tk.call(self._w, 'scan', 'dragto', x, y)
2711 def search(self, pattern, index, stopindex=None,
2712 forwards=None, backwards=None, exact=None,
2713 regexp=None, nocase=None, count=None):
2714 """Search PATTERN beginning from INDEX until STOPINDEX.
2715 Return the index of the first character of a match or an empty string."""
2716 args = [self._w, 'search']
2717 if forwards: args.append('-forwards')
2718 if backwards: args.append('-backwards')
2719 if exact: args.append('-exact')
2720 if regexp: args.append('-regexp')
2721 if nocase: args.append('-nocase')
2722 if count: args.append('-count'); args.append(count)
2723 if pattern[0] == '-': args.append('--')
2724 args.append(pattern)
2725 args.append(index)
2726 if stopindex: args.append(stopindex)
2727 return self.tk.call(tuple(args))
2728 def see(self, index):
2729 """Scroll such that the character at INDEX is visible."""
2730 self.tk.call(self._w, 'see', index)
2731 def tag_add(self, tagName, index1, *args):
2732 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2733 Additional pairs of indices may follow in ARGS."""
2734 self.tk.call(
2735 (self._w, 'tag', 'add', tagName, index1) + args)
2736 def tag_unbind(self, tagName, sequence, funcid=None):
2737 """Unbind for all characters with TAGNAME for event SEQUENCE the
2738 function identified with FUNCID."""
2739 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2740 if funcid:
2741 self.deletecommand(funcid)
2742 def tag_bind(self, tagName, sequence, func, add=None):
2743 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002744
Fredrik Lundh06d28152000-08-09 18:03:12 +00002745 An additional boolean parameter ADD specifies whether FUNC will be
2746 called additionally to the other bound function or whether it will
2747 replace the previous function. See bind for the return value."""
2748 return self._bind((self._w, 'tag', 'bind', tagName),
2749 sequence, func, add)
2750 def tag_cget(self, tagName, option):
2751 """Return the value of OPTION for tag TAGNAME."""
2752 if option[:1] != '-':
2753 option = '-' + option
2754 if option[-1:] == '_':
2755 option = option[:-1]
2756 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
2757 def tag_configure(self, tagName, cnf={}, **kw):
2758 """Configure a tag TAGNAME."""
2759 if type(cnf) == StringType:
2760 x = self.tk.split(self.tk.call(
2761 self._w, 'tag', 'configure', tagName, '-'+cnf))
2762 return (x[0][1:],) + x[1:]
2763 self.tk.call(
2764 (self._w, 'tag', 'configure', tagName)
2765 + self._options(cnf, kw))
2766 tag_config = tag_configure
2767 def tag_delete(self, *tagNames):
2768 """Delete all tags in TAGNAMES."""
2769 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2770 def tag_lower(self, tagName, belowThis=None):
2771 """Change the priority of tag TAGNAME such that it is lower
2772 than the priority of BELOWTHIS."""
2773 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2774 def tag_names(self, index=None):
2775 """Return a list of all tag names."""
2776 return self.tk.splitlist(
2777 self.tk.call(self._w, 'tag', 'names', index))
2778 def tag_nextrange(self, tagName, index1, index2=None):
2779 """Return a list of start and end index for the first sequence of
2780 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2781 The text is searched forward from INDEX1."""
2782 return self.tk.splitlist(self.tk.call(
2783 self._w, 'tag', 'nextrange', tagName, index1, index2))
2784 def tag_prevrange(self, tagName, index1, index2=None):
2785 """Return a list of start and end index for the first sequence of
2786 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2787 The text is searched backwards from INDEX1."""
2788 return self.tk.splitlist(self.tk.call(
2789 self._w, 'tag', 'prevrange', tagName, index1, index2))
2790 def tag_raise(self, tagName, aboveThis=None):
2791 """Change the priority of tag TAGNAME such that it is higher
2792 than the priority of ABOVETHIS."""
2793 self.tk.call(
2794 self._w, 'tag', 'raise', tagName, aboveThis)
2795 def tag_ranges(self, tagName):
2796 """Return a list of ranges of text which have tag TAGNAME."""
2797 return self.tk.splitlist(self.tk.call(
2798 self._w, 'tag', 'ranges', tagName))
2799 def tag_remove(self, tagName, index1, index2=None):
2800 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2801 self.tk.call(
2802 self._w, 'tag', 'remove', tagName, index1, index2)
2803 def window_cget(self, index, option):
2804 """Return the value of OPTION of an embedded window at INDEX."""
2805 if option[:1] != '-':
2806 option = '-' + option
2807 if option[-1:] == '_':
2808 option = option[:-1]
2809 return self.tk.call(self._w, 'window', 'cget', index, option)
2810 def window_configure(self, index, cnf={}, **kw):
2811 """Configure an embedded window at INDEX."""
2812 if type(cnf) == StringType:
2813 x = self.tk.split(self.tk.call(
2814 self._w, 'window', 'configure',
2815 index, '-'+cnf))
2816 return (x[0][1:],) + x[1:]
2817 self.tk.call(
2818 (self._w, 'window', 'configure', index)
2819 + self._options(cnf, kw))
2820 window_config = window_configure
2821 def window_create(self, index, cnf={}, **kw):
2822 """Create a window at INDEX."""
2823 self.tk.call(
2824 (self._w, 'window', 'create', index)
2825 + self._options(cnf, kw))
2826 def window_names(self):
2827 """Return all names of embedded windows in this widget."""
2828 return self.tk.splitlist(
2829 self.tk.call(self._w, 'window', 'names'))
2830 def xview(self, *what):
2831 """Query and change horizontal position of the view."""
2832 if not what:
2833 return self._getdoubles(self.tk.call(self._w, 'xview'))
2834 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002835 def xview_moveto(self, fraction):
2836 """Adjusts the view in the window so that FRACTION of the
2837 total width of the canvas is off-screen to the left."""
2838 self.tk.call(self._w, 'xview', 'moveto', fraction)
2839 def xview_scroll(self, number, what):
2840 """Shift the x-view according to NUMBER which is measured
2841 in "units" or "pages" (WHAT)."""
2842 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002843 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002844 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002845 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002846 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002847 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002848 def yview_moveto(self, fraction):
2849 """Adjusts the view in the window so that FRACTION of the
2850 total height of the canvas is off-screen to the top."""
2851 self.tk.call(self._w, 'yview', 'moveto', fraction)
2852 def yview_scroll(self, number, what):
2853 """Shift the y-view according to NUMBER which is measured
2854 in "units" or "pages" (WHAT)."""
2855 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002856 def yview_pickplace(self, *what):
2857 """Obsolete function, use see."""
2858 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00002859
Guido van Rossum28574b51996-10-21 15:16:51 +00002860class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002861 """Internal class. It wraps the command in the widget OptionMenu."""
2862 def __init__(self, var, value, callback=None):
2863 self.__value = value
2864 self.__var = var
2865 self.__callback = callback
2866 def __call__(self, *args):
2867 self.__var.set(self.__value)
2868 if self.__callback:
2869 apply(self.__callback, (self.__value,)+args)
Guido van Rossum28574b51996-10-21 15:16:51 +00002870
2871class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002872 """OptionMenu which allows the user to select a value from a menu."""
2873 def __init__(self, master, variable, value, *values, **kwargs):
2874 """Construct an optionmenu widget with the parent MASTER, with
2875 the resource textvariable set to VARIABLE, the initially selected
2876 value VALUE, the other menu values VALUES and an additional
2877 keyword argument command."""
2878 kw = {"borderwidth": 2, "textvariable": variable,
2879 "indicatoron": 1, "relief": RAISED, "anchor": "c",
2880 "highlightthickness": 2}
2881 Widget.__init__(self, master, "menubutton", kw)
2882 self.widgetName = 'tk_optionMenu'
2883 menu = self.__menu = Menu(self, name="menu", tearoff=0)
2884 self.menuname = menu._w
2885 # 'command' is the only supported keyword
2886 callback = kwargs.get('command')
2887 if kwargs.has_key('command'):
2888 del kwargs['command']
2889 if kwargs:
2890 raise TclError, 'unknown option -'+kwargs.keys()[0]
2891 menu.add_command(label=value,
2892 command=_setit(variable, value, callback))
2893 for v in values:
2894 menu.add_command(label=v,
2895 command=_setit(variable, v, callback))
2896 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00002897
Fredrik Lundh06d28152000-08-09 18:03:12 +00002898 def __getitem__(self, name):
2899 if name == 'menu':
2900 return self.__menu
2901 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00002902
Fredrik Lundh06d28152000-08-09 18:03:12 +00002903 def destroy(self):
2904 """Destroy this widget and the associated menu."""
2905 Menubutton.destroy(self)
2906 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00002907
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002908class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002909 """Base class for images."""
2910 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
2911 self.name = None
2912 if not master:
2913 master = _default_root
2914 if not master:
2915 raise RuntimeError, 'Too early to create image'
2916 self.tk = master.tk
2917 if not name:
2918 name = `id(self)`
2919 # The following is needed for systems where id(x)
2920 # can return a negative number, such as Linux/m68k:
2921 if name[0] == '-': name = '_' + name[1:]
2922 if kw and cnf: cnf = _cnfmerge((cnf, kw))
2923 elif kw: cnf = kw
2924 options = ()
2925 for k, v in cnf.items():
2926 if callable(v):
2927 v = self._register(v)
2928 options = options + ('-'+k, v)
2929 self.tk.call(('image', 'create', imgtype, name,) + options)
2930 self.name = name
2931 def __str__(self): return self.name
2932 def __del__(self):
2933 if self.name:
2934 try:
2935 self.tk.call('image', 'delete', self.name)
2936 except TclError:
2937 # May happen if the root was destroyed
2938 pass
2939 def __setitem__(self, key, value):
2940 self.tk.call(self.name, 'configure', '-'+key, value)
2941 def __getitem__(self, key):
2942 return self.tk.call(self.name, 'configure', '-'+key)
2943 def configure(self, **kw):
2944 """Configure the image."""
2945 res = ()
2946 for k, v in _cnfmerge(kw).items():
2947 if v is not None:
2948 if k[-1] == '_': k = k[:-1]
2949 if callable(v):
2950 v = self._register(v)
2951 res = res + ('-'+k, v)
2952 self.tk.call((self.name, 'config') + res)
2953 config = configure
2954 def height(self):
2955 """Return the height of the image."""
2956 return getint(
2957 self.tk.call('image', 'height', self.name))
2958 def type(self):
2959 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
2960 return self.tk.call('image', 'type', self.name)
2961 def width(self):
2962 """Return the width of the image."""
2963 return getint(
2964 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002965
2966class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002967 """Widget which can display colored images in GIF, PPM/PGM format."""
2968 def __init__(self, name=None, cnf={}, master=None, **kw):
2969 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002970
Fredrik Lundh06d28152000-08-09 18:03:12 +00002971 Valid resource names: data, format, file, gamma, height, palette,
2972 width."""
2973 apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
2974 def blank(self):
2975 """Display a transparent image."""
2976 self.tk.call(self.name, 'blank')
2977 def cget(self, option):
2978 """Return the value of OPTION."""
2979 return self.tk.call(self.name, 'cget', '-' + option)
2980 # XXX config
2981 def __getitem__(self, key):
2982 return self.tk.call(self.name, 'cget', '-' + key)
2983 # XXX copy -from, -to, ...?
2984 def copy(self):
2985 """Return a new PhotoImage with the same image as this widget."""
2986 destImage = PhotoImage()
2987 self.tk.call(destImage, 'copy', self.name)
2988 return destImage
2989 def zoom(self,x,y=''):
2990 """Return a new PhotoImage with the same image as this widget
2991 but zoom it with X and Y."""
2992 destImage = PhotoImage()
2993 if y=='': y=x
2994 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
2995 return destImage
2996 def subsample(self,x,y=''):
2997 """Return a new PhotoImage based on the same image as this widget
2998 but use only every Xth or Yth pixel."""
2999 destImage = PhotoImage()
3000 if y=='': y=x
3001 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3002 return destImage
3003 def get(self, x, y):
3004 """Return the color (red, green, blue) of the pixel at X,Y."""
3005 return self.tk.call(self.name, 'get', x, y)
3006 def put(self, data, to=None):
3007 """Put row formated colors to image starting from
3008 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3009 args = (self.name, 'put', data)
3010 if to:
3011 if to[0] == '-to':
3012 to = to[1:]
3013 args = args + ('-to',) + tuple(to)
3014 self.tk.call(args)
3015 # XXX read
3016 def write(self, filename, format=None, from_coords=None):
3017 """Write image to file FILENAME in FORMAT starting from
3018 position FROM_COORDS."""
3019 args = (self.name, 'write', filename)
3020 if format:
3021 args = args + ('-format', format)
3022 if from_coords:
3023 args = args + ('-from',) + tuple(from_coords)
3024 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003025
3026class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003027 """Widget which can display a bitmap."""
3028 def __init__(self, name=None, cnf={}, master=None, **kw):
3029 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003030
Fredrik Lundh06d28152000-08-09 18:03:12 +00003031 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3032 apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003033
3034def image_names(): return _default_root.tk.call('image', 'names')
3035def image_types(): return _default_root.tk.call('image', 'types')
3036
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003037######################################################################
3038# Extensions:
3039
3040class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003041 def __init__(self, master=None, cnf={}, **kw):
3042 Widget.__init__(self, master, 'studbutton', cnf, kw)
3043 self.bind('<Any-Enter>', self.tkButtonEnter)
3044 self.bind('<Any-Leave>', self.tkButtonLeave)
3045 self.bind('<1>', self.tkButtonDown)
3046 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003047
3048class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003049 def __init__(self, master=None, cnf={}, **kw):
3050 Widget.__init__(self, master, 'tributton', cnf, kw)
3051 self.bind('<Any-Enter>', self.tkButtonEnter)
3052 self.bind('<Any-Leave>', self.tkButtonLeave)
3053 self.bind('<1>', self.tkButtonDown)
3054 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3055 self['fg'] = self['bg']
3056 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003057
Guido van Rossumc417ef81996-08-21 23:38:59 +00003058######################################################################
3059# Test:
3060
3061def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003062 root = Tk()
3063 text = "This is Tcl/Tk version %s" % TclVersion
3064 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003065 try:
3066 text = text + unicode("\nThis should be a cedilla: \347",
3067 "iso-8859-1")
3068 except NameError:
3069 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003070 label = Label(root, text=text)
3071 label.pack()
3072 test = Button(root, text="Click me!",
3073 command=lambda root=root: root.test.configure(
3074 text="[%s]" % root.test['text']))
3075 test.pack()
3076 root.test = test
3077 quit = Button(root, text="QUIT", command=root.destroy)
3078 quit.pack()
3079 # The following three commands are needed so the window pops
3080 # up on top on Windows...
3081 root.iconify()
3082 root.update()
3083 root.deiconify()
3084 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003085
3086if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003087 _test()
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003088