blob: 31b072cb4cb3c9bf3a1b64550bddeb6e1b511738 [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)
Fredrik Lundha249f162000-09-07 15:05:09 +00001053 try:
1054 e.delta = getint(D)
1055 except ValueError:
1056 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001057 return (e,)
1058 def _report_exception(self):
1059 """Internal function."""
1060 import sys
1061 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1062 root = self._root()
1063 root.report_callback_exception(exc, val, tb)
1064 # These used to be defined in Widget:
1065 def configure(self, cnf=None, **kw):
1066 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001067
Fredrik Lundh06d28152000-08-09 18:03:12 +00001068 The values for resources are specified as keyword
1069 arguments. To get an overview about
1070 the allowed keyword arguments call the method keys.
1071 """
1072 # XXX ought to generalize this so tag_config etc. can use it
1073 if kw:
1074 cnf = _cnfmerge((cnf, kw))
1075 elif cnf:
1076 cnf = _cnfmerge(cnf)
1077 if cnf is None:
1078 cnf = {}
1079 for x in self.tk.split(
1080 self.tk.call(self._w, 'configure')):
1081 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1082 return cnf
1083 if type(cnf) is StringType:
1084 x = self.tk.split(self.tk.call(
1085 self._w, 'configure', '-'+cnf))
1086 return (x[0][1:],) + x[1:]
1087 self.tk.call((self._w, 'configure')
1088 + self._options(cnf))
1089 config = configure
1090 def cget(self, key):
1091 """Return the resource value for a KEY given as string."""
1092 return self.tk.call(self._w, 'cget', '-' + key)
1093 __getitem__ = cget
1094 def __setitem__(self, key, value):
1095 self.configure({key: value})
1096 def keys(self):
1097 """Return a list of all resource names of this widget."""
1098 return map(lambda x: x[0][1:],
1099 self.tk.split(self.tk.call(self._w, 'configure')))
1100 def __str__(self):
1101 """Return the window path name of this widget."""
1102 return self._w
1103 # Pack methods that apply to the master
1104 _noarg_ = ['_noarg_']
1105 def pack_propagate(self, flag=_noarg_):
1106 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001107
Fredrik Lundh06d28152000-08-09 18:03:12 +00001108 A boolean argument specifies whether the geometry information
1109 of the slaves will determine the size of this widget. If no argument
1110 is given the current setting will be returned.
1111 """
1112 if flag is Misc._noarg_:
1113 return self._getboolean(self.tk.call(
1114 'pack', 'propagate', self._w))
1115 else:
1116 self.tk.call('pack', 'propagate', self._w, flag)
1117 propagate = pack_propagate
1118 def pack_slaves(self):
1119 """Return a list of all slaves of this widget
1120 in its packing order."""
1121 return map(self._nametowidget,
1122 self.tk.splitlist(
1123 self.tk.call('pack', 'slaves', self._w)))
1124 slaves = pack_slaves
1125 # Place method that applies to the master
1126 def place_slaves(self):
1127 """Return a list of all slaves of this widget
1128 in its packing order."""
1129 return map(self._nametowidget,
1130 self.tk.splitlist(
1131 self.tk.call(
1132 'place', 'slaves', self._w)))
1133 # Grid methods that apply to the master
1134 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1135 """Return a tuple of integer coordinates for the bounding
1136 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001137
Fredrik Lundh06d28152000-08-09 18:03:12 +00001138 If COLUMN, ROW is given the bounding box applies from
1139 the cell with row and column 0 to the specified
1140 cell. If COL2 and ROW2 are given the bounding box
1141 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001142
Fredrik Lundh06d28152000-08-09 18:03:12 +00001143 The returned integers specify the offset of the upper left
1144 corner in the master widget and the width and height.
1145 """
1146 args = ('grid', 'bbox', self._w)
1147 if column is not None and row is not None:
1148 args = args + (column, row)
1149 if col2 is not None and row2 is not None:
1150 args = args + (col2, row2)
1151 return self._getints(apply(self.tk.call, args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001152
Fredrik Lundh06d28152000-08-09 18:03:12 +00001153 bbox = grid_bbox
1154 def _grid_configure(self, command, index, cnf, kw):
1155 """Internal function."""
1156 if type(cnf) is StringType and not kw:
1157 if cnf[-1:] == '_':
1158 cnf = cnf[:-1]
1159 if cnf[:1] != '-':
1160 cnf = '-'+cnf
1161 options = (cnf,)
1162 else:
1163 options = self._options(cnf, kw)
1164 if not options:
1165 res = self.tk.call('grid',
1166 command, self._w, index)
1167 words = self.tk.splitlist(res)
1168 dict = {}
1169 for i in range(0, len(words), 2):
1170 key = words[i][1:]
1171 value = words[i+1]
1172 if not value:
1173 value = None
1174 elif '.' in value:
1175 value = getdouble(value)
1176 else:
1177 value = getint(value)
1178 dict[key] = value
1179 return dict
1180 res = self.tk.call(
1181 ('grid', command, self._w, index)
1182 + options)
1183 if len(options) == 1:
1184 if not res: return None
1185 # In Tk 7.5, -width can be a float
1186 if '.' in res: return getdouble(res)
1187 return getint(res)
1188 def grid_columnconfigure(self, index, cnf={}, **kw):
1189 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001190
Fredrik Lundh06d28152000-08-09 18:03:12 +00001191 Valid resources are minsize (minimum size of the column),
1192 weight (how much does additional space propagate to this column)
1193 and pad (how much space to let additionally)."""
1194 return self._grid_configure('columnconfigure', index, cnf, kw)
1195 columnconfigure = grid_columnconfigure
1196 def grid_propagate(self, flag=_noarg_):
1197 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001198
Fredrik Lundh06d28152000-08-09 18:03:12 +00001199 A boolean argument specifies whether the geometry information
1200 of the slaves will determine the size of this widget. If no argument
1201 is given, the current setting will be returned.
1202 """
1203 if flag is Misc._noarg_:
1204 return self._getboolean(self.tk.call(
1205 'grid', 'propagate', self._w))
1206 else:
1207 self.tk.call('grid', 'propagate', self._w, flag)
1208 def grid_rowconfigure(self, index, cnf={}, **kw):
1209 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001210
Fredrik Lundh06d28152000-08-09 18:03:12 +00001211 Valid resources are minsize (minimum size of the row),
1212 weight (how much does additional space propagate to this row)
1213 and pad (how much space to let additionally)."""
1214 return self._grid_configure('rowconfigure', index, cnf, kw)
1215 rowconfigure = grid_rowconfigure
1216 def grid_size(self):
1217 """Return a tuple of the number of column and rows in the grid."""
1218 return self._getints(
1219 self.tk.call('grid', 'size', self._w)) or None
1220 size = grid_size
1221 def grid_slaves(self, row=None, column=None):
1222 """Return a list of all slaves of this widget
1223 in its packing order."""
1224 args = ()
1225 if row is not None:
1226 args = args + ('-row', row)
1227 if column is not None:
1228 args = args + ('-column', column)
1229 return map(self._nametowidget,
1230 self.tk.splitlist(self.tk.call(
1231 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001232
Fredrik Lundh06d28152000-08-09 18:03:12 +00001233 # Support for the "event" command, new in Tk 4.2.
1234 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001235
Fredrik Lundh06d28152000-08-09 18:03:12 +00001236 def event_add(self, virtual, *sequences):
1237 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1238 to an event SEQUENCE such that the virtual event is triggered
1239 whenever SEQUENCE occurs."""
1240 args = ('event', 'add', virtual) + sequences
1241 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001242
Fredrik Lundh06d28152000-08-09 18:03:12 +00001243 def event_delete(self, virtual, *sequences):
1244 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1245 args = ('event', 'delete', virtual) + sequences
1246 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001247
Fredrik Lundh06d28152000-08-09 18:03:12 +00001248 def event_generate(self, sequence, **kw):
1249 """Generate an event SEQUENCE. Additional
1250 keyword arguments specify parameter of the event
1251 (e.g. x, y, rootx, rooty)."""
1252 args = ('event', 'generate', self._w, sequence)
1253 for k, v in kw.items():
1254 args = args + ('-%s' % k, str(v))
1255 self.tk.call(args)
1256
1257 def event_info(self, virtual=None):
1258 """Return a list of all virtual events or the information
1259 about the SEQUENCE bound to the virtual event VIRTUAL."""
1260 return self.tk.splitlist(
1261 self.tk.call('event', 'info', virtual))
1262
1263 # Image related commands
1264
1265 def image_names(self):
1266 """Return a list of all existing image names."""
1267 return self.tk.call('image', 'names')
1268
1269 def image_types(self):
1270 """Return a list of all available image types (e.g. phote bitmap)."""
1271 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001272
Guido van Rossum80f8be81997-12-02 19:51:39 +00001273
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001274class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001275 """Internal class. Stores function to call when some user
1276 defined Tcl function is called e.g. after an event occurred."""
1277 def __init__(self, func, subst, widget):
1278 """Store FUNC, SUBST and WIDGET as members."""
1279 self.func = func
1280 self.subst = subst
1281 self.widget = widget
1282 def __call__(self, *args):
1283 """Apply first function SUBST to arguments, than FUNC."""
1284 try:
1285 if self.subst:
1286 args = apply(self.subst, args)
1287 return apply(self.func, args)
1288 except SystemExit, msg:
1289 raise SystemExit, msg
1290 except:
1291 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001292
Guido van Rossume365a591998-05-01 19:48:20 +00001293
Guido van Rossum18468821994-06-20 07:49:28 +00001294class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001295 """Provides functions for the communication with the window manager."""
1296 def wm_aspect(self,
1297 minNumer=None, minDenom=None,
1298 maxNumer=None, maxDenom=None):
1299 """Instruct the window manager to set the aspect ratio (width/height)
1300 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1301 of the actual values if no argument is given."""
1302 return self._getints(
1303 self.tk.call('wm', 'aspect', self._w,
1304 minNumer, minDenom,
1305 maxNumer, maxDenom))
1306 aspect = wm_aspect
1307 def wm_client(self, name=None):
1308 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1309 current value."""
1310 return self.tk.call('wm', 'client', self._w, name)
1311 client = wm_client
1312 def wm_colormapwindows(self, *wlist):
1313 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1314 of this widget. This list contains windows whose colormaps differ from their
1315 parents. Return current list of widgets if WLIST is empty."""
1316 if len(wlist) > 1:
1317 wlist = (wlist,) # Tk needs a list of windows here
1318 args = ('wm', 'colormapwindows', self._w) + wlist
1319 return map(self._nametowidget, self.tk.call(args))
1320 colormapwindows = wm_colormapwindows
1321 def wm_command(self, value=None):
1322 """Store VALUE in WM_COMMAND property. It is the command
1323 which shall be used to invoke the application. Return current
1324 command if VALUE is None."""
1325 return self.tk.call('wm', 'command', self._w, value)
1326 command = wm_command
1327 def wm_deiconify(self):
1328 """Deiconify this widget. If it was never mapped it will not be mapped.
1329 On Windows it will raise this widget and give it the focus."""
1330 return self.tk.call('wm', 'deiconify', self._w)
1331 deiconify = wm_deiconify
1332 def wm_focusmodel(self, model=None):
1333 """Set focus model to MODEL. "active" means that this widget will claim
1334 the focus itself, "passive" means that the window manager shall give
1335 the focus. Return current focus model if MODEL is None."""
1336 return self.tk.call('wm', 'focusmodel', self._w, model)
1337 focusmodel = wm_focusmodel
1338 def wm_frame(self):
1339 """Return identifier for decorative frame of this widget if present."""
1340 return self.tk.call('wm', 'frame', self._w)
1341 frame = wm_frame
1342 def wm_geometry(self, newGeometry=None):
1343 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1344 current value if None is given."""
1345 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1346 geometry = wm_geometry
1347 def wm_grid(self,
1348 baseWidth=None, baseHeight=None,
1349 widthInc=None, heightInc=None):
1350 """Instruct the window manager that this widget shall only be
1351 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1352 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1353 number of grid units requested in Tk_GeometryRequest."""
1354 return self._getints(self.tk.call(
1355 'wm', 'grid', self._w,
1356 baseWidth, baseHeight, widthInc, heightInc))
1357 grid = wm_grid
1358 def wm_group(self, pathName=None):
1359 """Set the group leader widgets for related widgets to PATHNAME. Return
1360 the group leader of this widget if None is given."""
1361 return self.tk.call('wm', 'group', self._w, pathName)
1362 group = wm_group
1363 def wm_iconbitmap(self, bitmap=None):
1364 """Set bitmap for the iconified widget to BITMAP. Return
1365 the bitmap if None is given."""
1366 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1367 iconbitmap = wm_iconbitmap
1368 def wm_iconify(self):
1369 """Display widget as icon."""
1370 return self.tk.call('wm', 'iconify', self._w)
1371 iconify = wm_iconify
1372 def wm_iconmask(self, bitmap=None):
1373 """Set mask for the icon bitmap of this widget. Return the
1374 mask if None is given."""
1375 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1376 iconmask = wm_iconmask
1377 def wm_iconname(self, newName=None):
1378 """Set the name of the icon for this widget. Return the name if
1379 None is given."""
1380 return self.tk.call('wm', 'iconname', self._w, newName)
1381 iconname = wm_iconname
1382 def wm_iconposition(self, x=None, y=None):
1383 """Set the position of the icon of this widget to X and Y. Return
1384 a tuple of the current values of X and X if None is given."""
1385 return self._getints(self.tk.call(
1386 'wm', 'iconposition', self._w, x, y))
1387 iconposition = wm_iconposition
1388 def wm_iconwindow(self, pathName=None):
1389 """Set widget PATHNAME to be displayed instead of icon. Return the current
1390 value if None is given."""
1391 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1392 iconwindow = wm_iconwindow
1393 def wm_maxsize(self, width=None, height=None):
1394 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1395 the values are given in grid units. Return the current values if None
1396 is given."""
1397 return self._getints(self.tk.call(
1398 'wm', 'maxsize', self._w, width, height))
1399 maxsize = wm_maxsize
1400 def wm_minsize(self, width=None, height=None):
1401 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1402 the values are given in grid units. Return the current values if None
1403 is given."""
1404 return self._getints(self.tk.call(
1405 'wm', 'minsize', self._w, width, height))
1406 minsize = wm_minsize
1407 def wm_overrideredirect(self, boolean=None):
1408 """Instruct the window manager to ignore this widget
1409 if BOOLEAN is given with 1. Return the current value if None
1410 is given."""
1411 return self._getboolean(self.tk.call(
1412 'wm', 'overrideredirect', self._w, boolean))
1413 overrideredirect = wm_overrideredirect
1414 def wm_positionfrom(self, who=None):
1415 """Instruct the window manager that the position of this widget shall
1416 be defined by the user if WHO is "user", and by its own policy if WHO is
1417 "program"."""
1418 return self.tk.call('wm', 'positionfrom', self._w, who)
1419 positionfrom = wm_positionfrom
1420 def wm_protocol(self, name=None, func=None):
1421 """Bind function FUNC to command NAME for this widget.
1422 Return the function bound to NAME if None is given. NAME could be
1423 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1424 if callable(func):
1425 command = self._register(func)
1426 else:
1427 command = func
1428 return self.tk.call(
1429 'wm', 'protocol', self._w, name, command)
1430 protocol = wm_protocol
1431 def wm_resizable(self, width=None, height=None):
1432 """Instruct the window manager whether this width can be resized
1433 in WIDTH or HEIGHT. Both values are boolean values."""
1434 return self.tk.call('wm', 'resizable', self._w, width, height)
1435 resizable = wm_resizable
1436 def wm_sizefrom(self, who=None):
1437 """Instruct the window manager that the size of this widget shall
1438 be defined by the user if WHO is "user", and by its own policy if WHO is
1439 "program"."""
1440 return self.tk.call('wm', 'sizefrom', self._w, who)
1441 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001442 def wm_state(self, newstate=None):
1443 """Query or set the state of this widget as one of normal, icon,
1444 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1445 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001446 state = wm_state
1447 def wm_title(self, string=None):
1448 """Set the title of this widget."""
1449 return self.tk.call('wm', 'title', self._w, string)
1450 title = wm_title
1451 def wm_transient(self, master=None):
1452 """Instruct the window manager that this widget is transient
1453 with regard to widget MASTER."""
1454 return self.tk.call('wm', 'transient', self._w, master)
1455 transient = wm_transient
1456 def wm_withdraw(self):
1457 """Withdraw this widget from the screen such that it is unmapped
1458 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1459 return self.tk.call('wm', 'withdraw', self._w)
1460 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001461
Guido van Rossum18468821994-06-20 07:49:28 +00001462
1463class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001464 """Toplevel widget of Tk which represents mostly the main window
1465 of an appliation. It has an associated Tcl interpreter."""
1466 _w = '.'
1467 def __init__(self, screenName=None, baseName=None, className='Tk'):
1468 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1469 be created. BASENAME will be used for the identification of the profile file (see
1470 readprofile).
1471 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1472 is the name of the widget class."""
1473 global _default_root
1474 self.master = None
1475 self.children = {}
1476 if baseName is None:
1477 import sys, os
1478 baseName = os.path.basename(sys.argv[0])
1479 baseName, ext = os.path.splitext(baseName)
1480 if ext not in ('.py', '.pyc', '.pyo'):
1481 baseName = baseName + ext
1482 self.tk = _tkinter.create(screenName, baseName, className)
1483 if _MacOS:
1484 # Disable event scanning except for Command-Period
1485 _MacOS.SchedParams(1, 0)
1486 # Work around nasty MacTk bug
1487 # XXX Is this one still needed?
1488 self.update()
1489 # Version sanity checks
1490 tk_version = self.tk.getvar('tk_version')
1491 if tk_version != _tkinter.TK_VERSION:
1492 raise RuntimeError, \
1493 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1494 % (_tkinter.TK_VERSION, tk_version)
1495 tcl_version = self.tk.getvar('tcl_version')
1496 if tcl_version != _tkinter.TCL_VERSION:
1497 raise RuntimeError, \
1498 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1499 % (_tkinter.TCL_VERSION, tcl_version)
1500 if TkVersion < 4.0:
1501 raise RuntimeError, \
1502 "Tk 4.0 or higher is required; found Tk %s" \
1503 % str(TkVersion)
1504 self.tk.createcommand('tkerror', _tkerror)
1505 self.tk.createcommand('exit', _exit)
1506 self.readprofile(baseName, className)
1507 if _support_default_root and not _default_root:
1508 _default_root = self
1509 self.protocol("WM_DELETE_WINDOW", self.destroy)
1510 def destroy(self):
1511 """Destroy this and all descendants widgets. This will
1512 end the application of this Tcl interpreter."""
1513 for c in self.children.values(): c.destroy()
1514 self.tk.call('destroy', self._w)
1515 Misc.destroy(self)
1516 global _default_root
1517 if _support_default_root and _default_root is self:
1518 _default_root = None
1519 def readprofile(self, baseName, className):
1520 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1521 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1522 such a file exists in the home directory."""
1523 import os
1524 if os.environ.has_key('HOME'): home = os.environ['HOME']
1525 else: home = os.curdir
1526 class_tcl = os.path.join(home, '.%s.tcl' % className)
1527 class_py = os.path.join(home, '.%s.py' % className)
1528 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1529 base_py = os.path.join(home, '.%s.py' % baseName)
1530 dir = {'self': self}
1531 exec 'from Tkinter import *' in dir
1532 if os.path.isfile(class_tcl):
1533 print 'source', `class_tcl`
1534 self.tk.call('source', class_tcl)
1535 if os.path.isfile(class_py):
1536 print 'execfile', `class_py`
1537 execfile(class_py, dir)
1538 if os.path.isfile(base_tcl):
1539 print 'source', `base_tcl`
1540 self.tk.call('source', base_tcl)
1541 if os.path.isfile(base_py):
1542 print 'execfile', `base_py`
1543 execfile(base_py, dir)
1544 def report_callback_exception(self, exc, val, tb):
1545 """Internal function. It reports exception on sys.stderr."""
1546 import traceback, sys
1547 sys.stderr.write("Exception in Tkinter callback\n")
1548 sys.last_type = exc
1549 sys.last_value = val
1550 sys.last_traceback = tb
1551 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001552
Guido van Rossum368e06b1997-11-07 20:38:49 +00001553# Ideally, the classes Pack, Place and Grid disappear, the
1554# pack/place/grid methods are defined on the Widget class, and
1555# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1556# ...), with pack(), place() and grid() being short for
1557# pack_configure(), place_configure() and grid_columnconfigure(), and
1558# forget() being short for pack_forget(). As a practical matter, I'm
1559# afraid that there is too much code out there that may be using the
1560# Pack, Place or Grid class, so I leave them intact -- but only as
1561# backwards compatibility features. Also note that those methods that
1562# take a master as argument (e.g. pack_propagate) have been moved to
1563# the Misc class (which now incorporates all methods common between
1564# toplevel and interior widgets). Again, for compatibility, these are
1565# copied into the Pack, Place or Grid class.
1566
Guido van Rossum18468821994-06-20 07:49:28 +00001567class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001568 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001569
Fredrik Lundh06d28152000-08-09 18:03:12 +00001570 Base class to use the methods pack_* in every widget."""
1571 def pack_configure(self, cnf={}, **kw):
1572 """Pack a widget in the parent widget. Use as options:
1573 after=widget - pack it after you have packed widget
1574 anchor=NSEW (or subset) - position widget according to
1575 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001576 before=widget - pack it before you will pack widget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001577 expand=1 or 0 - expand widget if parent size grows
1578 fill=NONE or X or Y or BOTH - fill widget if widget grows
1579 in=master - use master to contain this widget
1580 ipadx=amount - add internal padding in x direction
1581 ipady=amount - add internal padding in y direction
1582 padx=amount - add padding in x direction
1583 pady=amount - add padding in y direction
1584 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1585 """
1586 self.tk.call(
1587 ('pack', 'configure', self._w)
1588 + self._options(cnf, kw))
1589 pack = configure = config = pack_configure
1590 def pack_forget(self):
1591 """Unmap this widget and do not use it for the packing order."""
1592 self.tk.call('pack', 'forget', self._w)
1593 forget = pack_forget
1594 def pack_info(self):
1595 """Return information about the packing options
1596 for this widget."""
1597 words = self.tk.splitlist(
1598 self.tk.call('pack', 'info', self._w))
1599 dict = {}
1600 for i in range(0, len(words), 2):
1601 key = words[i][1:]
1602 value = words[i+1]
1603 if value[:1] == '.':
1604 value = self._nametowidget(value)
1605 dict[key] = value
1606 return dict
1607 info = pack_info
1608 propagate = pack_propagate = Misc.pack_propagate
1609 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001610
1611class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001612 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001613
Fredrik Lundh06d28152000-08-09 18:03:12 +00001614 Base class to use the methods place_* in every widget."""
1615 def place_configure(self, cnf={}, **kw):
1616 """Place a widget in the parent widget. Use as options:
1617 in=master - master relative to which the widget is placed.
1618 x=amount - locate anchor of this widget at position x of master
1619 y=amount - locate anchor of this widget at position y of master
1620 relx=amount - locate anchor of this widget between 0.0 and 1.0
1621 relative to width of master (1.0 is right edge)
1622 rely=amount - locate anchor of this widget between 0.0 and 1.0
1623 relative to height of master (1.0 is bottom edge)
1624 anchor=NSEW (or subset) - position anchor according to given direction
1625 width=amount - width of this widget in pixel
1626 height=amount - height of this widget in pixel
1627 relwidth=amount - width of this widget between 0.0 and 1.0
1628 relative to width of master (1.0 is the same width
1629 as the master)
1630 relheight=amount - height of this widget between 0.0 and 1.0
1631 relative to height of master (1.0 is the same
1632 height as the master)
1633 bordermode="inside" or "outside" - whether to take border width of master widget
1634 into account
1635 """
1636 for k in ['in_']:
1637 if kw.has_key(k):
1638 kw[k[:-1]] = kw[k]
1639 del kw[k]
1640 self.tk.call(
1641 ('place', 'configure', self._w)
1642 + self._options(cnf, kw))
1643 place = configure = config = place_configure
1644 def place_forget(self):
1645 """Unmap this widget."""
1646 self.tk.call('place', 'forget', self._w)
1647 forget = place_forget
1648 def place_info(self):
1649 """Return information about the placing options
1650 for this widget."""
1651 words = self.tk.splitlist(
1652 self.tk.call('place', 'info', self._w))
1653 dict = {}
1654 for i in range(0, len(words), 2):
1655 key = words[i][1:]
1656 value = words[i+1]
1657 if value[:1] == '.':
1658 value = self._nametowidget(value)
1659 dict[key] = value
1660 return dict
1661 info = place_info
1662 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001663
Guido van Rossum37dcab11996-05-16 16:00:19 +00001664class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001665 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001666
Fredrik Lundh06d28152000-08-09 18:03:12 +00001667 Base class to use the methods grid_* in every widget."""
1668 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1669 def grid_configure(self, cnf={}, **kw):
1670 """Position a widget in the parent widget in a grid. Use as options:
1671 column=number - use cell identified with given column (starting with 0)
1672 columnspan=number - this widget will span several columns
1673 in=master - use master to contain this widget
1674 ipadx=amount - add internal padding in x direction
1675 ipady=amount - add internal padding in y direction
1676 padx=amount - add padding in x direction
1677 pady=amount - add padding in y direction
1678 row=number - use cell identified with given row (starting with 0)
1679 rowspan=number - this widget will span several rows
1680 sticky=NSEW - if cell is larger on which sides will this
1681 widget stick to the cell boundary
1682 """
1683 self.tk.call(
1684 ('grid', 'configure', self._w)
1685 + self._options(cnf, kw))
1686 grid = configure = config = grid_configure
1687 bbox = grid_bbox = Misc.grid_bbox
1688 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1689 def grid_forget(self):
1690 """Unmap this widget."""
1691 self.tk.call('grid', 'forget', self._w)
1692 forget = grid_forget
1693 def grid_remove(self):
1694 """Unmap this widget but remember the grid options."""
1695 self.tk.call('grid', 'remove', self._w)
1696 def grid_info(self):
1697 """Return information about the options
1698 for positioning this widget in a grid."""
1699 words = self.tk.splitlist(
1700 self.tk.call('grid', 'info', self._w))
1701 dict = {}
1702 for i in range(0, len(words), 2):
1703 key = words[i][1:]
1704 value = words[i+1]
1705 if value[:1] == '.':
1706 value = self._nametowidget(value)
1707 dict[key] = value
1708 return dict
1709 info = grid_info
1710 def grid_location(self, x, y):
1711 """Return a tuple of column and row which identify the cell
1712 at which the pixel at position X and Y inside the master
1713 widget is located."""
1714 return self._getints(
1715 self.tk.call(
1716 'grid', 'location', self._w, x, y)) or None
1717 location = grid_location
1718 propagate = grid_propagate = Misc.grid_propagate
1719 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1720 size = grid_size = Misc.grid_size
1721 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001722
Guido van Rossum368e06b1997-11-07 20:38:49 +00001723class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001724 """Internal class."""
1725 def _setup(self, master, cnf):
1726 """Internal function. Sets up information about children."""
1727 if _support_default_root:
1728 global _default_root
1729 if not master:
1730 if not _default_root:
1731 _default_root = Tk()
1732 master = _default_root
1733 self.master = master
1734 self.tk = master.tk
1735 name = None
1736 if cnf.has_key('name'):
1737 name = cnf['name']
1738 del cnf['name']
1739 if not name:
1740 name = `id(self)`
1741 self._name = name
1742 if master._w=='.':
1743 self._w = '.' + name
1744 else:
1745 self._w = master._w + '.' + name
1746 self.children = {}
1747 if self.master.children.has_key(self._name):
1748 self.master.children[self._name].destroy()
1749 self.master.children[self._name] = self
1750 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1751 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1752 and appropriate options."""
1753 if kw:
1754 cnf = _cnfmerge((cnf, kw))
1755 self.widgetName = widgetName
1756 BaseWidget._setup(self, master, cnf)
1757 classes = []
1758 for k in cnf.keys():
1759 if type(k) is ClassType:
1760 classes.append((k, cnf[k]))
1761 del cnf[k]
1762 self.tk.call(
1763 (widgetName, self._w) + extra + self._options(cnf))
1764 for k, v in classes:
1765 k.configure(self, v)
1766 def destroy(self):
1767 """Destroy this and all descendants widgets."""
1768 for c in self.children.values(): c.destroy()
1769 if self.master.children.has_key(self._name):
1770 del self.master.children[self._name]
1771 self.tk.call('destroy', self._w)
1772 Misc.destroy(self)
1773 def _do(self, name, args=()):
1774 # XXX Obsolete -- better use self.tk.call directly!
1775 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001776
Guido van Rossum368e06b1997-11-07 20:38:49 +00001777class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001778 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001779
Fredrik Lundh06d28152000-08-09 18:03:12 +00001780 Base class for a widget which can be positioned with the geometry managers
1781 Pack, Place or Grid."""
1782 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001783
1784class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001785 """Toplevel widget, e.g. for dialogs."""
1786 def __init__(self, master=None, cnf={}, **kw):
1787 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001788
Fredrik Lundh06d28152000-08-09 18:03:12 +00001789 Valid resource names: background, bd, bg, borderwidth, class,
1790 colormap, container, cursor, height, highlightbackground,
1791 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1792 use, visual, width."""
1793 if kw:
1794 cnf = _cnfmerge((cnf, kw))
1795 extra = ()
1796 for wmkey in ['screen', 'class_', 'class', 'visual',
1797 'colormap']:
1798 if cnf.has_key(wmkey):
1799 val = cnf[wmkey]
1800 # TBD: a hack needed because some keys
1801 # are not valid as keyword arguments
1802 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1803 else: opt = '-'+wmkey
1804 extra = extra + (opt, val)
1805 del cnf[wmkey]
1806 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1807 root = self._root()
1808 self.iconname(root.iconname())
1809 self.title(root.title())
1810 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001811
1812class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001813 """Button widget."""
1814 def __init__(self, master=None, cnf={}, **kw):
1815 """Construct a button widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001816
Fredrik Lundh06d28152000-08-09 18:03:12 +00001817 Valid resource names: activebackground, activeforeground, anchor,
1818 background, bd, bg, bitmap, borderwidth, command, cursor, default,
1819 disabledforeground, fg, font, foreground, height,
1820 highlightbackground, highlightcolor, highlightthickness, image,
1821 justify, padx, pady, relief, state, takefocus, text, textvariable,
1822 underline, width, wraplength."""
1823 Widget.__init__(self, master, 'button', cnf, kw)
1824 def tkButtonEnter(self, *dummy):
1825 self.tk.call('tkButtonEnter', self._w)
1826 def tkButtonLeave(self, *dummy):
1827 self.tk.call('tkButtonLeave', self._w)
1828 def tkButtonDown(self, *dummy):
1829 self.tk.call('tkButtonDown', self._w)
1830 def tkButtonUp(self, *dummy):
1831 self.tk.call('tkButtonUp', self._w)
1832 def tkButtonInvoke(self, *dummy):
1833 self.tk.call('tkButtonInvoke', self._w)
1834 def flash(self):
1835 self.tk.call(self._w, 'flash')
1836 def invoke(self):
1837 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001838
1839# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001840# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001841def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001842 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001843def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001844 s = 'insert'
1845 for a in args:
1846 if a: s = s + (' ' + a)
1847 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001848def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001849 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001850def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001851 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001852def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001853 if y is None:
1854 return '@' + `x`
1855 else:
1856 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001857
1858class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001859 """Canvas widget to display graphical elements like lines or text."""
1860 def __init__(self, master=None, cnf={}, **kw):
1861 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001862
Fredrik Lundh06d28152000-08-09 18:03:12 +00001863 Valid resource names: background, bd, bg, borderwidth, closeenough,
1864 confine, cursor, height, highlightbackground, highlightcolor,
1865 highlightthickness, insertbackground, insertborderwidth,
1866 insertofftime, insertontime, insertwidth, offset, relief,
1867 scrollregion, selectbackground, selectborderwidth, selectforeground,
1868 state, takefocus, width, xscrollcommand, xscrollincrement,
1869 yscrollcommand, yscrollincrement."""
1870 Widget.__init__(self, master, 'canvas', cnf, kw)
1871 def addtag(self, *args):
1872 """Internal function."""
1873 self.tk.call((self._w, 'addtag') + args)
1874 def addtag_above(self, newtag, tagOrId):
1875 """Add tag NEWTAG to all items above TAGORID."""
1876 self.addtag(newtag, 'above', tagOrId)
1877 def addtag_all(self, newtag):
1878 """Add tag NEWTAG to all items."""
1879 self.addtag(newtag, 'all')
1880 def addtag_below(self, newtag, tagOrId):
1881 """Add tag NEWTAG to all items below TAGORID."""
1882 self.addtag(newtag, 'below', tagOrId)
1883 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1884 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1885 If several match take the top-most.
1886 All items closer than HALO are considered overlapping (all are
1887 closests). If START is specified the next below this tag is taken."""
1888 self.addtag(newtag, 'closest', x, y, halo, start)
1889 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1890 """Add tag NEWTAG to all items in the rectangle defined
1891 by X1,Y1,X2,Y2."""
1892 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1893 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1894 """Add tag NEWTAG to all items which overlap the rectangle
1895 defined by X1,Y1,X2,Y2."""
1896 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1897 def addtag_withtag(self, newtag, tagOrId):
1898 """Add tag NEWTAG to all items with TAGORID."""
1899 self.addtag(newtag, 'withtag', tagOrId)
1900 def bbox(self, *args):
1901 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1902 which encloses all items with tags specified as arguments."""
1903 return self._getints(
1904 self.tk.call((self._w, 'bbox') + args)) or None
1905 def tag_unbind(self, tagOrId, sequence, funcid=None):
1906 """Unbind for all items with TAGORID for event SEQUENCE the
1907 function identified with FUNCID."""
1908 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
1909 if funcid:
1910 self.deletecommand(funcid)
1911 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
1912 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001913
Fredrik Lundh06d28152000-08-09 18:03:12 +00001914 An additional boolean parameter ADD specifies whether FUNC will be
1915 called additionally to the other bound function or whether it will
1916 replace the previous function. See bind for the return value."""
1917 return self._bind((self._w, 'bind', tagOrId),
1918 sequence, func, add)
1919 def canvasx(self, screenx, gridspacing=None):
1920 """Return the canvas x coordinate of pixel position SCREENX rounded
1921 to nearest multiple of GRIDSPACING units."""
1922 return getdouble(self.tk.call(
1923 self._w, 'canvasx', screenx, gridspacing))
1924 def canvasy(self, screeny, gridspacing=None):
1925 """Return the canvas y coordinate of pixel position SCREENY rounded
1926 to nearest multiple of GRIDSPACING units."""
1927 return getdouble(self.tk.call(
1928 self._w, 'canvasy', screeny, gridspacing))
1929 def coords(self, *args):
1930 """Return a list of coordinates for the item given in ARGS."""
1931 # XXX Should use _flatten on args
1932 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00001933 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001934 self.tk.call((self._w, 'coords') + args)))
1935 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
1936 """Internal function."""
1937 args = _flatten(args)
1938 cnf = args[-1]
1939 if type(cnf) in (DictionaryType, TupleType):
1940 args = args[:-1]
1941 else:
1942 cnf = {}
1943 return getint(apply(
1944 self.tk.call,
1945 (self._w, 'create', itemType)
1946 + args + self._options(cnf, kw)))
1947 def create_arc(self, *args, **kw):
1948 """Create arc shaped region with coordinates x1,y1,x2,y2."""
1949 return self._create('arc', args, kw)
1950 def create_bitmap(self, *args, **kw):
1951 """Create bitmap with coordinates x1,y1."""
1952 return self._create('bitmap', args, kw)
1953 def create_image(self, *args, **kw):
1954 """Create image item with coordinates x1,y1."""
1955 return self._create('image', args, kw)
1956 def create_line(self, *args, **kw):
1957 """Create line with coordinates x1,y1,...,xn,yn."""
1958 return self._create('line', args, kw)
1959 def create_oval(self, *args, **kw):
1960 """Create oval with coordinates x1,y1,x2,y2."""
1961 return self._create('oval', args, kw)
1962 def create_polygon(self, *args, **kw):
1963 """Create polygon with coordinates x1,y1,...,xn,yn."""
1964 return self._create('polygon', args, kw)
1965 def create_rectangle(self, *args, **kw):
1966 """Create rectangle with coordinates x1,y1,x2,y2."""
1967 return self._create('rectangle', args, kw)
1968 def create_text(self, *args, **kw):
1969 """Create text with coordinates x1,y1."""
1970 return self._create('text', args, kw)
1971 def create_window(self, *args, **kw):
1972 """Create window with coordinates x1,y1,x2,y2."""
1973 return self._create('window', args, kw)
1974 def dchars(self, *args):
1975 """Delete characters of text items identified by tag or id in ARGS (possibly
1976 several times) from FIRST to LAST character (including)."""
1977 self.tk.call((self._w, 'dchars') + args)
1978 def delete(self, *args):
1979 """Delete items identified by all tag or ids contained in ARGS."""
1980 self.tk.call((self._w, 'delete') + args)
1981 def dtag(self, *args):
1982 """Delete tag or id given as last arguments in ARGS from items
1983 identified by first argument in ARGS."""
1984 self.tk.call((self._w, 'dtag') + args)
1985 def find(self, *args):
1986 """Internal function."""
1987 return self._getints(
1988 self.tk.call((self._w, 'find') + args)) or ()
1989 def find_above(self, tagOrId):
1990 """Return items above TAGORID."""
1991 return self.find('above', tagOrId)
1992 def find_all(self):
1993 """Return all items."""
1994 return self.find('all')
1995 def find_below(self, tagOrId):
1996 """Return all items below TAGORID."""
1997 return self.find('below', tagOrId)
1998 def find_closest(self, x, y, halo=None, start=None):
1999 """Return item which is closest to pixel at X, Y.
2000 If several match take the top-most.
2001 All items closer than HALO are considered overlapping (all are
2002 closests). If START is specified the next below this tag is taken."""
2003 return self.find('closest', x, y, halo, start)
2004 def find_enclosed(self, x1, y1, x2, y2):
2005 """Return all items in rectangle defined
2006 by X1,Y1,X2,Y2."""
2007 return self.find('enclosed', x1, y1, x2, y2)
2008 def find_overlapping(self, x1, y1, x2, y2):
2009 """Return all items which overlap the rectangle
2010 defined by X1,Y1,X2,Y2."""
2011 return self.find('overlapping', x1, y1, x2, y2)
2012 def find_withtag(self, tagOrId):
2013 """Return all items with TAGORID."""
2014 return self.find('withtag', tagOrId)
2015 def focus(self, *args):
2016 """Set focus to the first item specified in ARGS."""
2017 return self.tk.call((self._w, 'focus') + args)
2018 def gettags(self, *args):
2019 """Return tags associated with the first item specified in ARGS."""
2020 return self.tk.splitlist(
2021 self.tk.call((self._w, 'gettags') + args))
2022 def icursor(self, *args):
2023 """Set cursor at position POS in the item identified by TAGORID.
2024 In ARGS TAGORID must be first."""
2025 self.tk.call((self._w, 'icursor') + args)
2026 def index(self, *args):
2027 """Return position of cursor as integer in item specified in ARGS."""
2028 return getint(self.tk.call((self._w, 'index') + args))
2029 def insert(self, *args):
2030 """Insert TEXT in item TAGORID at position POS. ARGS must
2031 be TAGORID POS TEXT."""
2032 self.tk.call((self._w, 'insert') + args)
2033 def itemcget(self, tagOrId, option):
2034 """Return the resource value for an OPTION for item TAGORID."""
2035 return self.tk.call(
2036 (self._w, 'itemcget') + (tagOrId, '-'+option))
2037 def itemconfigure(self, tagOrId, cnf=None, **kw):
2038 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002039
Fredrik Lundh06d28152000-08-09 18:03:12 +00002040 The values for resources are specified as keyword
2041 arguments. To get an overview about
2042 the allowed keyword arguments call the method without arguments.
2043 """
2044 if cnf is None and not kw:
2045 cnf = {}
2046 for x in self.tk.split(
2047 self.tk.call(self._w,
2048 'itemconfigure', tagOrId)):
2049 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2050 return cnf
2051 if type(cnf) == StringType and not kw:
2052 x = self.tk.split(self.tk.call(
2053 self._w, 'itemconfigure', tagOrId, '-'+cnf))
2054 return (x[0][1:],) + x[1:]
2055 self.tk.call((self._w, 'itemconfigure', tagOrId) +
2056 self._options(cnf, kw))
2057 itemconfig = itemconfigure
2058 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2059 # so the preferred name for them is tag_lower, tag_raise
2060 # (similar to tag_bind, and similar to the Text widget);
2061 # unfortunately can't delete the old ones yet (maybe in 1.6)
2062 def tag_lower(self, *args):
2063 """Lower an item TAGORID given in ARGS
2064 (optional below another item)."""
2065 self.tk.call((self._w, 'lower') + args)
2066 lower = tag_lower
2067 def move(self, *args):
2068 """Move an item TAGORID given in ARGS."""
2069 self.tk.call((self._w, 'move') + args)
2070 def postscript(self, cnf={}, **kw):
2071 """Print the contents of the canvas to a postscript
2072 file. Valid options: colormap, colormode, file, fontmap,
2073 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2074 rotate, witdh, x, y."""
2075 return self.tk.call((self._w, 'postscript') +
2076 self._options(cnf, kw))
2077 def tag_raise(self, *args):
2078 """Raise an item TAGORID given in ARGS
2079 (optional above another item)."""
2080 self.tk.call((self._w, 'raise') + args)
2081 lift = tkraise = tag_raise
2082 def scale(self, *args):
2083 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2084 self.tk.call((self._w, 'scale') + args)
2085 def scan_mark(self, x, y):
2086 """Remember the current X, Y coordinates."""
2087 self.tk.call(self._w, 'scan', 'mark', x, y)
2088 def scan_dragto(self, x, y):
2089 """Adjust the view of the canvas to 10 times the
2090 difference between X and Y and the coordinates given in
2091 scan_mark."""
2092 self.tk.call(self._w, 'scan', 'dragto', x, y)
2093 def select_adjust(self, tagOrId, index):
2094 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2095 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2096 def select_clear(self):
2097 """Clear the selection if it is in this widget."""
2098 self.tk.call(self._w, 'select', 'clear')
2099 def select_from(self, tagOrId, index):
2100 """Set the fixed end of a selection in item TAGORID to INDEX."""
2101 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2102 def select_item(self):
2103 """Return the item which has the selection."""
2104 self.tk.call(self._w, 'select', 'item')
2105 def select_to(self, tagOrId, index):
2106 """Set the variable end of a selection in item TAGORID to INDEX."""
2107 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2108 def type(self, tagOrId):
2109 """Return the type of the item TAGORID."""
2110 return self.tk.call(self._w, 'type', tagOrId) or None
2111 def xview(self, *args):
2112 """Query and change horizontal position of the view."""
2113 if not args:
2114 return self._getdoubles(self.tk.call(self._w, 'xview'))
2115 self.tk.call((self._w, 'xview') + args)
2116 def xview_moveto(self, fraction):
2117 """Adjusts the view in the window so that FRACTION of the
2118 total width of the canvas is off-screen to the left."""
2119 self.tk.call(self._w, 'xview', 'moveto', fraction)
2120 def xview_scroll(self, number, what):
2121 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2122 self.tk.call(self._w, 'xview', 'scroll', number, what)
2123 def yview(self, *args):
2124 """Query and change vertical position of the view."""
2125 if not args:
2126 return self._getdoubles(self.tk.call(self._w, 'yview'))
2127 self.tk.call((self._w, 'yview') + args)
2128 def yview_moveto(self, fraction):
2129 """Adjusts the view in the window so that FRACTION of the
2130 total height of the canvas is off-screen to the top."""
2131 self.tk.call(self._w, 'yview', 'moveto', fraction)
2132 def yview_scroll(self, number, what):
2133 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2134 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002135
2136class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002137 """Checkbutton widget which is either in on- or off-state."""
2138 def __init__(self, master=None, cnf={}, **kw):
2139 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002140
Fredrik Lundh06d28152000-08-09 18:03:12 +00002141 Valid resource names: activebackground, activeforeground, anchor,
2142 background, bd, bg, bitmap, borderwidth, command, cursor,
2143 disabledforeground, fg, font, foreground, height,
2144 highlightbackground, highlightcolor, highlightthickness, image,
2145 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2146 selectcolor, selectimage, state, takefocus, text, textvariable,
2147 underline, variable, width, wraplength."""
2148 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2149 def deselect(self):
2150 """Put the button in off-state."""
2151 self.tk.call(self._w, 'deselect')
2152 def flash(self):
2153 """Flash the button."""
2154 self.tk.call(self._w, 'flash')
2155 def invoke(self):
2156 """Toggle the button and invoke a command if given as resource."""
2157 return self.tk.call(self._w, 'invoke')
2158 def select(self):
2159 """Put the button in on-state."""
2160 self.tk.call(self._w, 'select')
2161 def toggle(self):
2162 """Toggle the button."""
2163 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002164
2165class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002166 """Entry widget which allows to display simple text."""
2167 def __init__(self, master=None, cnf={}, **kw):
2168 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002169
Fredrik Lundh06d28152000-08-09 18:03:12 +00002170 Valid resource names: background, bd, bg, borderwidth, cursor,
2171 exportselection, fg, font, foreground, highlightbackground,
2172 highlightcolor, highlightthickness, insertbackground,
2173 insertborderwidth, insertofftime, insertontime, insertwidth,
2174 invalidcommand, invcmd, justify, relief, selectbackground,
2175 selectborderwidth, selectforeground, show, state, takefocus,
2176 textvariable, validate, validatecommand, vcmd, width,
2177 xscrollcommand."""
2178 Widget.__init__(self, master, 'entry', cnf, kw)
2179 def delete(self, first, last=None):
2180 """Delete text from FIRST to LAST (not included)."""
2181 self.tk.call(self._w, 'delete', first, last)
2182 def get(self):
2183 """Return the text."""
2184 return self.tk.call(self._w, 'get')
2185 def icursor(self, index):
2186 """Insert cursor at INDEX."""
2187 self.tk.call(self._w, 'icursor', index)
2188 def index(self, index):
2189 """Return position of cursor."""
2190 return getint(self.tk.call(
2191 self._w, 'index', index))
2192 def insert(self, index, string):
2193 """Insert STRING at INDEX."""
2194 self.tk.call(self._w, 'insert', index, string)
2195 def scan_mark(self, x):
2196 """Remember the current X, Y coordinates."""
2197 self.tk.call(self._w, 'scan', 'mark', x)
2198 def scan_dragto(self, x):
2199 """Adjust the view of the canvas to 10 times the
2200 difference between X and Y and the coordinates given in
2201 scan_mark."""
2202 self.tk.call(self._w, 'scan', 'dragto', x)
2203 def selection_adjust(self, index):
2204 """Adjust the end of the selection near the cursor to INDEX."""
2205 self.tk.call(self._w, 'selection', 'adjust', index)
2206 select_adjust = selection_adjust
2207 def selection_clear(self):
2208 """Clear the selection if it is in this widget."""
2209 self.tk.call(self._w, 'selection', 'clear')
2210 select_clear = selection_clear
2211 def selection_from(self, index):
2212 """Set the fixed end of a selection to INDEX."""
2213 self.tk.call(self._w, 'selection', 'from', index)
2214 select_from = selection_from
2215 def selection_present(self):
2216 """Return whether the widget has the selection."""
2217 return self.tk.getboolean(
2218 self.tk.call(self._w, 'selection', 'present'))
2219 select_present = selection_present
2220 def selection_range(self, start, end):
2221 """Set the selection from START to END (not included)."""
2222 self.tk.call(self._w, 'selection', 'range', start, end)
2223 select_range = selection_range
2224 def selection_to(self, index):
2225 """Set the variable end of a selection to INDEX."""
2226 self.tk.call(self._w, 'selection', 'to', index)
2227 select_to = selection_to
2228 def xview(self, index):
2229 """Query and change horizontal position of the view."""
2230 self.tk.call(self._w, 'xview', index)
2231 def xview_moveto(self, fraction):
2232 """Adjust the view in the window so that FRACTION of the
2233 total width of the entry is off-screen to the left."""
2234 self.tk.call(self._w, 'xview', 'moveto', fraction)
2235 def xview_scroll(self, number, what):
2236 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2237 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002238
2239class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002240 """Frame widget which may contain other widgets and can have a 3D border."""
2241 def __init__(self, master=None, cnf={}, **kw):
2242 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002243
Fredrik Lundh06d28152000-08-09 18:03:12 +00002244 Valid resource names: background, bd, bg, borderwidth, class,
2245 colormap, container, cursor, height, highlightbackground,
2246 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2247 cnf = _cnfmerge((cnf, kw))
2248 extra = ()
2249 if cnf.has_key('class_'):
2250 extra = ('-class', cnf['class_'])
2251 del cnf['class_']
2252 elif cnf.has_key('class'):
2253 extra = ('-class', cnf['class'])
2254 del cnf['class']
2255 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002256
2257class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002258 """Label widget which can display text and bitmaps."""
2259 def __init__(self, master=None, cnf={}, **kw):
2260 """Construct a label widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002261
Fredrik Lundh06d28152000-08-09 18:03:12 +00002262 Valid resource names: anchor, background, bd, bg, bitmap,
2263 borderwidth, cursor, fg, font, foreground, height,
2264 highlightbackground, highlightcolor, highlightthickness, image,
2265 justify, padx, pady, relief, takefocus, text, textvariable,
2266 underline, width, wraplength."""
2267 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002268
Guido van Rossum18468821994-06-20 07:49:28 +00002269class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002270 """Listbox widget which can display a list of strings."""
2271 def __init__(self, master=None, cnf={}, **kw):
2272 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002273
Fredrik Lundh06d28152000-08-09 18:03:12 +00002274 Valid resource names: background, bd, bg, borderwidth, cursor,
2275 exportselection, fg, font, foreground, height, highlightbackground,
2276 highlightcolor, highlightthickness, relief, selectbackground,
2277 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2278 width, xscrollcommand, yscrollcommand, listvariable."""
2279 Widget.__init__(self, master, 'listbox', cnf, kw)
2280 def activate(self, index):
2281 """Activate item identified by INDEX."""
2282 self.tk.call(self._w, 'activate', index)
2283 def bbox(self, *args):
2284 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2285 which encloses the item identified by index in ARGS."""
2286 return self._getints(
2287 self.tk.call((self._w, 'bbox') + args)) or None
2288 def curselection(self):
2289 """Return list of indices of currently selected item."""
2290 # XXX Ought to apply self._getints()...
2291 return self.tk.splitlist(self.tk.call(
2292 self._w, 'curselection'))
2293 def delete(self, first, last=None):
2294 """Delete items from FIRST to LAST (not included)."""
2295 self.tk.call(self._w, 'delete', first, last)
2296 def get(self, first, last=None):
2297 """Get list of items from FIRST to LAST (not included)."""
2298 if last:
2299 return self.tk.splitlist(self.tk.call(
2300 self._w, 'get', first, last))
2301 else:
2302 return self.tk.call(self._w, 'get', first)
2303 def index(self, index):
2304 """Return index of item identified with INDEX."""
2305 i = self.tk.call(self._w, 'index', index)
2306 if i == 'none': return None
2307 return getint(i)
2308 def insert(self, index, *elements):
2309 """Insert ELEMENTS at INDEX."""
2310 self.tk.call((self._w, 'insert', index) + elements)
2311 def nearest(self, y):
2312 """Get index of item which is nearest to y coordinate Y."""
2313 return getint(self.tk.call(
2314 self._w, 'nearest', y))
2315 def scan_mark(self, x, y):
2316 """Remember the current X, Y coordinates."""
2317 self.tk.call(self._w, 'scan', 'mark', x, y)
2318 def scan_dragto(self, x, y):
2319 """Adjust the view of the listbox to 10 times the
2320 difference between X and Y and the coordinates given in
2321 scan_mark."""
2322 self.tk.call(self._w, 'scan', 'dragto', x, y)
2323 def see(self, index):
2324 """Scroll such that INDEX is visible."""
2325 self.tk.call(self._w, 'see', index)
2326 def selection_anchor(self, index):
2327 """Set the fixed end oft the selection to INDEX."""
2328 self.tk.call(self._w, 'selection', 'anchor', index)
2329 select_anchor = selection_anchor
2330 def selection_clear(self, first, last=None):
2331 """Clear the selection from FIRST to LAST (not included)."""
2332 self.tk.call(self._w,
2333 'selection', 'clear', first, last)
2334 select_clear = selection_clear
2335 def selection_includes(self, index):
2336 """Return 1 if INDEX is part of the selection."""
2337 return self.tk.getboolean(self.tk.call(
2338 self._w, 'selection', 'includes', index))
2339 select_includes = selection_includes
2340 def selection_set(self, first, last=None):
2341 """Set the selection from FIRST to LAST (not included) without
2342 changing the currently selected elements."""
2343 self.tk.call(self._w, 'selection', 'set', first, last)
2344 select_set = selection_set
2345 def size(self):
2346 """Return the number of elements in the listbox."""
2347 return getint(self.tk.call(self._w, 'size'))
2348 def xview(self, *what):
2349 """Query and change horizontal position of the view."""
2350 if not what:
2351 return self._getdoubles(self.tk.call(self._w, 'xview'))
2352 self.tk.call((self._w, 'xview') + what)
2353 def xview_moveto(self, fraction):
2354 """Adjust the view in the window so that FRACTION of the
2355 total width of the entry is off-screen to the left."""
2356 self.tk.call(self._w, 'xview', 'moveto', fraction)
2357 def xview_scroll(self, number, what):
2358 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2359 self.tk.call(self._w, 'xview', 'scroll', number, what)
2360 def yview(self, *what):
2361 """Query and change vertical position of the view."""
2362 if not what:
2363 return self._getdoubles(self.tk.call(self._w, 'yview'))
2364 self.tk.call((self._w, 'yview') + what)
2365 def yview_moveto(self, fraction):
2366 """Adjust the view in the window so that FRACTION of the
2367 total width of the entry is off-screen to the top."""
2368 self.tk.call(self._w, 'yview', 'moveto', fraction)
2369 def yview_scroll(self, number, what):
2370 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2371 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002372
2373class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002374 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2375 def __init__(self, master=None, cnf={}, **kw):
2376 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002377
Fredrik Lundh06d28152000-08-09 18:03:12 +00002378 Valid resource names: activebackground, activeborderwidth,
2379 activeforeground, background, bd, bg, borderwidth, cursor,
2380 disabledforeground, fg, font, foreground, postcommand, relief,
2381 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2382 Widget.__init__(self, master, 'menu', cnf, kw)
2383 def tk_bindForTraversal(self):
2384 pass # obsolete since Tk 4.0
2385 def tk_mbPost(self):
2386 self.tk.call('tk_mbPost', self._w)
2387 def tk_mbUnpost(self):
2388 self.tk.call('tk_mbUnpost')
2389 def tk_traverseToMenu(self, char):
2390 self.tk.call('tk_traverseToMenu', self._w, char)
2391 def tk_traverseWithinMenu(self, char):
2392 self.tk.call('tk_traverseWithinMenu', self._w, char)
2393 def tk_getMenuButtons(self):
2394 return self.tk.call('tk_getMenuButtons', self._w)
2395 def tk_nextMenu(self, count):
2396 self.tk.call('tk_nextMenu', count)
2397 def tk_nextMenuEntry(self, count):
2398 self.tk.call('tk_nextMenuEntry', count)
2399 def tk_invokeMenu(self):
2400 self.tk.call('tk_invokeMenu', self._w)
2401 def tk_firstMenu(self):
2402 self.tk.call('tk_firstMenu', self._w)
2403 def tk_mbButtonDown(self):
2404 self.tk.call('tk_mbButtonDown', self._w)
2405 def tk_popup(self, x, y, entry=""):
2406 """Post the menu at position X,Y with entry ENTRY."""
2407 self.tk.call('tk_popup', self._w, x, y, entry)
2408 def activate(self, index):
2409 """Activate entry at INDEX."""
2410 self.tk.call(self._w, 'activate', index)
2411 def add(self, itemType, cnf={}, **kw):
2412 """Internal function."""
2413 self.tk.call((self._w, 'add', itemType) +
2414 self._options(cnf, kw))
2415 def add_cascade(self, cnf={}, **kw):
2416 """Add hierarchical menu item."""
2417 self.add('cascade', cnf or kw)
2418 def add_checkbutton(self, cnf={}, **kw):
2419 """Add checkbutton menu item."""
2420 self.add('checkbutton', cnf or kw)
2421 def add_command(self, cnf={}, **kw):
2422 """Add command menu item."""
2423 self.add('command', cnf or kw)
2424 def add_radiobutton(self, cnf={}, **kw):
2425 """Addd radio menu item."""
2426 self.add('radiobutton', cnf or kw)
2427 def add_separator(self, cnf={}, **kw):
2428 """Add separator."""
2429 self.add('separator', cnf or kw)
2430 def insert(self, index, itemType, cnf={}, **kw):
2431 """Internal function."""
2432 self.tk.call((self._w, 'insert', index, itemType) +
2433 self._options(cnf, kw))
2434 def insert_cascade(self, index, cnf={}, **kw):
2435 """Add hierarchical menu item at INDEX."""
2436 self.insert(index, 'cascade', cnf or kw)
2437 def insert_checkbutton(self, index, cnf={}, **kw):
2438 """Add checkbutton menu item at INDEX."""
2439 self.insert(index, 'checkbutton', cnf or kw)
2440 def insert_command(self, index, cnf={}, **kw):
2441 """Add command menu item at INDEX."""
2442 self.insert(index, 'command', cnf or kw)
2443 def insert_radiobutton(self, index, cnf={}, **kw):
2444 """Addd radio menu item at INDEX."""
2445 self.insert(index, 'radiobutton', cnf or kw)
2446 def insert_separator(self, index, cnf={}, **kw):
2447 """Add separator at INDEX."""
2448 self.insert(index, 'separator', cnf or kw)
2449 def delete(self, index1, index2=None):
2450 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2451 self.tk.call(self._w, 'delete', index1, index2)
2452 def entrycget(self, index, option):
2453 """Return the resource value of an menu item for OPTION at INDEX."""
2454 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2455 def entryconfigure(self, index, cnf=None, **kw):
2456 """Configure a menu item at INDEX."""
2457 if cnf is None and not kw:
2458 cnf = {}
2459 for x in self.tk.split(self.tk.call(
2460 (self._w, 'entryconfigure', index))):
2461 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2462 return cnf
2463 if type(cnf) == StringType and not kw:
2464 x = self.tk.split(self.tk.call(
2465 (self._w, 'entryconfigure', index, '-'+cnf)))
2466 return (x[0][1:],) + x[1:]
2467 self.tk.call((self._w, 'entryconfigure', index)
2468 + self._options(cnf, kw))
2469 entryconfig = entryconfigure
2470 def index(self, index):
2471 """Return the index of a menu item identified by INDEX."""
2472 i = self.tk.call(self._w, 'index', index)
2473 if i == 'none': return None
2474 return getint(i)
2475 def invoke(self, index):
2476 """Invoke a menu item identified by INDEX and execute
2477 the associated command."""
2478 return self.tk.call(self._w, 'invoke', index)
2479 def post(self, x, y):
2480 """Display a menu at position X,Y."""
2481 self.tk.call(self._w, 'post', x, y)
2482 def type(self, index):
2483 """Return the type of the menu item at INDEX."""
2484 return self.tk.call(self._w, 'type', index)
2485 def unpost(self):
2486 """Unmap a menu."""
2487 self.tk.call(self._w, 'unpost')
2488 def yposition(self, index):
2489 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2490 return getint(self.tk.call(
2491 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002492
2493class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002494 """Menubutton widget, obsolete since Tk8.0."""
2495 def __init__(self, master=None, cnf={}, **kw):
2496 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002497
2498class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002499 """Message widget to display multiline text. Obsolete since Label does it too."""
2500 def __init__(self, master=None, cnf={}, **kw):
2501 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002502
2503class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002504 """Radiobutton widget which shows only one of several buttons in on-state."""
2505 def __init__(self, master=None, cnf={}, **kw):
2506 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002507
Fredrik Lundh06d28152000-08-09 18:03:12 +00002508 Valid resource names: activebackground, activeforeground, anchor,
2509 background, bd, bg, bitmap, borderwidth, command, cursor,
2510 disabledforeground, fg, font, foreground, height,
2511 highlightbackground, highlightcolor, highlightthickness, image,
2512 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2513 state, takefocus, text, textvariable, underline, value, variable,
2514 width, wraplength."""
2515 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2516 def deselect(self):
2517 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002518
Fredrik Lundh06d28152000-08-09 18:03:12 +00002519 self.tk.call(self._w, 'deselect')
2520 def flash(self):
2521 """Flash the button."""
2522 self.tk.call(self._w, 'flash')
2523 def invoke(self):
2524 """Toggle the button and invoke a command if given as resource."""
2525 return self.tk.call(self._w, 'invoke')
2526 def select(self):
2527 """Put the button in on-state."""
2528 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002529
2530class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002531 """Scale widget which can display a numerical scale."""
2532 def __init__(self, master=None, cnf={}, **kw):
2533 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002534
Fredrik Lundh06d28152000-08-09 18:03:12 +00002535 Valid resource names: activebackground, background, bigincrement, bd,
2536 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2537 highlightbackground, highlightcolor, highlightthickness, label,
2538 length, orient, relief, repeatdelay, repeatinterval, resolution,
2539 showvalue, sliderlength, sliderrelief, state, takefocus,
2540 tickinterval, to, troughcolor, variable, width."""
2541 Widget.__init__(self, master, 'scale', cnf, kw)
2542 def get(self):
2543 """Get the current value as integer or float."""
2544 value = self.tk.call(self._w, 'get')
2545 try:
2546 return getint(value)
2547 except ValueError:
2548 return getdouble(value)
2549 def set(self, value):
2550 """Set the value to VALUE."""
2551 self.tk.call(self._w, 'set', value)
2552 def coords(self, value=None):
2553 """Return a tuple (X,Y) of the point along the centerline of the
2554 trough that corresponds to VALUE or the current value if None is
2555 given."""
2556
2557 return self._getints(self.tk.call(self._w, 'coords', value))
2558 def identify(self, x, y):
2559 """Return where the point X,Y lies. Valid return values are "slider",
2560 "though1" and "though2"."""
2561 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002562
2563class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002564 """Scrollbar widget which displays a slider at a certain position."""
2565 def __init__(self, master=None, cnf={}, **kw):
2566 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002567
Fredrik Lundh06d28152000-08-09 18:03:12 +00002568 Valid resource names: activebackground, activerelief,
2569 background, bd, bg, borderwidth, command, cursor,
2570 elementborderwidth, highlightbackground,
2571 highlightcolor, highlightthickness, jump, orient,
2572 relief, repeatdelay, repeatinterval, takefocus,
2573 troughcolor, width."""
2574 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2575 def activate(self, index):
2576 """Display the element at INDEX with activebackground and activerelief.
2577 INDEX can be "arrow1","slider" or "arrow2"."""
2578 self.tk.call(self._w, 'activate', index)
2579 def delta(self, deltax, deltay):
2580 """Return the fractional change of the scrollbar setting if it
2581 would be moved by DELTAX or DELTAY pixels."""
2582 return getdouble(
2583 self.tk.call(self._w, 'delta', deltax, deltay))
2584 def fraction(self, x, y):
2585 """Return the fractional value which corresponds to a slider
2586 position of X,Y."""
2587 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2588 def identify(self, x, y):
2589 """Return the element under position X,Y as one of
2590 "arrow1","slider","arrow2" or ""."""
2591 return self.tk.call(self._w, 'identify', x, y)
2592 def get(self):
2593 """Return the current fractional values (upper and lower end)
2594 of the slider position."""
2595 return self._getdoubles(self.tk.call(self._w, 'get'))
2596 def set(self, *args):
2597 """Set the fractional values of the slider position (upper and
2598 lower ends as value between 0 and 1)."""
2599 self.tk.call((self._w, 'set') + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002600
2601class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002602 """Text widget which can display text in various forms."""
2603 # XXX Add dump()
2604 def __init__(self, master=None, cnf={}, **kw):
2605 """Construct a text widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002606
Fredrik Lundh06d28152000-08-09 18:03:12 +00002607 Valid resource names: background, bd, bg, borderwidth, cursor,
2608 exportselection, fg, font, foreground, height,
2609 highlightbackground, highlightcolor, highlightthickness,
2610 insertbackground, insertborderwidth, insertofftime,
2611 insertontime, insertwidth, padx, pady, relief,
2612 selectbackground, selectborderwidth, selectforeground,
2613 setgrid, spacing1, spacing2, spacing3, state, tabs, takefocus,
2614 width, wrap, xscrollcommand, yscrollcommand."""
2615 Widget.__init__(self, master, 'text', cnf, kw)
2616 def bbox(self, *args):
2617 """Return a tuple of (x,y,width,height) which gives the bounding
2618 box of the visible part of the character at the index in ARGS."""
2619 return self._getints(
2620 self.tk.call((self._w, 'bbox') + args)) or None
2621 def tk_textSelectTo(self, index):
2622 self.tk.call('tk_textSelectTo', self._w, index)
2623 def tk_textBackspace(self):
2624 self.tk.call('tk_textBackspace', self._w)
2625 def tk_textIndexCloser(self, a, b, c):
2626 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2627 def tk_textResetAnchor(self, index):
2628 self.tk.call('tk_textResetAnchor', self._w, index)
2629 def compare(self, index1, op, index2):
2630 """Return whether between index INDEX1 and index INDEX2 the
2631 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2632 return self.tk.getboolean(self.tk.call(
2633 self._w, 'compare', index1, op, index2))
2634 def debug(self, boolean=None):
2635 """Turn on the internal consistency checks of the B-Tree inside the text
2636 widget according to BOOLEAN."""
2637 return self.tk.getboolean(self.tk.call(
2638 self._w, 'debug', boolean))
2639 def delete(self, index1, index2=None):
2640 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2641 self.tk.call(self._w, 'delete', index1, index2)
2642 def dlineinfo(self, index):
2643 """Return tuple (x,y,width,height,baseline) giving the bounding box
2644 and baseline position of the visible part of the line containing
2645 the character at INDEX."""
2646 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
2647 def get(self, index1, index2=None):
2648 """Return the text from INDEX1 to INDEX2 (not included)."""
2649 return self.tk.call(self._w, 'get', index1, index2)
2650 # (Image commands are new in 8.0)
2651 def image_cget(self, index, option):
2652 """Return the value of OPTION of an embedded image at INDEX."""
2653 if option[:1] != "-":
2654 option = "-" + option
2655 if option[-1:] == "_":
2656 option = option[:-1]
2657 return self.tk.call(self._w, "image", "cget", index, option)
2658 def image_configure(self, index, cnf={}, **kw):
2659 """Configure an embedded image at INDEX."""
2660 if not cnf and not kw:
2661 cnf = {}
2662 for x in self.tk.split(
2663 self.tk.call(
2664 self._w, "image", "configure", index)):
2665 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2666 return cnf
2667 apply(self.tk.call,
2668 (self._w, "image", "configure", index)
2669 + self._options(cnf, kw))
2670 def image_create(self, index, cnf={}, **kw):
2671 """Create an embedded image at INDEX."""
2672 return apply(self.tk.call,
2673 (self._w, "image", "create", index)
2674 + self._options(cnf, kw))
2675 def image_names(self):
2676 """Return all names of embedded images in this widget."""
2677 return self.tk.call(self._w, "image", "names")
2678 def index(self, index):
2679 """Return the index in the form line.char for INDEX."""
2680 return self.tk.call(self._w, 'index', index)
2681 def insert(self, index, chars, *args):
2682 """Insert CHARS before the characters at INDEX. An additional
2683 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2684 self.tk.call((self._w, 'insert', index, chars) + args)
2685 def mark_gravity(self, markName, direction=None):
2686 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2687 Return the current value if None is given for DIRECTION."""
2688 return self.tk.call(
2689 (self._w, 'mark', 'gravity', markName, direction))
2690 def mark_names(self):
2691 """Return all mark names."""
2692 return self.tk.splitlist(self.tk.call(
2693 self._w, 'mark', 'names'))
2694 def mark_set(self, markName, index):
2695 """Set mark MARKNAME before the character at INDEX."""
2696 self.tk.call(self._w, 'mark', 'set', markName, index)
2697 def mark_unset(self, *markNames):
2698 """Delete all marks in MARKNAMES."""
2699 self.tk.call((self._w, 'mark', 'unset') + markNames)
2700 def mark_next(self, index):
2701 """Return the name of the next mark after INDEX."""
2702 return self.tk.call(self._w, 'mark', 'next', index) or None
2703 def mark_previous(self, index):
2704 """Return the name of the previous mark before INDEX."""
2705 return self.tk.call(self._w, 'mark', 'previous', index) or None
2706 def scan_mark(self, x, y):
2707 """Remember the current X, Y coordinates."""
2708 self.tk.call(self._w, 'scan', 'mark', x, y)
2709 def scan_dragto(self, x, y):
2710 """Adjust the view of the text to 10 times the
2711 difference between X and Y and the coordinates given in
2712 scan_mark."""
2713 self.tk.call(self._w, 'scan', 'dragto', x, y)
2714 def search(self, pattern, index, stopindex=None,
2715 forwards=None, backwards=None, exact=None,
2716 regexp=None, nocase=None, count=None):
2717 """Search PATTERN beginning from INDEX until STOPINDEX.
2718 Return the index of the first character of a match or an empty string."""
2719 args = [self._w, 'search']
2720 if forwards: args.append('-forwards')
2721 if backwards: args.append('-backwards')
2722 if exact: args.append('-exact')
2723 if regexp: args.append('-regexp')
2724 if nocase: args.append('-nocase')
2725 if count: args.append('-count'); args.append(count)
2726 if pattern[0] == '-': args.append('--')
2727 args.append(pattern)
2728 args.append(index)
2729 if stopindex: args.append(stopindex)
2730 return self.tk.call(tuple(args))
2731 def see(self, index):
2732 """Scroll such that the character at INDEX is visible."""
2733 self.tk.call(self._w, 'see', index)
2734 def tag_add(self, tagName, index1, *args):
2735 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2736 Additional pairs of indices may follow in ARGS."""
2737 self.tk.call(
2738 (self._w, 'tag', 'add', tagName, index1) + args)
2739 def tag_unbind(self, tagName, sequence, funcid=None):
2740 """Unbind for all characters with TAGNAME for event SEQUENCE the
2741 function identified with FUNCID."""
2742 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2743 if funcid:
2744 self.deletecommand(funcid)
2745 def tag_bind(self, tagName, sequence, func, add=None):
2746 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002747
Fredrik Lundh06d28152000-08-09 18:03:12 +00002748 An additional boolean parameter ADD specifies whether FUNC will be
2749 called additionally to the other bound function or whether it will
2750 replace the previous function. See bind for the return value."""
2751 return self._bind((self._w, 'tag', 'bind', tagName),
2752 sequence, func, add)
2753 def tag_cget(self, tagName, option):
2754 """Return the value of OPTION for tag TAGNAME."""
2755 if option[:1] != '-':
2756 option = '-' + option
2757 if option[-1:] == '_':
2758 option = option[:-1]
2759 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
2760 def tag_configure(self, tagName, cnf={}, **kw):
2761 """Configure a tag TAGNAME."""
2762 if type(cnf) == StringType:
2763 x = self.tk.split(self.tk.call(
2764 self._w, 'tag', 'configure', tagName, '-'+cnf))
2765 return (x[0][1:],) + x[1:]
2766 self.tk.call(
2767 (self._w, 'tag', 'configure', tagName)
2768 + self._options(cnf, kw))
2769 tag_config = tag_configure
2770 def tag_delete(self, *tagNames):
2771 """Delete all tags in TAGNAMES."""
2772 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2773 def tag_lower(self, tagName, belowThis=None):
2774 """Change the priority of tag TAGNAME such that it is lower
2775 than the priority of BELOWTHIS."""
2776 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2777 def tag_names(self, index=None):
2778 """Return a list of all tag names."""
2779 return self.tk.splitlist(
2780 self.tk.call(self._w, 'tag', 'names', index))
2781 def tag_nextrange(self, tagName, index1, index2=None):
2782 """Return a list of start and end index for the first sequence of
2783 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2784 The text is searched forward from INDEX1."""
2785 return self.tk.splitlist(self.tk.call(
2786 self._w, 'tag', 'nextrange', tagName, index1, index2))
2787 def tag_prevrange(self, tagName, index1, index2=None):
2788 """Return a list of start and end index for the first sequence of
2789 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2790 The text is searched backwards from INDEX1."""
2791 return self.tk.splitlist(self.tk.call(
2792 self._w, 'tag', 'prevrange', tagName, index1, index2))
2793 def tag_raise(self, tagName, aboveThis=None):
2794 """Change the priority of tag TAGNAME such that it is higher
2795 than the priority of ABOVETHIS."""
2796 self.tk.call(
2797 self._w, 'tag', 'raise', tagName, aboveThis)
2798 def tag_ranges(self, tagName):
2799 """Return a list of ranges of text which have tag TAGNAME."""
2800 return self.tk.splitlist(self.tk.call(
2801 self._w, 'tag', 'ranges', tagName))
2802 def tag_remove(self, tagName, index1, index2=None):
2803 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2804 self.tk.call(
2805 self._w, 'tag', 'remove', tagName, index1, index2)
2806 def window_cget(self, index, option):
2807 """Return the value of OPTION of an embedded window at INDEX."""
2808 if option[:1] != '-':
2809 option = '-' + option
2810 if option[-1:] == '_':
2811 option = option[:-1]
2812 return self.tk.call(self._w, 'window', 'cget', index, option)
2813 def window_configure(self, index, cnf={}, **kw):
2814 """Configure an embedded window at INDEX."""
2815 if type(cnf) == StringType:
2816 x = self.tk.split(self.tk.call(
2817 self._w, 'window', 'configure',
2818 index, '-'+cnf))
2819 return (x[0][1:],) + x[1:]
2820 self.tk.call(
2821 (self._w, 'window', 'configure', index)
2822 + self._options(cnf, kw))
2823 window_config = window_configure
2824 def window_create(self, index, cnf={}, **kw):
2825 """Create a window at INDEX."""
2826 self.tk.call(
2827 (self._w, 'window', 'create', index)
2828 + self._options(cnf, kw))
2829 def window_names(self):
2830 """Return all names of embedded windows in this widget."""
2831 return self.tk.splitlist(
2832 self.tk.call(self._w, 'window', 'names'))
2833 def xview(self, *what):
2834 """Query and change horizontal position of the view."""
2835 if not what:
2836 return self._getdoubles(self.tk.call(self._w, 'xview'))
2837 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002838 def xview_moveto(self, fraction):
2839 """Adjusts the view in the window so that FRACTION of the
2840 total width of the canvas is off-screen to the left."""
2841 self.tk.call(self._w, 'xview', 'moveto', fraction)
2842 def xview_scroll(self, number, what):
2843 """Shift the x-view according to NUMBER which is measured
2844 in "units" or "pages" (WHAT)."""
2845 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002846 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002847 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002848 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002849 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002850 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002851 def yview_moveto(self, fraction):
2852 """Adjusts the view in the window so that FRACTION of the
2853 total height of the canvas is off-screen to the top."""
2854 self.tk.call(self._w, 'yview', 'moveto', fraction)
2855 def yview_scroll(self, number, what):
2856 """Shift the y-view according to NUMBER which is measured
2857 in "units" or "pages" (WHAT)."""
2858 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002859 def yview_pickplace(self, *what):
2860 """Obsolete function, use see."""
2861 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00002862
Guido van Rossum28574b51996-10-21 15:16:51 +00002863class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002864 """Internal class. It wraps the command in the widget OptionMenu."""
2865 def __init__(self, var, value, callback=None):
2866 self.__value = value
2867 self.__var = var
2868 self.__callback = callback
2869 def __call__(self, *args):
2870 self.__var.set(self.__value)
2871 if self.__callback:
2872 apply(self.__callback, (self.__value,)+args)
Guido van Rossum28574b51996-10-21 15:16:51 +00002873
2874class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002875 """OptionMenu which allows the user to select a value from a menu."""
2876 def __init__(self, master, variable, value, *values, **kwargs):
2877 """Construct an optionmenu widget with the parent MASTER, with
2878 the resource textvariable set to VARIABLE, the initially selected
2879 value VALUE, the other menu values VALUES and an additional
2880 keyword argument command."""
2881 kw = {"borderwidth": 2, "textvariable": variable,
2882 "indicatoron": 1, "relief": RAISED, "anchor": "c",
2883 "highlightthickness": 2}
2884 Widget.__init__(self, master, "menubutton", kw)
2885 self.widgetName = 'tk_optionMenu'
2886 menu = self.__menu = Menu(self, name="menu", tearoff=0)
2887 self.menuname = menu._w
2888 # 'command' is the only supported keyword
2889 callback = kwargs.get('command')
2890 if kwargs.has_key('command'):
2891 del kwargs['command']
2892 if kwargs:
2893 raise TclError, 'unknown option -'+kwargs.keys()[0]
2894 menu.add_command(label=value,
2895 command=_setit(variable, value, callback))
2896 for v in values:
2897 menu.add_command(label=v,
2898 command=_setit(variable, v, callback))
2899 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00002900
Fredrik Lundh06d28152000-08-09 18:03:12 +00002901 def __getitem__(self, name):
2902 if name == 'menu':
2903 return self.__menu
2904 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00002905
Fredrik Lundh06d28152000-08-09 18:03:12 +00002906 def destroy(self):
2907 """Destroy this widget and the associated menu."""
2908 Menubutton.destroy(self)
2909 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00002910
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002911class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002912 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00002913 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00002914 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
2915 self.name = None
2916 if not master:
2917 master = _default_root
2918 if not master:
2919 raise RuntimeError, 'Too early to create image'
2920 self.tk = master.tk
2921 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00002922 Image._last_id += 1
2923 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00002924 # The following is needed for systems where id(x)
2925 # can return a negative number, such as Linux/m68k:
2926 if name[0] == '-': name = '_' + name[1:]
2927 if kw and cnf: cnf = _cnfmerge((cnf, kw))
2928 elif kw: cnf = kw
2929 options = ()
2930 for k, v in cnf.items():
2931 if callable(v):
2932 v = self._register(v)
2933 options = options + ('-'+k, v)
2934 self.tk.call(('image', 'create', imgtype, name,) + options)
2935 self.name = name
2936 def __str__(self): return self.name
2937 def __del__(self):
2938 if self.name:
2939 try:
2940 self.tk.call('image', 'delete', self.name)
2941 except TclError:
2942 # May happen if the root was destroyed
2943 pass
2944 def __setitem__(self, key, value):
2945 self.tk.call(self.name, 'configure', '-'+key, value)
2946 def __getitem__(self, key):
2947 return self.tk.call(self.name, 'configure', '-'+key)
2948 def configure(self, **kw):
2949 """Configure the image."""
2950 res = ()
2951 for k, v in _cnfmerge(kw).items():
2952 if v is not None:
2953 if k[-1] == '_': k = k[:-1]
2954 if callable(v):
2955 v = self._register(v)
2956 res = res + ('-'+k, v)
2957 self.tk.call((self.name, 'config') + res)
2958 config = configure
2959 def height(self):
2960 """Return the height of the image."""
2961 return getint(
2962 self.tk.call('image', 'height', self.name))
2963 def type(self):
2964 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
2965 return self.tk.call('image', 'type', self.name)
2966 def width(self):
2967 """Return the width of the image."""
2968 return getint(
2969 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002970
2971class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002972 """Widget which can display colored images in GIF, PPM/PGM format."""
2973 def __init__(self, name=None, cnf={}, master=None, **kw):
2974 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002975
Fredrik Lundh06d28152000-08-09 18:03:12 +00002976 Valid resource names: data, format, file, gamma, height, palette,
2977 width."""
2978 apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
2979 def blank(self):
2980 """Display a transparent image."""
2981 self.tk.call(self.name, 'blank')
2982 def cget(self, option):
2983 """Return the value of OPTION."""
2984 return self.tk.call(self.name, 'cget', '-' + option)
2985 # XXX config
2986 def __getitem__(self, key):
2987 return self.tk.call(self.name, 'cget', '-' + key)
2988 # XXX copy -from, -to, ...?
2989 def copy(self):
2990 """Return a new PhotoImage with the same image as this widget."""
2991 destImage = PhotoImage()
2992 self.tk.call(destImage, 'copy', self.name)
2993 return destImage
2994 def zoom(self,x,y=''):
2995 """Return a new PhotoImage with the same image as this widget
2996 but zoom it with X and Y."""
2997 destImage = PhotoImage()
2998 if y=='': y=x
2999 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3000 return destImage
3001 def subsample(self,x,y=''):
3002 """Return a new PhotoImage based on the same image as this widget
3003 but use only every Xth or Yth pixel."""
3004 destImage = PhotoImage()
3005 if y=='': y=x
3006 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3007 return destImage
3008 def get(self, x, y):
3009 """Return the color (red, green, blue) of the pixel at X,Y."""
3010 return self.tk.call(self.name, 'get', x, y)
3011 def put(self, data, to=None):
3012 """Put row formated colors to image starting from
3013 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3014 args = (self.name, 'put', data)
3015 if to:
3016 if to[0] == '-to':
3017 to = to[1:]
3018 args = args + ('-to',) + tuple(to)
3019 self.tk.call(args)
3020 # XXX read
3021 def write(self, filename, format=None, from_coords=None):
3022 """Write image to file FILENAME in FORMAT starting from
3023 position FROM_COORDS."""
3024 args = (self.name, 'write', filename)
3025 if format:
3026 args = args + ('-format', format)
3027 if from_coords:
3028 args = args + ('-from',) + tuple(from_coords)
3029 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003030
3031class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003032 """Widget which can display a bitmap."""
3033 def __init__(self, name=None, cnf={}, master=None, **kw):
3034 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003035
Fredrik Lundh06d28152000-08-09 18:03:12 +00003036 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3037 apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003038
3039def image_names(): return _default_root.tk.call('image', 'names')
3040def image_types(): return _default_root.tk.call('image', 'types')
3041
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003042######################################################################
3043# Extensions:
3044
3045class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003046 def __init__(self, master=None, cnf={}, **kw):
3047 Widget.__init__(self, master, 'studbutton', cnf, kw)
3048 self.bind('<Any-Enter>', self.tkButtonEnter)
3049 self.bind('<Any-Leave>', self.tkButtonLeave)
3050 self.bind('<1>', self.tkButtonDown)
3051 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003052
3053class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003054 def __init__(self, master=None, cnf={}, **kw):
3055 Widget.__init__(self, master, 'tributton', cnf, kw)
3056 self.bind('<Any-Enter>', self.tkButtonEnter)
3057 self.bind('<Any-Leave>', self.tkButtonLeave)
3058 self.bind('<1>', self.tkButtonDown)
3059 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3060 self['fg'] = self['bg']
3061 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003062
Guido van Rossumc417ef81996-08-21 23:38:59 +00003063######################################################################
3064# Test:
3065
3066def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003067 root = Tk()
3068 text = "This is Tcl/Tk version %s" % TclVersion
3069 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003070 try:
3071 text = text + unicode("\nThis should be a cedilla: \347",
3072 "iso-8859-1")
3073 except NameError:
3074 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003075 label = Label(root, text=text)
3076 label.pack()
3077 test = Button(root, text="Click me!",
3078 command=lambda root=root: root.test.configure(
3079 text="[%s]" % root.test['text']))
3080 test.pack()
3081 root.test = test
3082 quit = Button(root, text="QUIT", command=root.destroy)
3083 quit.pack()
3084 # The following three commands are needed so the window pops
3085 # up on top on Windows...
3086 root.iconify()
3087 root.update()
3088 root.deiconify()
3089 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003090
3091if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003092 _test()
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003093