blob: c4e78a2a86cad700b1470c878c7e68f5d5f322d5 [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."""
Fred Drake132dce22000-12-12 23:11:42 +0000342 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000343 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."""
Fred Drake132dce22000-12-12 23:11:42 +0000350 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000351 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):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001533 self.tk.call('source', class_tcl)
1534 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001535 execfile(class_py, dir)
1536 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001537 self.tk.call('source', base_tcl)
1538 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001539 execfile(base_py, dir)
1540 def report_callback_exception(self, exc, val, tb):
1541 """Internal function. It reports exception on sys.stderr."""
1542 import traceback, sys
1543 sys.stderr.write("Exception in Tkinter callback\n")
1544 sys.last_type = exc
1545 sys.last_value = val
1546 sys.last_traceback = tb
1547 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001548
Guido van Rossum368e06b1997-11-07 20:38:49 +00001549# Ideally, the classes Pack, Place and Grid disappear, the
1550# pack/place/grid methods are defined on the Widget class, and
1551# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1552# ...), with pack(), place() and grid() being short for
1553# pack_configure(), place_configure() and grid_columnconfigure(), and
1554# forget() being short for pack_forget(). As a practical matter, I'm
1555# afraid that there is too much code out there that may be using the
1556# Pack, Place or Grid class, so I leave them intact -- but only as
1557# backwards compatibility features. Also note that those methods that
1558# take a master as argument (e.g. pack_propagate) have been moved to
1559# the Misc class (which now incorporates all methods common between
1560# toplevel and interior widgets). Again, for compatibility, these are
1561# copied into the Pack, Place or Grid class.
1562
Guido van Rossum18468821994-06-20 07:49:28 +00001563class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001564 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001565
Fredrik Lundh06d28152000-08-09 18:03:12 +00001566 Base class to use the methods pack_* in every widget."""
1567 def pack_configure(self, cnf={}, **kw):
1568 """Pack a widget in the parent widget. Use as options:
1569 after=widget - pack it after you have packed widget
1570 anchor=NSEW (or subset) - position widget according to
1571 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001572 before=widget - pack it before you will pack widget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001573 expand=1 or 0 - expand widget if parent size grows
1574 fill=NONE or X or Y or BOTH - fill widget if widget grows
1575 in=master - use master to contain this widget
1576 ipadx=amount - add internal padding in x direction
1577 ipady=amount - add internal padding in y direction
1578 padx=amount - add padding in x direction
1579 pady=amount - add padding in y direction
1580 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1581 """
1582 self.tk.call(
1583 ('pack', 'configure', self._w)
1584 + self._options(cnf, kw))
1585 pack = configure = config = pack_configure
1586 def pack_forget(self):
1587 """Unmap this widget and do not use it for the packing order."""
1588 self.tk.call('pack', 'forget', self._w)
1589 forget = pack_forget
1590 def pack_info(self):
1591 """Return information about the packing options
1592 for this widget."""
1593 words = self.tk.splitlist(
1594 self.tk.call('pack', 'info', self._w))
1595 dict = {}
1596 for i in range(0, len(words), 2):
1597 key = words[i][1:]
1598 value = words[i+1]
1599 if value[:1] == '.':
1600 value = self._nametowidget(value)
1601 dict[key] = value
1602 return dict
1603 info = pack_info
1604 propagate = pack_propagate = Misc.pack_propagate
1605 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001606
1607class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001608 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001609
Fredrik Lundh06d28152000-08-09 18:03:12 +00001610 Base class to use the methods place_* in every widget."""
1611 def place_configure(self, cnf={}, **kw):
1612 """Place a widget in the parent widget. Use as options:
1613 in=master - master relative to which the widget is placed.
1614 x=amount - locate anchor of this widget at position x of master
1615 y=amount - locate anchor of this widget at position y of master
1616 relx=amount - locate anchor of this widget between 0.0 and 1.0
1617 relative to width of master (1.0 is right edge)
1618 rely=amount - locate anchor of this widget between 0.0 and 1.0
1619 relative to height of master (1.0 is bottom edge)
1620 anchor=NSEW (or subset) - position anchor according to given direction
1621 width=amount - width of this widget in pixel
1622 height=amount - height of this widget in pixel
1623 relwidth=amount - width of this widget between 0.0 and 1.0
1624 relative to width of master (1.0 is the same width
1625 as the master)
1626 relheight=amount - height of this widget between 0.0 and 1.0
1627 relative to height of master (1.0 is the same
1628 height as the master)
1629 bordermode="inside" or "outside" - whether to take border width of master widget
1630 into account
1631 """
1632 for k in ['in_']:
1633 if kw.has_key(k):
1634 kw[k[:-1]] = kw[k]
1635 del kw[k]
1636 self.tk.call(
1637 ('place', 'configure', self._w)
1638 + self._options(cnf, kw))
1639 place = configure = config = place_configure
1640 def place_forget(self):
1641 """Unmap this widget."""
1642 self.tk.call('place', 'forget', self._w)
1643 forget = place_forget
1644 def place_info(self):
1645 """Return information about the placing options
1646 for this widget."""
1647 words = self.tk.splitlist(
1648 self.tk.call('place', 'info', self._w))
1649 dict = {}
1650 for i in range(0, len(words), 2):
1651 key = words[i][1:]
1652 value = words[i+1]
1653 if value[:1] == '.':
1654 value = self._nametowidget(value)
1655 dict[key] = value
1656 return dict
1657 info = place_info
1658 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001659
Guido van Rossum37dcab11996-05-16 16:00:19 +00001660class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001661 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001662
Fredrik Lundh06d28152000-08-09 18:03:12 +00001663 Base class to use the methods grid_* in every widget."""
1664 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1665 def grid_configure(self, cnf={}, **kw):
1666 """Position a widget in the parent widget in a grid. Use as options:
1667 column=number - use cell identified with given column (starting with 0)
1668 columnspan=number - this widget will span several columns
1669 in=master - use master to contain this widget
1670 ipadx=amount - add internal padding in x direction
1671 ipady=amount - add internal padding in y direction
1672 padx=amount - add padding in x direction
1673 pady=amount - add padding in y direction
1674 row=number - use cell identified with given row (starting with 0)
1675 rowspan=number - this widget will span several rows
1676 sticky=NSEW - if cell is larger on which sides will this
1677 widget stick to the cell boundary
1678 """
1679 self.tk.call(
1680 ('grid', 'configure', self._w)
1681 + self._options(cnf, kw))
1682 grid = configure = config = grid_configure
1683 bbox = grid_bbox = Misc.grid_bbox
1684 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1685 def grid_forget(self):
1686 """Unmap this widget."""
1687 self.tk.call('grid', 'forget', self._w)
1688 forget = grid_forget
1689 def grid_remove(self):
1690 """Unmap this widget but remember the grid options."""
1691 self.tk.call('grid', 'remove', self._w)
1692 def grid_info(self):
1693 """Return information about the options
1694 for positioning this widget in a grid."""
1695 words = self.tk.splitlist(
1696 self.tk.call('grid', 'info', self._w))
1697 dict = {}
1698 for i in range(0, len(words), 2):
1699 key = words[i][1:]
1700 value = words[i+1]
1701 if value[:1] == '.':
1702 value = self._nametowidget(value)
1703 dict[key] = value
1704 return dict
1705 info = grid_info
1706 def grid_location(self, x, y):
1707 """Return a tuple of column and row which identify the cell
1708 at which the pixel at position X and Y inside the master
1709 widget is located."""
1710 return self._getints(
1711 self.tk.call(
1712 'grid', 'location', self._w, x, y)) or None
1713 location = grid_location
1714 propagate = grid_propagate = Misc.grid_propagate
1715 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1716 size = grid_size = Misc.grid_size
1717 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001718
Guido van Rossum368e06b1997-11-07 20:38:49 +00001719class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001720 """Internal class."""
1721 def _setup(self, master, cnf):
1722 """Internal function. Sets up information about children."""
1723 if _support_default_root:
1724 global _default_root
1725 if not master:
1726 if not _default_root:
1727 _default_root = Tk()
1728 master = _default_root
1729 self.master = master
1730 self.tk = master.tk
1731 name = None
1732 if cnf.has_key('name'):
1733 name = cnf['name']
1734 del cnf['name']
1735 if not name:
1736 name = `id(self)`
1737 self._name = name
1738 if master._w=='.':
1739 self._w = '.' + name
1740 else:
1741 self._w = master._w + '.' + name
1742 self.children = {}
1743 if self.master.children.has_key(self._name):
1744 self.master.children[self._name].destroy()
1745 self.master.children[self._name] = self
1746 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1747 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1748 and appropriate options."""
1749 if kw:
1750 cnf = _cnfmerge((cnf, kw))
1751 self.widgetName = widgetName
1752 BaseWidget._setup(self, master, cnf)
1753 classes = []
1754 for k in cnf.keys():
1755 if type(k) is ClassType:
1756 classes.append((k, cnf[k]))
1757 del cnf[k]
1758 self.tk.call(
1759 (widgetName, self._w) + extra + self._options(cnf))
1760 for k, v in classes:
1761 k.configure(self, v)
1762 def destroy(self):
1763 """Destroy this and all descendants widgets."""
1764 for c in self.children.values(): c.destroy()
1765 if self.master.children.has_key(self._name):
1766 del self.master.children[self._name]
1767 self.tk.call('destroy', self._w)
1768 Misc.destroy(self)
1769 def _do(self, name, args=()):
1770 # XXX Obsolete -- better use self.tk.call directly!
1771 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001772
Guido van Rossum368e06b1997-11-07 20:38:49 +00001773class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001774 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001775
Fredrik Lundh06d28152000-08-09 18:03:12 +00001776 Base class for a widget which can be positioned with the geometry managers
1777 Pack, Place or Grid."""
1778 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001779
1780class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001781 """Toplevel widget, e.g. for dialogs."""
1782 def __init__(self, master=None, cnf={}, **kw):
1783 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001784
Fredrik Lundh06d28152000-08-09 18:03:12 +00001785 Valid resource names: background, bd, bg, borderwidth, class,
1786 colormap, container, cursor, height, highlightbackground,
1787 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1788 use, visual, width."""
1789 if kw:
1790 cnf = _cnfmerge((cnf, kw))
1791 extra = ()
1792 for wmkey in ['screen', 'class_', 'class', 'visual',
1793 'colormap']:
1794 if cnf.has_key(wmkey):
1795 val = cnf[wmkey]
1796 # TBD: a hack needed because some keys
1797 # are not valid as keyword arguments
1798 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1799 else: opt = '-'+wmkey
1800 extra = extra + (opt, val)
1801 del cnf[wmkey]
1802 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1803 root = self._root()
1804 self.iconname(root.iconname())
1805 self.title(root.title())
1806 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001807
1808class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001809 """Button widget."""
1810 def __init__(self, master=None, cnf={}, **kw):
1811 """Construct a button widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001812
Fredrik Lundh06d28152000-08-09 18:03:12 +00001813 Valid resource names: activebackground, activeforeground, anchor,
1814 background, bd, bg, bitmap, borderwidth, command, cursor, default,
1815 disabledforeground, fg, font, foreground, height,
1816 highlightbackground, highlightcolor, highlightthickness, image,
1817 justify, padx, pady, relief, state, takefocus, text, textvariable,
1818 underline, width, wraplength."""
1819 Widget.__init__(self, master, 'button', cnf, kw)
1820 def tkButtonEnter(self, *dummy):
1821 self.tk.call('tkButtonEnter', self._w)
1822 def tkButtonLeave(self, *dummy):
1823 self.tk.call('tkButtonLeave', self._w)
1824 def tkButtonDown(self, *dummy):
1825 self.tk.call('tkButtonDown', self._w)
1826 def tkButtonUp(self, *dummy):
1827 self.tk.call('tkButtonUp', self._w)
1828 def tkButtonInvoke(self, *dummy):
1829 self.tk.call('tkButtonInvoke', self._w)
1830 def flash(self):
1831 self.tk.call(self._w, 'flash')
1832 def invoke(self):
1833 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001834
1835# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001836# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001837def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001838 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001839def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001840 s = 'insert'
1841 for a in args:
1842 if a: s = s + (' ' + a)
1843 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001844def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001845 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001846def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001847 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001848def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001849 if y is None:
1850 return '@' + `x`
1851 else:
1852 return '@' + `x` + ',' + `y`
Guido van Rossum18468821994-06-20 07:49:28 +00001853
1854class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001855 """Canvas widget to display graphical elements like lines or text."""
1856 def __init__(self, master=None, cnf={}, **kw):
1857 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001858
Fredrik Lundh06d28152000-08-09 18:03:12 +00001859 Valid resource names: background, bd, bg, borderwidth, closeenough,
1860 confine, cursor, height, highlightbackground, highlightcolor,
1861 highlightthickness, insertbackground, insertborderwidth,
1862 insertofftime, insertontime, insertwidth, offset, relief,
1863 scrollregion, selectbackground, selectborderwidth, selectforeground,
1864 state, takefocus, width, xscrollcommand, xscrollincrement,
1865 yscrollcommand, yscrollincrement."""
1866 Widget.__init__(self, master, 'canvas', cnf, kw)
1867 def addtag(self, *args):
1868 """Internal function."""
1869 self.tk.call((self._w, 'addtag') + args)
1870 def addtag_above(self, newtag, tagOrId):
1871 """Add tag NEWTAG to all items above TAGORID."""
1872 self.addtag(newtag, 'above', tagOrId)
1873 def addtag_all(self, newtag):
1874 """Add tag NEWTAG to all items."""
1875 self.addtag(newtag, 'all')
1876 def addtag_below(self, newtag, tagOrId):
1877 """Add tag NEWTAG to all items below TAGORID."""
1878 self.addtag(newtag, 'below', tagOrId)
1879 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1880 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1881 If several match take the top-most.
1882 All items closer than HALO are considered overlapping (all are
1883 closests). If START is specified the next below this tag is taken."""
1884 self.addtag(newtag, 'closest', x, y, halo, start)
1885 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1886 """Add tag NEWTAG to all items in the rectangle defined
1887 by X1,Y1,X2,Y2."""
1888 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1889 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
1890 """Add tag NEWTAG to all items which overlap the rectangle
1891 defined by X1,Y1,X2,Y2."""
1892 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
1893 def addtag_withtag(self, newtag, tagOrId):
1894 """Add tag NEWTAG to all items with TAGORID."""
1895 self.addtag(newtag, 'withtag', tagOrId)
1896 def bbox(self, *args):
1897 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
1898 which encloses all items with tags specified as arguments."""
1899 return self._getints(
1900 self.tk.call((self._w, 'bbox') + args)) or None
1901 def tag_unbind(self, tagOrId, sequence, funcid=None):
1902 """Unbind for all items with TAGORID for event SEQUENCE the
1903 function identified with FUNCID."""
1904 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
1905 if funcid:
1906 self.deletecommand(funcid)
1907 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
1908 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001909
Fredrik Lundh06d28152000-08-09 18:03:12 +00001910 An additional boolean parameter ADD specifies whether FUNC will be
1911 called additionally to the other bound function or whether it will
1912 replace the previous function. See bind for the return value."""
1913 return self._bind((self._w, 'bind', tagOrId),
1914 sequence, func, add)
1915 def canvasx(self, screenx, gridspacing=None):
1916 """Return the canvas x coordinate of pixel position SCREENX rounded
1917 to nearest multiple of GRIDSPACING units."""
1918 return getdouble(self.tk.call(
1919 self._w, 'canvasx', screenx, gridspacing))
1920 def canvasy(self, screeny, gridspacing=None):
1921 """Return the canvas y coordinate of pixel position SCREENY rounded
1922 to nearest multiple of GRIDSPACING units."""
1923 return getdouble(self.tk.call(
1924 self._w, 'canvasy', screeny, gridspacing))
1925 def coords(self, *args):
1926 """Return a list of coordinates for the item given in ARGS."""
1927 # XXX Should use _flatten on args
1928 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00001929 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001930 self.tk.call((self._w, 'coords') + args)))
1931 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
1932 """Internal function."""
1933 args = _flatten(args)
1934 cnf = args[-1]
1935 if type(cnf) in (DictionaryType, TupleType):
1936 args = args[:-1]
1937 else:
1938 cnf = {}
1939 return getint(apply(
1940 self.tk.call,
1941 (self._w, 'create', itemType)
1942 + args + self._options(cnf, kw)))
1943 def create_arc(self, *args, **kw):
1944 """Create arc shaped region with coordinates x1,y1,x2,y2."""
1945 return self._create('arc', args, kw)
1946 def create_bitmap(self, *args, **kw):
1947 """Create bitmap with coordinates x1,y1."""
1948 return self._create('bitmap', args, kw)
1949 def create_image(self, *args, **kw):
1950 """Create image item with coordinates x1,y1."""
1951 return self._create('image', args, kw)
1952 def create_line(self, *args, **kw):
1953 """Create line with coordinates x1,y1,...,xn,yn."""
1954 return self._create('line', args, kw)
1955 def create_oval(self, *args, **kw):
1956 """Create oval with coordinates x1,y1,x2,y2."""
1957 return self._create('oval', args, kw)
1958 def create_polygon(self, *args, **kw):
1959 """Create polygon with coordinates x1,y1,...,xn,yn."""
1960 return self._create('polygon', args, kw)
1961 def create_rectangle(self, *args, **kw):
1962 """Create rectangle with coordinates x1,y1,x2,y2."""
1963 return self._create('rectangle', args, kw)
1964 def create_text(self, *args, **kw):
1965 """Create text with coordinates x1,y1."""
1966 return self._create('text', args, kw)
1967 def create_window(self, *args, **kw):
1968 """Create window with coordinates x1,y1,x2,y2."""
1969 return self._create('window', args, kw)
1970 def dchars(self, *args):
1971 """Delete characters of text items identified by tag or id in ARGS (possibly
1972 several times) from FIRST to LAST character (including)."""
1973 self.tk.call((self._w, 'dchars') + args)
1974 def delete(self, *args):
1975 """Delete items identified by all tag or ids contained in ARGS."""
1976 self.tk.call((self._w, 'delete') + args)
1977 def dtag(self, *args):
1978 """Delete tag or id given as last arguments in ARGS from items
1979 identified by first argument in ARGS."""
1980 self.tk.call((self._w, 'dtag') + args)
1981 def find(self, *args):
1982 """Internal function."""
1983 return self._getints(
1984 self.tk.call((self._w, 'find') + args)) or ()
1985 def find_above(self, tagOrId):
1986 """Return items above TAGORID."""
1987 return self.find('above', tagOrId)
1988 def find_all(self):
1989 """Return all items."""
1990 return self.find('all')
1991 def find_below(self, tagOrId):
1992 """Return all items below TAGORID."""
1993 return self.find('below', tagOrId)
1994 def find_closest(self, x, y, halo=None, start=None):
1995 """Return item which is closest to pixel at X, Y.
1996 If several match take the top-most.
1997 All items closer than HALO are considered overlapping (all are
1998 closests). If START is specified the next below this tag is taken."""
1999 return self.find('closest', x, y, halo, start)
2000 def find_enclosed(self, x1, y1, x2, y2):
2001 """Return all items in rectangle defined
2002 by X1,Y1,X2,Y2."""
2003 return self.find('enclosed', x1, y1, x2, y2)
2004 def find_overlapping(self, x1, y1, x2, y2):
2005 """Return all items which overlap the rectangle
2006 defined by X1,Y1,X2,Y2."""
2007 return self.find('overlapping', x1, y1, x2, y2)
2008 def find_withtag(self, tagOrId):
2009 """Return all items with TAGORID."""
2010 return self.find('withtag', tagOrId)
2011 def focus(self, *args):
2012 """Set focus to the first item specified in ARGS."""
2013 return self.tk.call((self._w, 'focus') + args)
2014 def gettags(self, *args):
2015 """Return tags associated with the first item specified in ARGS."""
2016 return self.tk.splitlist(
2017 self.tk.call((self._w, 'gettags') + args))
2018 def icursor(self, *args):
2019 """Set cursor at position POS in the item identified by TAGORID.
2020 In ARGS TAGORID must be first."""
2021 self.tk.call((self._w, 'icursor') + args)
2022 def index(self, *args):
2023 """Return position of cursor as integer in item specified in ARGS."""
2024 return getint(self.tk.call((self._w, 'index') + args))
2025 def insert(self, *args):
2026 """Insert TEXT in item TAGORID at position POS. ARGS must
2027 be TAGORID POS TEXT."""
2028 self.tk.call((self._w, 'insert') + args)
2029 def itemcget(self, tagOrId, option):
2030 """Return the resource value for an OPTION for item TAGORID."""
2031 return self.tk.call(
2032 (self._w, 'itemcget') + (tagOrId, '-'+option))
2033 def itemconfigure(self, tagOrId, cnf=None, **kw):
2034 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002035
Fredrik Lundh06d28152000-08-09 18:03:12 +00002036 The values for resources are specified as keyword
2037 arguments. To get an overview about
2038 the allowed keyword arguments call the method without arguments.
2039 """
2040 if cnf is None and not kw:
2041 cnf = {}
2042 for x in self.tk.split(
2043 self.tk.call(self._w,
2044 'itemconfigure', tagOrId)):
2045 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2046 return cnf
2047 if type(cnf) == StringType and not kw:
2048 x = self.tk.split(self.tk.call(
2049 self._w, 'itemconfigure', tagOrId, '-'+cnf))
2050 return (x[0][1:],) + x[1:]
2051 self.tk.call((self._w, 'itemconfigure', tagOrId) +
2052 self._options(cnf, kw))
2053 itemconfig = itemconfigure
2054 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2055 # so the preferred name for them is tag_lower, tag_raise
2056 # (similar to tag_bind, and similar to the Text widget);
2057 # unfortunately can't delete the old ones yet (maybe in 1.6)
2058 def tag_lower(self, *args):
2059 """Lower an item TAGORID given in ARGS
2060 (optional below another item)."""
2061 self.tk.call((self._w, 'lower') + args)
2062 lower = tag_lower
2063 def move(self, *args):
2064 """Move an item TAGORID given in ARGS."""
2065 self.tk.call((self._w, 'move') + args)
2066 def postscript(self, cnf={}, **kw):
2067 """Print the contents of the canvas to a postscript
2068 file. Valid options: colormap, colormode, file, fontmap,
2069 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2070 rotate, witdh, x, y."""
2071 return self.tk.call((self._w, 'postscript') +
2072 self._options(cnf, kw))
2073 def tag_raise(self, *args):
2074 """Raise an item TAGORID given in ARGS
2075 (optional above another item)."""
2076 self.tk.call((self._w, 'raise') + args)
2077 lift = tkraise = tag_raise
2078 def scale(self, *args):
2079 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2080 self.tk.call((self._w, 'scale') + args)
2081 def scan_mark(self, x, y):
2082 """Remember the current X, Y coordinates."""
2083 self.tk.call(self._w, 'scan', 'mark', x, y)
2084 def scan_dragto(self, x, y):
2085 """Adjust the view of the canvas to 10 times the
2086 difference between X and Y and the coordinates given in
2087 scan_mark."""
2088 self.tk.call(self._w, 'scan', 'dragto', x, y)
2089 def select_adjust(self, tagOrId, index):
2090 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2091 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2092 def select_clear(self):
2093 """Clear the selection if it is in this widget."""
2094 self.tk.call(self._w, 'select', 'clear')
2095 def select_from(self, tagOrId, index):
2096 """Set the fixed end of a selection in item TAGORID to INDEX."""
2097 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2098 def select_item(self):
2099 """Return the item which has the selection."""
2100 self.tk.call(self._w, 'select', 'item')
2101 def select_to(self, tagOrId, index):
2102 """Set the variable end of a selection in item TAGORID to INDEX."""
2103 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2104 def type(self, tagOrId):
2105 """Return the type of the item TAGORID."""
2106 return self.tk.call(self._w, 'type', tagOrId) or None
2107 def xview(self, *args):
2108 """Query and change horizontal position of the view."""
2109 if not args:
2110 return self._getdoubles(self.tk.call(self._w, 'xview'))
2111 self.tk.call((self._w, 'xview') + args)
2112 def xview_moveto(self, fraction):
2113 """Adjusts the view in the window so that FRACTION of the
2114 total width of the canvas is off-screen to the left."""
2115 self.tk.call(self._w, 'xview', 'moveto', fraction)
2116 def xview_scroll(self, number, what):
2117 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2118 self.tk.call(self._w, 'xview', 'scroll', number, what)
2119 def yview(self, *args):
2120 """Query and change vertical position of the view."""
2121 if not args:
2122 return self._getdoubles(self.tk.call(self._w, 'yview'))
2123 self.tk.call((self._w, 'yview') + args)
2124 def yview_moveto(self, fraction):
2125 """Adjusts the view in the window so that FRACTION of the
2126 total height of the canvas is off-screen to the top."""
2127 self.tk.call(self._w, 'yview', 'moveto', fraction)
2128 def yview_scroll(self, number, what):
2129 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2130 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002131
2132class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002133 """Checkbutton widget which is either in on- or off-state."""
2134 def __init__(self, master=None, cnf={}, **kw):
2135 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002136
Fredrik Lundh06d28152000-08-09 18:03:12 +00002137 Valid resource names: activebackground, activeforeground, anchor,
2138 background, bd, bg, bitmap, borderwidth, command, cursor,
2139 disabledforeground, fg, font, foreground, height,
2140 highlightbackground, highlightcolor, highlightthickness, image,
2141 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2142 selectcolor, selectimage, state, takefocus, text, textvariable,
2143 underline, variable, width, wraplength."""
2144 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2145 def deselect(self):
2146 """Put the button in off-state."""
2147 self.tk.call(self._w, 'deselect')
2148 def flash(self):
2149 """Flash the button."""
2150 self.tk.call(self._w, 'flash')
2151 def invoke(self):
2152 """Toggle the button and invoke a command if given as resource."""
2153 return self.tk.call(self._w, 'invoke')
2154 def select(self):
2155 """Put the button in on-state."""
2156 self.tk.call(self._w, 'select')
2157 def toggle(self):
2158 """Toggle the button."""
2159 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002160
2161class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002162 """Entry widget which allows to display simple text."""
2163 def __init__(self, master=None, cnf={}, **kw):
2164 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002165
Fredrik Lundh06d28152000-08-09 18:03:12 +00002166 Valid resource names: background, bd, bg, borderwidth, cursor,
2167 exportselection, fg, font, foreground, highlightbackground,
2168 highlightcolor, highlightthickness, insertbackground,
2169 insertborderwidth, insertofftime, insertontime, insertwidth,
2170 invalidcommand, invcmd, justify, relief, selectbackground,
2171 selectborderwidth, selectforeground, show, state, takefocus,
2172 textvariable, validate, validatecommand, vcmd, width,
2173 xscrollcommand."""
2174 Widget.__init__(self, master, 'entry', cnf, kw)
2175 def delete(self, first, last=None):
2176 """Delete text from FIRST to LAST (not included)."""
2177 self.tk.call(self._w, 'delete', first, last)
2178 def get(self):
2179 """Return the text."""
2180 return self.tk.call(self._w, 'get')
2181 def icursor(self, index):
2182 """Insert cursor at INDEX."""
2183 self.tk.call(self._w, 'icursor', index)
2184 def index(self, index):
2185 """Return position of cursor."""
2186 return getint(self.tk.call(
2187 self._w, 'index', index))
2188 def insert(self, index, string):
2189 """Insert STRING at INDEX."""
2190 self.tk.call(self._w, 'insert', index, string)
2191 def scan_mark(self, x):
2192 """Remember the current X, Y coordinates."""
2193 self.tk.call(self._w, 'scan', 'mark', x)
2194 def scan_dragto(self, x):
2195 """Adjust the view of the canvas to 10 times the
2196 difference between X and Y and the coordinates given in
2197 scan_mark."""
2198 self.tk.call(self._w, 'scan', 'dragto', x)
2199 def selection_adjust(self, index):
2200 """Adjust the end of the selection near the cursor to INDEX."""
2201 self.tk.call(self._w, 'selection', 'adjust', index)
2202 select_adjust = selection_adjust
2203 def selection_clear(self):
2204 """Clear the selection if it is in this widget."""
2205 self.tk.call(self._w, 'selection', 'clear')
2206 select_clear = selection_clear
2207 def selection_from(self, index):
2208 """Set the fixed end of a selection to INDEX."""
2209 self.tk.call(self._w, 'selection', 'from', index)
2210 select_from = selection_from
2211 def selection_present(self):
2212 """Return whether the widget has the selection."""
2213 return self.tk.getboolean(
2214 self.tk.call(self._w, 'selection', 'present'))
2215 select_present = selection_present
2216 def selection_range(self, start, end):
2217 """Set the selection from START to END (not included)."""
2218 self.tk.call(self._w, 'selection', 'range', start, end)
2219 select_range = selection_range
2220 def selection_to(self, index):
2221 """Set the variable end of a selection to INDEX."""
2222 self.tk.call(self._w, 'selection', 'to', index)
2223 select_to = selection_to
2224 def xview(self, index):
2225 """Query and change horizontal position of the view."""
2226 self.tk.call(self._w, 'xview', index)
2227 def xview_moveto(self, fraction):
2228 """Adjust the view in the window so that FRACTION of the
2229 total width of the entry is off-screen to the left."""
2230 self.tk.call(self._w, 'xview', 'moveto', fraction)
2231 def xview_scroll(self, number, what):
2232 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2233 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002234
2235class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002236 """Frame widget which may contain other widgets and can have a 3D border."""
2237 def __init__(self, master=None, cnf={}, **kw):
2238 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002239
Fredrik Lundh06d28152000-08-09 18:03:12 +00002240 Valid resource names: background, bd, bg, borderwidth, class,
2241 colormap, container, cursor, height, highlightbackground,
2242 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2243 cnf = _cnfmerge((cnf, kw))
2244 extra = ()
2245 if cnf.has_key('class_'):
2246 extra = ('-class', cnf['class_'])
2247 del cnf['class_']
2248 elif cnf.has_key('class'):
2249 extra = ('-class', cnf['class'])
2250 del cnf['class']
2251 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002252
2253class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002254 """Label widget which can display text and bitmaps."""
2255 def __init__(self, master=None, cnf={}, **kw):
2256 """Construct a label widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002257
Fredrik Lundh06d28152000-08-09 18:03:12 +00002258 Valid resource names: anchor, background, bd, bg, bitmap,
2259 borderwidth, cursor, fg, font, foreground, height,
2260 highlightbackground, highlightcolor, highlightthickness, image,
2261 justify, padx, pady, relief, takefocus, text, textvariable,
2262 underline, width, wraplength."""
2263 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002264
Guido van Rossum18468821994-06-20 07:49:28 +00002265class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002266 """Listbox widget which can display a list of strings."""
2267 def __init__(self, master=None, cnf={}, **kw):
2268 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002269
Fredrik Lundh06d28152000-08-09 18:03:12 +00002270 Valid resource names: background, bd, bg, borderwidth, cursor,
2271 exportselection, fg, font, foreground, height, highlightbackground,
2272 highlightcolor, highlightthickness, relief, selectbackground,
2273 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2274 width, xscrollcommand, yscrollcommand, listvariable."""
2275 Widget.__init__(self, master, 'listbox', cnf, kw)
2276 def activate(self, index):
2277 """Activate item identified by INDEX."""
2278 self.tk.call(self._w, 'activate', index)
2279 def bbox(self, *args):
2280 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2281 which encloses the item identified by index in ARGS."""
2282 return self._getints(
2283 self.tk.call((self._w, 'bbox') + args)) or None
2284 def curselection(self):
2285 """Return list of indices of currently selected item."""
2286 # XXX Ought to apply self._getints()...
2287 return self.tk.splitlist(self.tk.call(
2288 self._w, 'curselection'))
2289 def delete(self, first, last=None):
2290 """Delete items from FIRST to LAST (not included)."""
2291 self.tk.call(self._w, 'delete', first, last)
2292 def get(self, first, last=None):
2293 """Get list of items from FIRST to LAST (not included)."""
2294 if last:
2295 return self.tk.splitlist(self.tk.call(
2296 self._w, 'get', first, last))
2297 else:
2298 return self.tk.call(self._w, 'get', first)
2299 def index(self, index):
2300 """Return index of item identified with INDEX."""
2301 i = self.tk.call(self._w, 'index', index)
2302 if i == 'none': return None
2303 return getint(i)
2304 def insert(self, index, *elements):
2305 """Insert ELEMENTS at INDEX."""
2306 self.tk.call((self._w, 'insert', index) + elements)
2307 def nearest(self, y):
2308 """Get index of item which is nearest to y coordinate Y."""
2309 return getint(self.tk.call(
2310 self._w, 'nearest', y))
2311 def scan_mark(self, x, y):
2312 """Remember the current X, Y coordinates."""
2313 self.tk.call(self._w, 'scan', 'mark', x, y)
2314 def scan_dragto(self, x, y):
2315 """Adjust the view of the listbox to 10 times the
2316 difference between X and Y and the coordinates given in
2317 scan_mark."""
2318 self.tk.call(self._w, 'scan', 'dragto', x, y)
2319 def see(self, index):
2320 """Scroll such that INDEX is visible."""
2321 self.tk.call(self._w, 'see', index)
2322 def selection_anchor(self, index):
2323 """Set the fixed end oft the selection to INDEX."""
2324 self.tk.call(self._w, 'selection', 'anchor', index)
2325 select_anchor = selection_anchor
2326 def selection_clear(self, first, last=None):
2327 """Clear the selection from FIRST to LAST (not included)."""
2328 self.tk.call(self._w,
2329 'selection', 'clear', first, last)
2330 select_clear = selection_clear
2331 def selection_includes(self, index):
2332 """Return 1 if INDEX is part of the selection."""
2333 return self.tk.getboolean(self.tk.call(
2334 self._w, 'selection', 'includes', index))
2335 select_includes = selection_includes
2336 def selection_set(self, first, last=None):
2337 """Set the selection from FIRST to LAST (not included) without
2338 changing the currently selected elements."""
2339 self.tk.call(self._w, 'selection', 'set', first, last)
2340 select_set = selection_set
2341 def size(self):
2342 """Return the number of elements in the listbox."""
2343 return getint(self.tk.call(self._w, 'size'))
2344 def xview(self, *what):
2345 """Query and change horizontal position of the view."""
2346 if not what:
2347 return self._getdoubles(self.tk.call(self._w, 'xview'))
2348 self.tk.call((self._w, 'xview') + what)
2349 def xview_moveto(self, fraction):
2350 """Adjust the view in the window so that FRACTION of the
2351 total width of the entry is off-screen to the left."""
2352 self.tk.call(self._w, 'xview', 'moveto', fraction)
2353 def xview_scroll(self, number, what):
2354 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2355 self.tk.call(self._w, 'xview', 'scroll', number, what)
2356 def yview(self, *what):
2357 """Query and change vertical position of the view."""
2358 if not what:
2359 return self._getdoubles(self.tk.call(self._w, 'yview'))
2360 self.tk.call((self._w, 'yview') + what)
2361 def yview_moveto(self, fraction):
2362 """Adjust the view in the window so that FRACTION of the
2363 total width of the entry is off-screen to the top."""
2364 self.tk.call(self._w, 'yview', 'moveto', fraction)
2365 def yview_scroll(self, number, what):
2366 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2367 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002368
2369class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002370 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2371 def __init__(self, master=None, cnf={}, **kw):
2372 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002373
Fredrik Lundh06d28152000-08-09 18:03:12 +00002374 Valid resource names: activebackground, activeborderwidth,
2375 activeforeground, background, bd, bg, borderwidth, cursor,
2376 disabledforeground, fg, font, foreground, postcommand, relief,
2377 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2378 Widget.__init__(self, master, 'menu', cnf, kw)
2379 def tk_bindForTraversal(self):
2380 pass # obsolete since Tk 4.0
2381 def tk_mbPost(self):
2382 self.tk.call('tk_mbPost', self._w)
2383 def tk_mbUnpost(self):
2384 self.tk.call('tk_mbUnpost')
2385 def tk_traverseToMenu(self, char):
2386 self.tk.call('tk_traverseToMenu', self._w, char)
2387 def tk_traverseWithinMenu(self, char):
2388 self.tk.call('tk_traverseWithinMenu', self._w, char)
2389 def tk_getMenuButtons(self):
2390 return self.tk.call('tk_getMenuButtons', self._w)
2391 def tk_nextMenu(self, count):
2392 self.tk.call('tk_nextMenu', count)
2393 def tk_nextMenuEntry(self, count):
2394 self.tk.call('tk_nextMenuEntry', count)
2395 def tk_invokeMenu(self):
2396 self.tk.call('tk_invokeMenu', self._w)
2397 def tk_firstMenu(self):
2398 self.tk.call('tk_firstMenu', self._w)
2399 def tk_mbButtonDown(self):
2400 self.tk.call('tk_mbButtonDown', self._w)
2401 def tk_popup(self, x, y, entry=""):
2402 """Post the menu at position X,Y with entry ENTRY."""
2403 self.tk.call('tk_popup', self._w, x, y, entry)
2404 def activate(self, index):
2405 """Activate entry at INDEX."""
2406 self.tk.call(self._w, 'activate', index)
2407 def add(self, itemType, cnf={}, **kw):
2408 """Internal function."""
2409 self.tk.call((self._w, 'add', itemType) +
2410 self._options(cnf, kw))
2411 def add_cascade(self, cnf={}, **kw):
2412 """Add hierarchical menu item."""
2413 self.add('cascade', cnf or kw)
2414 def add_checkbutton(self, cnf={}, **kw):
2415 """Add checkbutton menu item."""
2416 self.add('checkbutton', cnf or kw)
2417 def add_command(self, cnf={}, **kw):
2418 """Add command menu item."""
2419 self.add('command', cnf or kw)
2420 def add_radiobutton(self, cnf={}, **kw):
2421 """Addd radio menu item."""
2422 self.add('radiobutton', cnf or kw)
2423 def add_separator(self, cnf={}, **kw):
2424 """Add separator."""
2425 self.add('separator', cnf or kw)
2426 def insert(self, index, itemType, cnf={}, **kw):
2427 """Internal function."""
2428 self.tk.call((self._w, 'insert', index, itemType) +
2429 self._options(cnf, kw))
2430 def insert_cascade(self, index, cnf={}, **kw):
2431 """Add hierarchical menu item at INDEX."""
2432 self.insert(index, 'cascade', cnf or kw)
2433 def insert_checkbutton(self, index, cnf={}, **kw):
2434 """Add checkbutton menu item at INDEX."""
2435 self.insert(index, 'checkbutton', cnf or kw)
2436 def insert_command(self, index, cnf={}, **kw):
2437 """Add command menu item at INDEX."""
2438 self.insert(index, 'command', cnf or kw)
2439 def insert_radiobutton(self, index, cnf={}, **kw):
2440 """Addd radio menu item at INDEX."""
2441 self.insert(index, 'radiobutton', cnf or kw)
2442 def insert_separator(self, index, cnf={}, **kw):
2443 """Add separator at INDEX."""
2444 self.insert(index, 'separator', cnf or kw)
2445 def delete(self, index1, index2=None):
2446 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2447 self.tk.call(self._w, 'delete', index1, index2)
2448 def entrycget(self, index, option):
2449 """Return the resource value of an menu item for OPTION at INDEX."""
2450 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2451 def entryconfigure(self, index, cnf=None, **kw):
2452 """Configure a menu item at INDEX."""
2453 if cnf is None and not kw:
2454 cnf = {}
2455 for x in self.tk.split(self.tk.call(
2456 (self._w, 'entryconfigure', index))):
2457 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2458 return cnf
2459 if type(cnf) == StringType and not kw:
2460 x = self.tk.split(self.tk.call(
2461 (self._w, 'entryconfigure', index, '-'+cnf)))
2462 return (x[0][1:],) + x[1:]
2463 self.tk.call((self._w, 'entryconfigure', index)
2464 + self._options(cnf, kw))
2465 entryconfig = entryconfigure
2466 def index(self, index):
2467 """Return the index of a menu item identified by INDEX."""
2468 i = self.tk.call(self._w, 'index', index)
2469 if i == 'none': return None
2470 return getint(i)
2471 def invoke(self, index):
2472 """Invoke a menu item identified by INDEX and execute
2473 the associated command."""
2474 return self.tk.call(self._w, 'invoke', index)
2475 def post(self, x, y):
2476 """Display a menu at position X,Y."""
2477 self.tk.call(self._w, 'post', x, y)
2478 def type(self, index):
2479 """Return the type of the menu item at INDEX."""
2480 return self.tk.call(self._w, 'type', index)
2481 def unpost(self):
2482 """Unmap a menu."""
2483 self.tk.call(self._w, 'unpost')
2484 def yposition(self, index):
2485 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2486 return getint(self.tk.call(
2487 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002488
2489class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002490 """Menubutton widget, obsolete since Tk8.0."""
2491 def __init__(self, master=None, cnf={}, **kw):
2492 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002493
2494class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002495 """Message widget to display multiline text. Obsolete since Label does it too."""
2496 def __init__(self, master=None, cnf={}, **kw):
2497 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002498
2499class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002500 """Radiobutton widget which shows only one of several buttons in on-state."""
2501 def __init__(self, master=None, cnf={}, **kw):
2502 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002503
Fredrik Lundh06d28152000-08-09 18:03:12 +00002504 Valid resource names: activebackground, activeforeground, anchor,
2505 background, bd, bg, bitmap, borderwidth, command, cursor,
2506 disabledforeground, fg, font, foreground, height,
2507 highlightbackground, highlightcolor, highlightthickness, image,
2508 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2509 state, takefocus, text, textvariable, underline, value, variable,
2510 width, wraplength."""
2511 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2512 def deselect(self):
2513 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002514
Fredrik Lundh06d28152000-08-09 18:03:12 +00002515 self.tk.call(self._w, 'deselect')
2516 def flash(self):
2517 """Flash the button."""
2518 self.tk.call(self._w, 'flash')
2519 def invoke(self):
2520 """Toggle the button and invoke a command if given as resource."""
2521 return self.tk.call(self._w, 'invoke')
2522 def select(self):
2523 """Put the button in on-state."""
2524 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002525
2526class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002527 """Scale widget which can display a numerical scale."""
2528 def __init__(self, master=None, cnf={}, **kw):
2529 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002530
Fredrik Lundh06d28152000-08-09 18:03:12 +00002531 Valid resource names: activebackground, background, bigincrement, bd,
2532 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2533 highlightbackground, highlightcolor, highlightthickness, label,
2534 length, orient, relief, repeatdelay, repeatinterval, resolution,
2535 showvalue, sliderlength, sliderrelief, state, takefocus,
2536 tickinterval, to, troughcolor, variable, width."""
2537 Widget.__init__(self, master, 'scale', cnf, kw)
2538 def get(self):
2539 """Get the current value as integer or float."""
2540 value = self.tk.call(self._w, 'get')
2541 try:
2542 return getint(value)
2543 except ValueError:
2544 return getdouble(value)
2545 def set(self, value):
2546 """Set the value to VALUE."""
2547 self.tk.call(self._w, 'set', value)
2548 def coords(self, value=None):
2549 """Return a tuple (X,Y) of the point along the centerline of the
2550 trough that corresponds to VALUE or the current value if None is
2551 given."""
2552
2553 return self._getints(self.tk.call(self._w, 'coords', value))
2554 def identify(self, x, y):
2555 """Return where the point X,Y lies. Valid return values are "slider",
2556 "though1" and "though2"."""
2557 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002558
2559class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002560 """Scrollbar widget which displays a slider at a certain position."""
2561 def __init__(self, master=None, cnf={}, **kw):
2562 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002563
Fredrik Lundh06d28152000-08-09 18:03:12 +00002564 Valid resource names: activebackground, activerelief,
2565 background, bd, bg, borderwidth, command, cursor,
2566 elementborderwidth, highlightbackground,
2567 highlightcolor, highlightthickness, jump, orient,
2568 relief, repeatdelay, repeatinterval, takefocus,
2569 troughcolor, width."""
2570 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2571 def activate(self, index):
2572 """Display the element at INDEX with activebackground and activerelief.
2573 INDEX can be "arrow1","slider" or "arrow2"."""
2574 self.tk.call(self._w, 'activate', index)
2575 def delta(self, deltax, deltay):
2576 """Return the fractional change of the scrollbar setting if it
2577 would be moved by DELTAX or DELTAY pixels."""
2578 return getdouble(
2579 self.tk.call(self._w, 'delta', deltax, deltay))
2580 def fraction(self, x, y):
2581 """Return the fractional value which corresponds to a slider
2582 position of X,Y."""
2583 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2584 def identify(self, x, y):
2585 """Return the element under position X,Y as one of
2586 "arrow1","slider","arrow2" or ""."""
2587 return self.tk.call(self._w, 'identify', x, y)
2588 def get(self):
2589 """Return the current fractional values (upper and lower end)
2590 of the slider position."""
2591 return self._getdoubles(self.tk.call(self._w, 'get'))
2592 def set(self, *args):
2593 """Set the fractional values of the slider position (upper and
2594 lower ends as value between 0 and 1)."""
2595 self.tk.call((self._w, 'set') + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002596
2597class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002598 """Text widget which can display text in various forms."""
2599 # XXX Add dump()
2600 def __init__(self, master=None, cnf={}, **kw):
2601 """Construct a text widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002602
Fredrik Lundh06d28152000-08-09 18:03:12 +00002603 Valid resource names: background, bd, bg, borderwidth, cursor,
2604 exportselection, fg, font, foreground, height,
2605 highlightbackground, highlightcolor, highlightthickness,
2606 insertbackground, insertborderwidth, insertofftime,
2607 insertontime, insertwidth, padx, pady, relief,
2608 selectbackground, selectborderwidth, selectforeground,
2609 setgrid, spacing1, spacing2, spacing3, state, tabs, takefocus,
2610 width, wrap, xscrollcommand, yscrollcommand."""
2611 Widget.__init__(self, master, 'text', cnf, kw)
2612 def bbox(self, *args):
2613 """Return a tuple of (x,y,width,height) which gives the bounding
2614 box of the visible part of the character at the index in ARGS."""
2615 return self._getints(
2616 self.tk.call((self._w, 'bbox') + args)) or None
2617 def tk_textSelectTo(self, index):
2618 self.tk.call('tk_textSelectTo', self._w, index)
2619 def tk_textBackspace(self):
2620 self.tk.call('tk_textBackspace', self._w)
2621 def tk_textIndexCloser(self, a, b, c):
2622 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2623 def tk_textResetAnchor(self, index):
2624 self.tk.call('tk_textResetAnchor', self._w, index)
2625 def compare(self, index1, op, index2):
2626 """Return whether between index INDEX1 and index INDEX2 the
2627 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2628 return self.tk.getboolean(self.tk.call(
2629 self._w, 'compare', index1, op, index2))
2630 def debug(self, boolean=None):
2631 """Turn on the internal consistency checks of the B-Tree inside the text
2632 widget according to BOOLEAN."""
2633 return self.tk.getboolean(self.tk.call(
2634 self._w, 'debug', boolean))
2635 def delete(self, index1, index2=None):
2636 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2637 self.tk.call(self._w, 'delete', index1, index2)
2638 def dlineinfo(self, index):
2639 """Return tuple (x,y,width,height,baseline) giving the bounding box
2640 and baseline position of the visible part of the line containing
2641 the character at INDEX."""
2642 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
2643 def get(self, index1, index2=None):
2644 """Return the text from INDEX1 to INDEX2 (not included)."""
2645 return self.tk.call(self._w, 'get', index1, index2)
2646 # (Image commands are new in 8.0)
2647 def image_cget(self, index, option):
2648 """Return the value of OPTION of an embedded image at INDEX."""
2649 if option[:1] != "-":
2650 option = "-" + option
2651 if option[-1:] == "_":
2652 option = option[:-1]
2653 return self.tk.call(self._w, "image", "cget", index, option)
2654 def image_configure(self, index, cnf={}, **kw):
2655 """Configure an embedded image at INDEX."""
2656 if not cnf and not kw:
2657 cnf = {}
2658 for x in self.tk.split(
2659 self.tk.call(
2660 self._w, "image", "configure", index)):
2661 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
2662 return cnf
2663 apply(self.tk.call,
2664 (self._w, "image", "configure", index)
2665 + self._options(cnf, kw))
2666 def image_create(self, index, cnf={}, **kw):
2667 """Create an embedded image at INDEX."""
2668 return apply(self.tk.call,
2669 (self._w, "image", "create", index)
2670 + self._options(cnf, kw))
2671 def image_names(self):
2672 """Return all names of embedded images in this widget."""
2673 return self.tk.call(self._w, "image", "names")
2674 def index(self, index):
2675 """Return the index in the form line.char for INDEX."""
2676 return self.tk.call(self._w, 'index', index)
2677 def insert(self, index, chars, *args):
2678 """Insert CHARS before the characters at INDEX. An additional
2679 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2680 self.tk.call((self._w, 'insert', index, chars) + args)
2681 def mark_gravity(self, markName, direction=None):
2682 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2683 Return the current value if None is given for DIRECTION."""
2684 return self.tk.call(
2685 (self._w, 'mark', 'gravity', markName, direction))
2686 def mark_names(self):
2687 """Return all mark names."""
2688 return self.tk.splitlist(self.tk.call(
2689 self._w, 'mark', 'names'))
2690 def mark_set(self, markName, index):
2691 """Set mark MARKNAME before the character at INDEX."""
2692 self.tk.call(self._w, 'mark', 'set', markName, index)
2693 def mark_unset(self, *markNames):
2694 """Delete all marks in MARKNAMES."""
2695 self.tk.call((self._w, 'mark', 'unset') + markNames)
2696 def mark_next(self, index):
2697 """Return the name of the next mark after INDEX."""
2698 return self.tk.call(self._w, 'mark', 'next', index) or None
2699 def mark_previous(self, index):
2700 """Return the name of the previous mark before INDEX."""
2701 return self.tk.call(self._w, 'mark', 'previous', index) or None
2702 def scan_mark(self, x, y):
2703 """Remember the current X, Y coordinates."""
2704 self.tk.call(self._w, 'scan', 'mark', x, y)
2705 def scan_dragto(self, x, y):
2706 """Adjust the view of the text to 10 times the
2707 difference between X and Y and the coordinates given in
2708 scan_mark."""
2709 self.tk.call(self._w, 'scan', 'dragto', x, y)
2710 def search(self, pattern, index, stopindex=None,
2711 forwards=None, backwards=None, exact=None,
2712 regexp=None, nocase=None, count=None):
2713 """Search PATTERN beginning from INDEX until STOPINDEX.
2714 Return the index of the first character of a match or an empty string."""
2715 args = [self._w, 'search']
2716 if forwards: args.append('-forwards')
2717 if backwards: args.append('-backwards')
2718 if exact: args.append('-exact')
2719 if regexp: args.append('-regexp')
2720 if nocase: args.append('-nocase')
2721 if count: args.append('-count'); args.append(count)
2722 if pattern[0] == '-': args.append('--')
2723 args.append(pattern)
2724 args.append(index)
2725 if stopindex: args.append(stopindex)
2726 return self.tk.call(tuple(args))
2727 def see(self, index):
2728 """Scroll such that the character at INDEX is visible."""
2729 self.tk.call(self._w, 'see', index)
2730 def tag_add(self, tagName, index1, *args):
2731 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2732 Additional pairs of indices may follow in ARGS."""
2733 self.tk.call(
2734 (self._w, 'tag', 'add', tagName, index1) + args)
2735 def tag_unbind(self, tagName, sequence, funcid=None):
2736 """Unbind for all characters with TAGNAME for event SEQUENCE the
2737 function identified with FUNCID."""
2738 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2739 if funcid:
2740 self.deletecommand(funcid)
2741 def tag_bind(self, tagName, sequence, func, add=None):
2742 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002743
Fredrik Lundh06d28152000-08-09 18:03:12 +00002744 An additional boolean parameter ADD specifies whether FUNC will be
2745 called additionally to the other bound function or whether it will
2746 replace the previous function. See bind for the return value."""
2747 return self._bind((self._w, 'tag', 'bind', tagName),
2748 sequence, func, add)
2749 def tag_cget(self, tagName, option):
2750 """Return the value of OPTION for tag TAGNAME."""
2751 if option[:1] != '-':
2752 option = '-' + option
2753 if option[-1:] == '_':
2754 option = option[:-1]
2755 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
2756 def tag_configure(self, tagName, cnf={}, **kw):
2757 """Configure a tag TAGNAME."""
2758 if type(cnf) == StringType:
2759 x = self.tk.split(self.tk.call(
2760 self._w, 'tag', 'configure', tagName, '-'+cnf))
2761 return (x[0][1:],) + x[1:]
2762 self.tk.call(
2763 (self._w, 'tag', 'configure', tagName)
2764 + self._options(cnf, kw))
2765 tag_config = tag_configure
2766 def tag_delete(self, *tagNames):
2767 """Delete all tags in TAGNAMES."""
2768 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2769 def tag_lower(self, tagName, belowThis=None):
2770 """Change the priority of tag TAGNAME such that it is lower
2771 than the priority of BELOWTHIS."""
2772 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2773 def tag_names(self, index=None):
2774 """Return a list of all tag names."""
2775 return self.tk.splitlist(
2776 self.tk.call(self._w, 'tag', 'names', index))
2777 def tag_nextrange(self, tagName, index1, index2=None):
2778 """Return a list of start and end index for the first sequence of
2779 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2780 The text is searched forward from INDEX1."""
2781 return self.tk.splitlist(self.tk.call(
2782 self._w, 'tag', 'nextrange', tagName, index1, index2))
2783 def tag_prevrange(self, tagName, index1, index2=None):
2784 """Return a list of start and end index for the first sequence of
2785 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2786 The text is searched backwards from INDEX1."""
2787 return self.tk.splitlist(self.tk.call(
2788 self._w, 'tag', 'prevrange', tagName, index1, index2))
2789 def tag_raise(self, tagName, aboveThis=None):
2790 """Change the priority of tag TAGNAME such that it is higher
2791 than the priority of ABOVETHIS."""
2792 self.tk.call(
2793 self._w, 'tag', 'raise', tagName, aboveThis)
2794 def tag_ranges(self, tagName):
2795 """Return a list of ranges of text which have tag TAGNAME."""
2796 return self.tk.splitlist(self.tk.call(
2797 self._w, 'tag', 'ranges', tagName))
2798 def tag_remove(self, tagName, index1, index2=None):
2799 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
2800 self.tk.call(
2801 self._w, 'tag', 'remove', tagName, index1, index2)
2802 def window_cget(self, index, option):
2803 """Return the value of OPTION of an embedded window at INDEX."""
2804 if option[:1] != '-':
2805 option = '-' + option
2806 if option[-1:] == '_':
2807 option = option[:-1]
2808 return self.tk.call(self._w, 'window', 'cget', index, option)
2809 def window_configure(self, index, cnf={}, **kw):
2810 """Configure an embedded window at INDEX."""
2811 if type(cnf) == StringType:
2812 x = self.tk.split(self.tk.call(
2813 self._w, 'window', 'configure',
2814 index, '-'+cnf))
2815 return (x[0][1:],) + x[1:]
2816 self.tk.call(
2817 (self._w, 'window', 'configure', index)
2818 + self._options(cnf, kw))
2819 window_config = window_configure
2820 def window_create(self, index, cnf={}, **kw):
2821 """Create a window at INDEX."""
2822 self.tk.call(
2823 (self._w, 'window', 'create', index)
2824 + self._options(cnf, kw))
2825 def window_names(self):
2826 """Return all names of embedded windows in this widget."""
2827 return self.tk.splitlist(
2828 self.tk.call(self._w, 'window', 'names'))
2829 def xview(self, *what):
2830 """Query and change horizontal position of the view."""
2831 if not what:
2832 return self._getdoubles(self.tk.call(self._w, 'xview'))
2833 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002834 def xview_moveto(self, fraction):
2835 """Adjusts the view in the window so that FRACTION of the
2836 total width of the canvas is off-screen to the left."""
2837 self.tk.call(self._w, 'xview', 'moveto', fraction)
2838 def xview_scroll(self, number, what):
2839 """Shift the x-view according to NUMBER which is measured
2840 in "units" or "pages" (WHAT)."""
2841 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002842 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002843 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002844 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002845 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00002846 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00002847 def yview_moveto(self, fraction):
2848 """Adjusts the view in the window so that FRACTION of the
2849 total height of the canvas is off-screen to the top."""
2850 self.tk.call(self._w, 'yview', 'moveto', fraction)
2851 def yview_scroll(self, number, what):
2852 """Shift the y-view according to NUMBER which is measured
2853 in "units" or "pages" (WHAT)."""
2854 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002855 def yview_pickplace(self, *what):
2856 """Obsolete function, use see."""
2857 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00002858
Guido van Rossum28574b51996-10-21 15:16:51 +00002859class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002860 """Internal class. It wraps the command in the widget OptionMenu."""
2861 def __init__(self, var, value, callback=None):
2862 self.__value = value
2863 self.__var = var
2864 self.__callback = callback
2865 def __call__(self, *args):
2866 self.__var.set(self.__value)
2867 if self.__callback:
2868 apply(self.__callback, (self.__value,)+args)
Guido van Rossum28574b51996-10-21 15:16:51 +00002869
2870class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002871 """OptionMenu which allows the user to select a value from a menu."""
2872 def __init__(self, master, variable, value, *values, **kwargs):
2873 """Construct an optionmenu widget with the parent MASTER, with
2874 the resource textvariable set to VARIABLE, the initially selected
2875 value VALUE, the other menu values VALUES and an additional
2876 keyword argument command."""
2877 kw = {"borderwidth": 2, "textvariable": variable,
2878 "indicatoron": 1, "relief": RAISED, "anchor": "c",
2879 "highlightthickness": 2}
2880 Widget.__init__(self, master, "menubutton", kw)
2881 self.widgetName = 'tk_optionMenu'
2882 menu = self.__menu = Menu(self, name="menu", tearoff=0)
2883 self.menuname = menu._w
2884 # 'command' is the only supported keyword
2885 callback = kwargs.get('command')
2886 if kwargs.has_key('command'):
2887 del kwargs['command']
2888 if kwargs:
2889 raise TclError, 'unknown option -'+kwargs.keys()[0]
2890 menu.add_command(label=value,
2891 command=_setit(variable, value, callback))
2892 for v in values:
2893 menu.add_command(label=v,
2894 command=_setit(variable, v, callback))
2895 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00002896
Fredrik Lundh06d28152000-08-09 18:03:12 +00002897 def __getitem__(self, name):
2898 if name == 'menu':
2899 return self.__menu
2900 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00002901
Fredrik Lundh06d28152000-08-09 18:03:12 +00002902 def destroy(self):
2903 """Destroy this widget and the associated menu."""
2904 Menubutton.destroy(self)
2905 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00002906
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002907class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002908 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00002909 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00002910 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
2911 self.name = None
2912 if not master:
2913 master = _default_root
2914 if not master:
2915 raise RuntimeError, 'Too early to create image'
2916 self.tk = master.tk
2917 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00002918 Image._last_id += 1
2919 name = "pyimage" +`Image._last_id` # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00002920 # The following is needed for systems where id(x)
2921 # can return a negative number, such as Linux/m68k:
2922 if name[0] == '-': name = '_' + name[1:]
2923 if kw and cnf: cnf = _cnfmerge((cnf, kw))
2924 elif kw: cnf = kw
2925 options = ()
2926 for k, v in cnf.items():
2927 if callable(v):
2928 v = self._register(v)
2929 options = options + ('-'+k, v)
2930 self.tk.call(('image', 'create', imgtype, name,) + options)
2931 self.name = name
2932 def __str__(self): return self.name
2933 def __del__(self):
2934 if self.name:
2935 try:
2936 self.tk.call('image', 'delete', self.name)
2937 except TclError:
2938 # May happen if the root was destroyed
2939 pass
2940 def __setitem__(self, key, value):
2941 self.tk.call(self.name, 'configure', '-'+key, value)
2942 def __getitem__(self, key):
2943 return self.tk.call(self.name, 'configure', '-'+key)
2944 def configure(self, **kw):
2945 """Configure the image."""
2946 res = ()
2947 for k, v in _cnfmerge(kw).items():
2948 if v is not None:
2949 if k[-1] == '_': k = k[:-1]
2950 if callable(v):
2951 v = self._register(v)
2952 res = res + ('-'+k, v)
2953 self.tk.call((self.name, 'config') + res)
2954 config = configure
2955 def height(self):
2956 """Return the height of the image."""
2957 return getint(
2958 self.tk.call('image', 'height', self.name))
2959 def type(self):
2960 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
2961 return self.tk.call('image', 'type', self.name)
2962 def width(self):
2963 """Return the width of the image."""
2964 return getint(
2965 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002966
2967class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002968 """Widget which can display colored images in GIF, PPM/PGM format."""
2969 def __init__(self, name=None, cnf={}, master=None, **kw):
2970 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002971
Fredrik Lundh06d28152000-08-09 18:03:12 +00002972 Valid resource names: data, format, file, gamma, height, palette,
2973 width."""
2974 apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
2975 def blank(self):
2976 """Display a transparent image."""
2977 self.tk.call(self.name, 'blank')
2978 def cget(self, option):
2979 """Return the value of OPTION."""
2980 return self.tk.call(self.name, 'cget', '-' + option)
2981 # XXX config
2982 def __getitem__(self, key):
2983 return self.tk.call(self.name, 'cget', '-' + key)
2984 # XXX copy -from, -to, ...?
2985 def copy(self):
2986 """Return a new PhotoImage with the same image as this widget."""
2987 destImage = PhotoImage()
2988 self.tk.call(destImage, 'copy', self.name)
2989 return destImage
2990 def zoom(self,x,y=''):
2991 """Return a new PhotoImage with the same image as this widget
2992 but zoom it with X and Y."""
2993 destImage = PhotoImage()
2994 if y=='': y=x
2995 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
2996 return destImage
2997 def subsample(self,x,y=''):
2998 """Return a new PhotoImage based on the same image as this widget
2999 but use only every Xth or Yth pixel."""
3000 destImage = PhotoImage()
3001 if y=='': y=x
3002 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3003 return destImage
3004 def get(self, x, y):
3005 """Return the color (red, green, blue) of the pixel at X,Y."""
3006 return self.tk.call(self.name, 'get', x, y)
3007 def put(self, data, to=None):
3008 """Put row formated colors to image starting from
3009 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3010 args = (self.name, 'put', data)
3011 if to:
3012 if to[0] == '-to':
3013 to = to[1:]
3014 args = args + ('-to',) + tuple(to)
3015 self.tk.call(args)
3016 # XXX read
3017 def write(self, filename, format=None, from_coords=None):
3018 """Write image to file FILENAME in FORMAT starting from
3019 position FROM_COORDS."""
3020 args = (self.name, 'write', filename)
3021 if format:
3022 args = args + ('-format', format)
3023 if from_coords:
3024 args = args + ('-from',) + tuple(from_coords)
3025 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003026
3027class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003028 """Widget which can display a bitmap."""
3029 def __init__(self, name=None, cnf={}, master=None, **kw):
3030 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003031
Fredrik Lundh06d28152000-08-09 18:03:12 +00003032 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3033 apply(Image.__init__, (self, 'bitmap', name, cnf, master), kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003034
3035def image_names(): return _default_root.tk.call('image', 'names')
3036def image_types(): return _default_root.tk.call('image', 'types')
3037
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003038######################################################################
3039# Extensions:
3040
3041class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003042 def __init__(self, master=None, cnf={}, **kw):
3043 Widget.__init__(self, master, 'studbutton', cnf, kw)
3044 self.bind('<Any-Enter>', self.tkButtonEnter)
3045 self.bind('<Any-Leave>', self.tkButtonLeave)
3046 self.bind('<1>', self.tkButtonDown)
3047 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003048
3049class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003050 def __init__(self, master=None, cnf={}, **kw):
3051 Widget.__init__(self, master, 'tributton', cnf, kw)
3052 self.bind('<Any-Enter>', self.tkButtonEnter)
3053 self.bind('<Any-Leave>', self.tkButtonLeave)
3054 self.bind('<1>', self.tkButtonDown)
3055 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3056 self['fg'] = self['bg']
3057 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003058
Guido van Rossumc417ef81996-08-21 23:38:59 +00003059######################################################################
3060# Test:
3061
3062def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003063 root = Tk()
3064 text = "This is Tcl/Tk version %s" % TclVersion
3065 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003066 try:
3067 text = text + unicode("\nThis should be a cedilla: \347",
3068 "iso-8859-1")
3069 except NameError:
3070 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003071 label = Label(root, text=text)
3072 label.pack()
3073 test = Button(root, text="Click me!",
3074 command=lambda root=root: root.test.configure(
3075 text="[%s]" % root.test['text']))
3076 test.pack()
3077 root.test = test
3078 quit = Button(root, text="QUIT", command=root.destroy)
3079 quit.pack()
3080 # The following three commands are needed so the window pops
3081 # up on top on Windows...
3082 root.iconify()
3083 root.update()
3084 root.deiconify()
3085 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003086
3087if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003088 _test()