blob: 67e942e18ad1b35c02b9dfba28ded99e29fcf27f [file] [log] [blame]
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001"""Wrapper functions for Tcl/Tk.
2
3Tkinter provides classes which allow the display, positioning and
4control of widgets. Toplevel widgets are Tk and Toplevel. Other
5widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00006Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
Raymond Hettingerff41c482003-04-06 09:01:11 +00007LabelFrame and PanedWindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00008
Raymond Hettingerff41c482003-04-06 09:01:11 +00009Properties of the widgets are specified with keyword arguments.
10Keyword arguments have the same name as the corresponding resource
Martin v. Löwis2ec36272002-10-13 10:22:08 +000011under Tk.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000012
13Widgets are positioned with one of the geometry managers Place, Pack
14or Grid. These managers can be called with methods place, pack, grid
15available in every Widget.
16
Guido van Rossuma0adb922001-09-01 18:29:55 +000017Actions are bound to events by resources (e.g. keyword argument
18command) or with the method bind.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000019
20Example (Hello, World):
21import Tkinter
22from Tkconstants import *
23tk = Tkinter.Tk()
24frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25frame.pack(fill=BOTH,expand=1)
26label = Tkinter.Label(frame, text="Hello, World")
27label.pack(fill=X, expand=1)
28button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
29button.pack(side=BOTTOM)
30tk.mainloop()
31"""
Guido van Rossum2dcf5291994-07-06 09:23:20 +000032
Guido van Rossum37dcab11996-05-16 16:00:19 +000033__version__ = "$Revision$"
34
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import sys
36if sys.platform == "win32":
Fredrik Lundh06d28152000-08-09 18:03:12 +000037 import FixTk # Attempt to configure Tcl/Tk without requiring PATH
Guido van Rossumf8d579c1999-01-04 18:06:45 +000038import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000039tkinter = _tkinter # b/w compat for export
40TclError = _tkinter.TclError
Guido van Rossum7e9394a1995-03-17 16:21:33 +000041from types import *
Guido van Rossuma5773dd1995-09-07 19:22:00 +000042from Tkconstants import *
Guido van Rossumf0c891a1998-04-29 21:43:36 +000043try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000044 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000045except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000046 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000047
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000048wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000049
Eric S. Raymondfc170b12001-02-09 11:51:27 +000050TkVersion = float(_tkinter.TK_VERSION)
51TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000052
Guido van Rossumd6615ab1997-08-05 02:35:01 +000053READABLE = _tkinter.READABLE
54WRITABLE = _tkinter.WRITABLE
55EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000056
57# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
58try: _tkinter.createfilehandler
59except AttributeError: _tkinter.createfilehandler = None
60try: _tkinter.deletefilehandler
61except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000062
63
Guido van Rossum2dcf5291994-07-06 09:23:20 +000064def _flatten(tuple):
Fredrik Lundh06d28152000-08-09 18:03:12 +000065 """Internal function."""
66 res = ()
67 for item in tuple:
68 if type(item) in (TupleType, ListType):
69 res = res + _flatten(item)
70 elif item is not None:
71 res = res + (item,)
72 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000073
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000074try: _flatten = _tkinter._flatten
75except AttributeError: pass
76
Guido van Rossum2dcf5291994-07-06 09:23:20 +000077def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000078 """Internal function."""
79 if type(cnfs) is DictionaryType:
80 return cnfs
81 elif type(cnfs) in (NoneType, StringType):
82 return cnfs
83 else:
84 cnf = {}
85 for c in _flatten(cnfs):
86 try:
87 cnf.update(c)
88 except (AttributeError, TypeError), msg:
89 print "_cnfmerge: fallback due to:", msg
90 for k, v in c.items():
91 cnf[k] = v
92 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000093
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000094try: _cnfmerge = _tkinter._cnfmerge
95except AttributeError: pass
96
Guido van Rossum2dcf5291994-07-06 09:23:20 +000097class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000099
Fredrik Lundh06d28152000-08-09 18:03:12 +0000100 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000101
Fredrik Lundh06d28152000-08-09 18:03:12 +0000102 KeyPress, KeyRelease - for keyboard events
103 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
104 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
105 Colormap, Gravity, Reparent, Property, Destroy, Activate,
106 Deactivate - for window events.
107
108 If a callback function for one of these events is registered
109 using bind, bind_all, bind_class, or tag_bind, the callback is
110 called with an Event as first argument. It will have the
111 following attributes (in braces are the event types for which
112 the attribute is valid):
113
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000114 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000115 num - mouse button pressed (ButtonPress, ButtonRelease)
116 focus - whether the window has the focus (Enter, Leave)
117 height - height of the exposed window (Configure, Expose)
118 width - width of the exposed window (Configure, Expose)
119 keycode - keycode of the pressed key (KeyPress, KeyRelease)
120 state - state of the event as a number (ButtonPress, ButtonRelease,
121 Enter, KeyPress, KeyRelease,
122 Leave, Motion)
123 state - state as a string (Visibility)
124 time - when the event occurred
125 x - x-position of the mouse
126 y - y-position of the mouse
127 x_root - x-position of the mouse on the screen
128 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
129 y_root - y-position of the mouse on the screen
130 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
131 char - pressed character (KeyPress, KeyRelease)
132 send_event - see X/Windows documentation
133 keysym - keysym of the the event as a string (KeyPress, KeyRelease)
134 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
135 type - type of the event as a number
136 widget - widget in which the event occurred
137 delta - delta of wheel movement (MouseWheel)
138 """
139 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000140
Guido van Rossumc4570481998-03-20 20:45:49 +0000141_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000142_default_root = None
143
Guido van Rossumc4570481998-03-20 20:45:49 +0000144def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000145 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000146
Fredrik Lundh06d28152000-08-09 18:03:12 +0000147 Call this function to inhibit that the first instance of
148 Tk is used for windows without an explicit parent window.
149 """
150 global _support_default_root
151 _support_default_root = 0
152 global _default_root
153 _default_root = None
154 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000155
Guido van Rossum45853db1994-06-20 12:19:19 +0000156def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000157 """Internal function."""
158 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000159
Guido van Rossum97aeca11994-07-07 13:12:12 +0000160def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000161 """Internal function. Calling it will throw the exception SystemExit."""
162 raise SystemExit, code
Guido van Rossum97aeca11994-07-07 13:12:12 +0000163
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000164_varnum = 0
165class Variable:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000166 """Class to define value holders for e.g. buttons.
167
168 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
169 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000170 _default = ""
171 def __init__(self, master=None):
172 """Construct a variable with an optional MASTER as master widget.
173 The variable is named PY_VAR_number in Tcl.
174 """
175 global _varnum
176 if not master:
177 master = _default_root
178 self._master = master
179 self._tk = master.tk
Walter Dörwald70a6b492004-02-12 17:35:32 +0000180 self._name = 'PY_VAR' + repr(_varnum)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000181 _varnum = _varnum + 1
182 self.set(self._default)
183 def __del__(self):
184 """Unset the variable in Tcl."""
185 self._tk.globalunsetvar(self._name)
186 def __str__(self):
187 """Return the name of the variable in Tcl."""
188 return self._name
189 def set(self, value):
190 """Set the variable to VALUE."""
191 return self._tk.globalsetvar(self._name, value)
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000192 def get(self):
193 """Return value of variable."""
194 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000195 def trace_variable(self, mode, callback):
196 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000197
Fredrik Lundh06d28152000-08-09 18:03:12 +0000198 MODE is one of "r", "w", "u" for read, write, undefine.
199 CALLBACK must be a function which is called when
200 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000201
Fredrik Lundh06d28152000-08-09 18:03:12 +0000202 Return the name of the callback.
203 """
204 cbname = self._master._register(callback)
205 self._tk.call("trace", "variable", self._name, mode, cbname)
206 return cbname
207 trace = trace_variable
208 def trace_vdelete(self, mode, cbname):
209 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000210
Fredrik Lundh06d28152000-08-09 18:03:12 +0000211 MODE is one of "r", "w", "u" for read, write, undefine.
212 CBNAME is the name of the callback returned from trace_variable or trace.
213 """
214 self._tk.call("trace", "vdelete", self._name, mode, cbname)
215 self._master.deletecommand(cbname)
216 def trace_vinfo(self):
217 """Return all trace callback information."""
218 return map(self._tk.split, self._tk.splitlist(
219 self._tk.call("trace", "vinfo", self._name)))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000220
221class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000222 """Value holder for strings variables."""
223 _default = ""
224 def __init__(self, master=None):
225 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000226
Fredrik Lundh06d28152000-08-09 18:03:12 +0000227 MASTER can be given as master widget."""
228 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000229
Fredrik Lundh06d28152000-08-09 18:03:12 +0000230 def get(self):
231 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000232 value = self._tk.globalgetvar(self._name)
233 if isinstance(value, basestring):
234 return value
235 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000236
237class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000238 """Value holder for integer variables."""
239 _default = 0
240 def __init__(self, master=None):
241 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000242
Fredrik Lundh06d28152000-08-09 18:03:12 +0000243 MASTER can be given as master widget."""
244 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000245
Martin v. Löwis70c3dda2003-01-22 09:17:38 +0000246 def set(self, value):
247 """Set the variable to value, converting booleans to integers."""
248 if isinstance(value, bool):
249 value = int(value)
250 return Variable.set(self, value)
251
Fredrik Lundh06d28152000-08-09 18:03:12 +0000252 def get(self):
253 """Return the value of the variable as an integer."""
254 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000255
256class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000257 """Value holder for float variables."""
258 _default = 0.0
259 def __init__(self, master=None):
260 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000261
Fredrik Lundh06d28152000-08-09 18:03:12 +0000262 MASTER can be given as a master widget."""
263 Variable.__init__(self, master)
264
265 def get(self):
266 """Return the value of the variable as a float."""
267 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000268
269class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000270 """Value holder for boolean variables."""
271 _default = "false"
272 def __init__(self, master=None):
273 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000274
Fredrik Lundh06d28152000-08-09 18:03:12 +0000275 MASTER can be given as a master widget."""
276 Variable.__init__(self, master)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000277
Fredrik Lundh06d28152000-08-09 18:03:12 +0000278 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000279 """Return the value of the variable as a bool."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000280 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000281
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000282def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000283 """Run the main loop of Tcl."""
284 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000285
Guido van Rossum0132f691998-04-30 17:50:36 +0000286getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000287
Guido van Rossum0132f691998-04-30 17:50:36 +0000288getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000289
290def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000291 """Convert true and false to integer values 1 and 0."""
292 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000293
Guido van Rossum368e06b1997-11-07 20:38:49 +0000294# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000295class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000296 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000297
Fredrik Lundh06d28152000-08-09 18:03:12 +0000298 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000299
Fredrik Lundh06d28152000-08-09 18:03:12 +0000300 # XXX font command?
301 _tclCommands = None
302 def destroy(self):
303 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000304
Fredrik Lundh06d28152000-08-09 18:03:12 +0000305 Delete all Tcl commands created for
306 this widget in the Tcl interpreter."""
307 if self._tclCommands is not None:
308 for name in self._tclCommands:
309 #print '- Tkinter: deleted command', name
310 self.tk.deletecommand(name)
311 self._tclCommands = None
312 def deletecommand(self, name):
313 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000314
Fredrik Lundh06d28152000-08-09 18:03:12 +0000315 Delete the Tcl command provided in NAME."""
316 #print '- Tkinter: deleted command', name
317 self.tk.deletecommand(name)
318 try:
319 self._tclCommands.remove(name)
320 except ValueError:
321 pass
322 def tk_strictMotif(self, boolean=None):
323 """Set Tcl internal variable, whether the look and feel
324 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000325
Fredrik Lundh06d28152000-08-09 18:03:12 +0000326 A parameter of 1 means adhere to Motif (e.g. no color
327 change if mouse passes over slider).
328 Returns the set value."""
329 return self.tk.getboolean(self.tk.call(
330 'set', 'tk_strictMotif', boolean))
331 def tk_bisque(self):
332 """Change the color scheme to light brown as used in Tk 3.6 and before."""
333 self.tk.call('tk_bisque')
334 def tk_setPalette(self, *args, **kw):
335 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000336
Fredrik Lundh06d28152000-08-09 18:03:12 +0000337 A single color as argument will cause that all colors of Tk
338 widget elements are derived from this.
339 Alternatively several keyword parameters and its associated
340 colors can be given. The following keywords are valid:
341 activeBackground, foreground, selectColor,
342 activeForeground, highlightBackground, selectBackground,
343 background, highlightColor, selectForeground,
344 disabledForeground, insertBackground, troughColor."""
345 self.tk.call(('tk_setPalette',)
346 + _flatten(args) + _flatten(kw.items()))
347 def tk_menuBar(self, *args):
348 """Do not use. Needed in Tk 3.6 and earlier."""
349 pass # obsolete since Tk 4.0
350 def wait_variable(self, name='PY_VAR'):
351 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000352
Fredrik Lundh06d28152000-08-09 18:03:12 +0000353 A parameter of type IntVar, StringVar, DoubleVar or
354 BooleanVar must be given."""
355 self.tk.call('tkwait', 'variable', name)
356 waitvar = wait_variable # XXX b/w compat
357 def wait_window(self, window=None):
358 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000359
Fredrik Lundh06d28152000-08-09 18:03:12 +0000360 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000361 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000362 window = self
363 self.tk.call('tkwait', 'window', window._w)
364 def wait_visibility(self, window=None):
365 """Wait until the visibility of a WIDGET changes
366 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000367
Fredrik Lundh06d28152000-08-09 18:03:12 +0000368 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000369 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000370 window = self
371 self.tk.call('tkwait', 'visibility', window._w)
372 def setvar(self, name='PY_VAR', value='1'):
373 """Set Tcl variable NAME to VALUE."""
374 self.tk.setvar(name, value)
375 def getvar(self, name='PY_VAR'):
376 """Return value of Tcl variable NAME."""
377 return self.tk.getvar(name)
378 getint = int
379 getdouble = float
380 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000381 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000382 return self.tk.getboolean(s)
383 def focus_set(self):
384 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000385
Fredrik Lundh06d28152000-08-09 18:03:12 +0000386 If the application currently does not have the focus
387 this widget will get the focus if the application gets
388 the focus through the window manager."""
389 self.tk.call('focus', self._w)
390 focus = focus_set # XXX b/w compat?
391 def focus_force(self):
392 """Direct input focus to this widget even if the
393 application does not have the focus. Use with
394 caution!"""
395 self.tk.call('focus', '-force', self._w)
396 def focus_get(self):
397 """Return the widget which has currently the focus in the
398 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000399
Fredrik Lundh06d28152000-08-09 18:03:12 +0000400 Use focus_displayof to allow working with several
401 displays. Return None if application does not have
402 the focus."""
403 name = self.tk.call('focus')
404 if name == 'none' or not name: return None
405 return self._nametowidget(name)
406 def focus_displayof(self):
407 """Return the widget which has currently the focus on the
408 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000409
Fredrik Lundh06d28152000-08-09 18:03:12 +0000410 Return None if the application does not have the focus."""
411 name = self.tk.call('focus', '-displayof', self._w)
412 if name == 'none' or not name: return None
413 return self._nametowidget(name)
414 def focus_lastfor(self):
415 """Return the widget which would have the focus if top level
416 for this widget gets the focus from the window manager."""
417 name = self.tk.call('focus', '-lastfor', self._w)
418 if name == 'none' or not name: return None
419 return self._nametowidget(name)
420 def tk_focusFollowsMouse(self):
421 """The widget under mouse will get automatically focus. Can not
422 be disabled easily."""
423 self.tk.call('tk_focusFollowsMouse')
424 def tk_focusNext(self):
425 """Return the next widget in the focus order which follows
426 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000427
Fredrik Lundh06d28152000-08-09 18:03:12 +0000428 The focus order first goes to the next child, then to
429 the children of the child recursively and then to the
430 next sibling which is higher in the stacking order. A
431 widget is omitted if it has the takefocus resource set
432 to 0."""
433 name = self.tk.call('tk_focusNext', self._w)
434 if not name: return None
435 return self._nametowidget(name)
436 def tk_focusPrev(self):
437 """Return previous widget in the focus order. See tk_focusNext for details."""
438 name = self.tk.call('tk_focusPrev', self._w)
439 if not name: return None
440 return self._nametowidget(name)
441 def after(self, ms, func=None, *args):
442 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000443
Fredrik Lundh06d28152000-08-09 18:03:12 +0000444 MS specifies the time in milliseconds. FUNC gives the
445 function which shall be called. Additional parameters
446 are given as parameters to the function call. Return
447 identifier to cancel scheduling with after_cancel."""
448 if not func:
449 # I'd rather use time.sleep(ms*0.001)
450 self.tk.call('after', ms)
451 else:
452 # XXX Disgusting hack to clean up after calling func
453 tmp = []
454 def callit(func=func, args=args, self=self, tmp=tmp):
455 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000456 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000457 finally:
458 try:
459 self.deletecommand(tmp[0])
460 except TclError:
461 pass
462 name = self._register(callit)
463 tmp.append(name)
464 return self.tk.call('after', ms, name)
465 def after_idle(self, func, *args):
466 """Call FUNC once if the Tcl main loop has no event to
467 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000468
Fredrik Lundh06d28152000-08-09 18:03:12 +0000469 Return an identifier to cancel the scheduling with
470 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000471 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000472 def after_cancel(self, id):
473 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000474
Fredrik Lundh06d28152000-08-09 18:03:12 +0000475 Identifier returned by after or after_idle must be
476 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000477 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000478 data = self.tk.call('after', 'info', id)
479 # In Tk 8.3, splitlist returns: (script, type)
480 # In Tk 8.4, splitlist may return (script, type) or (script,)
481 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000482 self.deletecommand(script)
483 except TclError:
484 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000485 self.tk.call('after', 'cancel', id)
486 def bell(self, displayof=0):
487 """Ring a display's bell."""
488 self.tk.call(('bell',) + self._displayof(displayof))
489 # Clipboard handling:
490 def clipboard_clear(self, **kw):
491 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000492
Fredrik Lundh06d28152000-08-09 18:03:12 +0000493 A widget specified for the optional displayof keyword
494 argument specifies the target display."""
495 if not kw.has_key('displayof'): kw['displayof'] = self._w
496 self.tk.call(('clipboard', 'clear') + self._options(kw))
497 def clipboard_append(self, string, **kw):
498 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000499
Fredrik Lundh06d28152000-08-09 18:03:12 +0000500 A widget specified at the optional displayof keyword
501 argument specifies the target display. The clipboard
502 can be retrieved with selection_get."""
503 if not kw.has_key('displayof'): kw['displayof'] = self._w
504 self.tk.call(('clipboard', 'append') + self._options(kw)
505 + ('--', string))
506 # XXX grab current w/o window argument
507 def grab_current(self):
508 """Return widget which has currently the grab in this application
509 or None."""
510 name = self.tk.call('grab', 'current', self._w)
511 if not name: return None
512 return self._nametowidget(name)
513 def grab_release(self):
514 """Release grab for this widget if currently set."""
515 self.tk.call('grab', 'release', self._w)
516 def grab_set(self):
517 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000518
Fredrik Lundh06d28152000-08-09 18:03:12 +0000519 A grab directs all events to this and descendant
520 widgets in the application."""
521 self.tk.call('grab', 'set', self._w)
522 def grab_set_global(self):
523 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000524
Fredrik Lundh06d28152000-08-09 18:03:12 +0000525 A global grab directs all events to this and
526 descendant widgets on the display. Use with caution -
527 other applications do not get events anymore."""
528 self.tk.call('grab', 'set', '-global', self._w)
529 def grab_status(self):
530 """Return None, "local" or "global" if this widget has
531 no, a local or a global grab."""
532 status = self.tk.call('grab', 'status', self._w)
533 if status == 'none': status = None
534 return status
535 def lower(self, belowThis=None):
536 """Lower this widget in the stacking order."""
537 self.tk.call('lower', self._w, belowThis)
538 def option_add(self, pattern, value, priority = None):
539 """Set a VALUE (second parameter) for an option
540 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000541
Fredrik Lundh06d28152000-08-09 18:03:12 +0000542 An optional third parameter gives the numeric priority
543 (defaults to 80)."""
544 self.tk.call('option', 'add', pattern, value, priority)
545 def option_clear(self):
546 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000547
Fredrik Lundh06d28152000-08-09 18:03:12 +0000548 It will be reloaded if option_add is called."""
549 self.tk.call('option', 'clear')
550 def option_get(self, name, className):
551 """Return the value for an option NAME for this widget
552 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000553
Fredrik Lundh06d28152000-08-09 18:03:12 +0000554 Values with higher priority override lower values."""
555 return self.tk.call('option', 'get', self._w, name, className)
556 def option_readfile(self, fileName, priority = None):
557 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000558
Fredrik Lundh06d28152000-08-09 18:03:12 +0000559 An optional second parameter gives the numeric
560 priority."""
561 self.tk.call('option', 'readfile', fileName, priority)
562 def selection_clear(self, **kw):
563 """Clear the current X selection."""
564 if not kw.has_key('displayof'): kw['displayof'] = self._w
565 self.tk.call(('selection', 'clear') + self._options(kw))
566 def selection_get(self, **kw):
567 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000568
Fredrik Lundh06d28152000-08-09 18:03:12 +0000569 A keyword parameter selection specifies the name of
570 the selection and defaults to PRIMARY. A keyword
571 parameter displayof specifies a widget on the display
572 to use."""
573 if not kw.has_key('displayof'): kw['displayof'] = self._w
574 return self.tk.call(('selection', 'get') + self._options(kw))
575 def selection_handle(self, command, **kw):
576 """Specify a function COMMAND to call if the X
577 selection owned by this widget is queried by another
578 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000579
Fredrik Lundh06d28152000-08-09 18:03:12 +0000580 This function must return the contents of the
581 selection. The function will be called with the
582 arguments OFFSET and LENGTH which allows the chunking
583 of very long selections. The following keyword
584 parameters can be provided:
585 selection - name of the selection (default PRIMARY),
586 type - type of the selection (e.g. STRING, FILE_NAME)."""
587 name = self._register(command)
588 self.tk.call(('selection', 'handle') + self._options(kw)
589 + (self._w, name))
590 def selection_own(self, **kw):
591 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000592
Fredrik Lundh06d28152000-08-09 18:03:12 +0000593 A keyword parameter selection specifies the name of
594 the selection (default PRIMARY)."""
595 self.tk.call(('selection', 'own') +
596 self._options(kw) + (self._w,))
597 def selection_own_get(self, **kw):
598 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000599
Fredrik Lundh06d28152000-08-09 18:03:12 +0000600 The following keyword parameter can
601 be provided:
602 selection - name of the selection (default PRIMARY),
603 type - type of the selection (e.g. STRING, FILE_NAME)."""
604 if not kw.has_key('displayof'): kw['displayof'] = self._w
605 name = self.tk.call(('selection', 'own') + self._options(kw))
606 if not name: return None
607 return self._nametowidget(name)
608 def send(self, interp, cmd, *args):
609 """Send Tcl command CMD to different interpreter INTERP to be executed."""
610 return self.tk.call(('send', interp, cmd) + args)
611 def lower(self, belowThis=None):
612 """Lower this widget in the stacking order."""
613 self.tk.call('lower', self._w, belowThis)
614 def tkraise(self, aboveThis=None):
615 """Raise this widget in the stacking order."""
616 self.tk.call('raise', self._w, aboveThis)
617 lift = tkraise
618 def colormodel(self, value=None):
619 """Useless. Not implemented in Tk."""
620 return self.tk.call('tk', 'colormodel', self._w, value)
621 def winfo_atom(self, name, displayof=0):
622 """Return integer which represents atom NAME."""
623 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
624 return getint(self.tk.call(args))
625 def winfo_atomname(self, id, displayof=0):
626 """Return name of atom with identifier ID."""
627 args = ('winfo', 'atomname') \
628 + self._displayof(displayof) + (id,)
629 return self.tk.call(args)
630 def winfo_cells(self):
631 """Return number of cells in the colormap for this widget."""
632 return getint(
633 self.tk.call('winfo', 'cells', self._w))
634 def winfo_children(self):
635 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000636 result = []
637 for child in self.tk.splitlist(
638 self.tk.call('winfo', 'children', self._w)):
639 try:
640 # Tcl sometimes returns extra windows, e.g. for
641 # menus; those need to be skipped
642 result.append(self._nametowidget(child))
643 except KeyError:
644 pass
645 return result
646
Fredrik Lundh06d28152000-08-09 18:03:12 +0000647 def winfo_class(self):
648 """Return window class name of this widget."""
649 return self.tk.call('winfo', 'class', self._w)
650 def winfo_colormapfull(self):
651 """Return true if at the last color request the colormap was full."""
652 return self.tk.getboolean(
653 self.tk.call('winfo', 'colormapfull', self._w))
654 def winfo_containing(self, rootX, rootY, displayof=0):
655 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
656 args = ('winfo', 'containing') \
657 + self._displayof(displayof) + (rootX, rootY)
658 name = self.tk.call(args)
659 if not name: return None
660 return self._nametowidget(name)
661 def winfo_depth(self):
662 """Return the number of bits per pixel."""
663 return getint(self.tk.call('winfo', 'depth', self._w))
664 def winfo_exists(self):
665 """Return true if this widget exists."""
666 return getint(
667 self.tk.call('winfo', 'exists', self._w))
668 def winfo_fpixels(self, number):
669 """Return the number of pixels for the given distance NUMBER
670 (e.g. "3c") as float."""
671 return getdouble(self.tk.call(
672 'winfo', 'fpixels', self._w, number))
673 def winfo_geometry(self):
674 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
675 return self.tk.call('winfo', 'geometry', self._w)
676 def winfo_height(self):
677 """Return height of this widget."""
678 return getint(
679 self.tk.call('winfo', 'height', self._w))
680 def winfo_id(self):
681 """Return identifier ID for this widget."""
682 return self.tk.getint(
683 self.tk.call('winfo', 'id', self._w))
684 def winfo_interps(self, displayof=0):
685 """Return the name of all Tcl interpreters for this display."""
686 args = ('winfo', 'interps') + self._displayof(displayof)
687 return self.tk.splitlist(self.tk.call(args))
688 def winfo_ismapped(self):
689 """Return true if this widget is mapped."""
690 return getint(
691 self.tk.call('winfo', 'ismapped', self._w))
692 def winfo_manager(self):
693 """Return the window mananger name for this widget."""
694 return self.tk.call('winfo', 'manager', self._w)
695 def winfo_name(self):
696 """Return the name of this widget."""
697 return self.tk.call('winfo', 'name', self._w)
698 def winfo_parent(self):
699 """Return the name of the parent of this widget."""
700 return self.tk.call('winfo', 'parent', self._w)
701 def winfo_pathname(self, id, displayof=0):
702 """Return the pathname of the widget given by ID."""
703 args = ('winfo', 'pathname') \
704 + self._displayof(displayof) + (id,)
705 return self.tk.call(args)
706 def winfo_pixels(self, number):
707 """Rounded integer value of winfo_fpixels."""
708 return getint(
709 self.tk.call('winfo', 'pixels', self._w, number))
710 def winfo_pointerx(self):
711 """Return the x coordinate of the pointer on the root window."""
712 return getint(
713 self.tk.call('winfo', 'pointerx', self._w))
714 def winfo_pointerxy(self):
715 """Return a tuple of x and y coordinates of the pointer on the root window."""
716 return self._getints(
717 self.tk.call('winfo', 'pointerxy', self._w))
718 def winfo_pointery(self):
719 """Return the y coordinate of the pointer on the root window."""
720 return getint(
721 self.tk.call('winfo', 'pointery', self._w))
722 def winfo_reqheight(self):
723 """Return requested height of this widget."""
724 return getint(
725 self.tk.call('winfo', 'reqheight', self._w))
726 def winfo_reqwidth(self):
727 """Return requested width of this widget."""
728 return getint(
729 self.tk.call('winfo', 'reqwidth', self._w))
730 def winfo_rgb(self, color):
731 """Return tuple of decimal values for red, green, blue for
732 COLOR in this widget."""
733 return self._getints(
734 self.tk.call('winfo', 'rgb', self._w, color))
735 def winfo_rootx(self):
736 """Return x coordinate of upper left corner of this widget on the
737 root window."""
738 return getint(
739 self.tk.call('winfo', 'rootx', self._w))
740 def winfo_rooty(self):
741 """Return y coordinate of upper left corner of this widget on the
742 root window."""
743 return getint(
744 self.tk.call('winfo', 'rooty', self._w))
745 def winfo_screen(self):
746 """Return the screen name of this widget."""
747 return self.tk.call('winfo', 'screen', self._w)
748 def winfo_screencells(self):
749 """Return the number of the cells in the colormap of the screen
750 of this widget."""
751 return getint(
752 self.tk.call('winfo', 'screencells', self._w))
753 def winfo_screendepth(self):
754 """Return the number of bits per pixel of the root window of the
755 screen of this widget."""
756 return getint(
757 self.tk.call('winfo', 'screendepth', self._w))
758 def winfo_screenheight(self):
759 """Return the number of pixels of the height of the screen of this widget
760 in pixel."""
761 return getint(
762 self.tk.call('winfo', 'screenheight', self._w))
763 def winfo_screenmmheight(self):
764 """Return the number of pixels of the height of the screen of
765 this widget in mm."""
766 return getint(
767 self.tk.call('winfo', 'screenmmheight', self._w))
768 def winfo_screenmmwidth(self):
769 """Return the number of pixels of the width of the screen of
770 this widget in mm."""
771 return getint(
772 self.tk.call('winfo', 'screenmmwidth', self._w))
773 def winfo_screenvisual(self):
774 """Return one of the strings directcolor, grayscale, pseudocolor,
775 staticcolor, staticgray, or truecolor for the default
776 colormodel of this screen."""
777 return self.tk.call('winfo', 'screenvisual', self._w)
778 def winfo_screenwidth(self):
779 """Return the number of pixels of the width of the screen of
780 this widget in pixel."""
781 return getint(
782 self.tk.call('winfo', 'screenwidth', self._w))
783 def winfo_server(self):
784 """Return information of the X-Server of the screen of this widget in
785 the form "XmajorRminor vendor vendorVersion"."""
786 return self.tk.call('winfo', 'server', self._w)
787 def winfo_toplevel(self):
788 """Return the toplevel widget of this widget."""
789 return self._nametowidget(self.tk.call(
790 'winfo', 'toplevel', self._w))
791 def winfo_viewable(self):
792 """Return true if the widget and all its higher ancestors are mapped."""
793 return getint(
794 self.tk.call('winfo', 'viewable', self._w))
795 def winfo_visual(self):
796 """Return one of the strings directcolor, grayscale, pseudocolor,
797 staticcolor, staticgray, or truecolor for the
798 colormodel of this widget."""
799 return self.tk.call('winfo', 'visual', self._w)
800 def winfo_visualid(self):
801 """Return the X identifier for the visual for this widget."""
802 return self.tk.call('winfo', 'visualid', self._w)
803 def winfo_visualsavailable(self, includeids=0):
804 """Return a list of all visuals available for the screen
805 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000806
Fredrik Lundh06d28152000-08-09 18:03:12 +0000807 Each item in the list consists of a visual name (see winfo_visual), a
808 depth and if INCLUDEIDS=1 is given also the X identifier."""
809 data = self.tk.split(
810 self.tk.call('winfo', 'visualsavailable', self._w,
811 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000812 if type(data) is StringType:
813 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000814 return map(self.__winfo_parseitem, data)
815 def __winfo_parseitem(self, t):
816 """Internal function."""
817 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
818 def __winfo_getint(self, x):
819 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000820 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000821 def winfo_vrootheight(self):
822 """Return the height of the virtual root window associated with this
823 widget in pixels. If there is no virtual root window return the
824 height of the screen."""
825 return getint(
826 self.tk.call('winfo', 'vrootheight', self._w))
827 def winfo_vrootwidth(self):
828 """Return the width of the virtual root window associated with this
829 widget in pixel. If there is no virtual root window return the
830 width of the screen."""
831 return getint(
832 self.tk.call('winfo', 'vrootwidth', self._w))
833 def winfo_vrootx(self):
834 """Return the x offset of the virtual root relative to the root
835 window of the screen of this widget."""
836 return getint(
837 self.tk.call('winfo', 'vrootx', self._w))
838 def winfo_vrooty(self):
839 """Return the y offset of the virtual root relative to the root
840 window of the screen of this widget."""
841 return getint(
842 self.tk.call('winfo', 'vrooty', self._w))
843 def winfo_width(self):
844 """Return the width of this widget."""
845 return getint(
846 self.tk.call('winfo', 'width', self._w))
847 def winfo_x(self):
848 """Return the x coordinate of the upper left corner of this widget
849 in the parent."""
850 return getint(
851 self.tk.call('winfo', 'x', self._w))
852 def winfo_y(self):
853 """Return the y coordinate of the upper left corner of this widget
854 in the parent."""
855 return getint(
856 self.tk.call('winfo', 'y', self._w))
857 def update(self):
858 """Enter event loop until all pending events have been processed by Tcl."""
859 self.tk.call('update')
860 def update_idletasks(self):
861 """Enter event loop until all idle callbacks have been called. This
862 will update the display of windows but not process events caused by
863 the user."""
864 self.tk.call('update', 'idletasks')
865 def bindtags(self, tagList=None):
866 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000867
Fredrik Lundh06d28152000-08-09 18:03:12 +0000868 With no argument return the list of all bindtags associated with
869 this widget. With a list of strings as argument the bindtags are
870 set to this list. The bindtags determine in which order events are
871 processed (see bind)."""
872 if tagList is None:
873 return self.tk.splitlist(
874 self.tk.call('bindtags', self._w))
875 else:
876 self.tk.call('bindtags', self._w, tagList)
877 def _bind(self, what, sequence, func, add, needcleanup=1):
878 """Internal function."""
879 if type(func) is StringType:
880 self.tk.call(what + (sequence, func))
881 elif func:
882 funcid = self._register(func, self._substitute,
883 needcleanup)
884 cmd = ('%sif {"[%s %s]" == "break"} break\n'
885 %
886 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000887 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000888 self.tk.call(what + (sequence, cmd))
889 return funcid
890 elif sequence:
891 return self.tk.call(what + (sequence,))
892 else:
893 return self.tk.splitlist(self.tk.call(what))
894 def bind(self, sequence=None, func=None, add=None):
895 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000896
Fredrik Lundh06d28152000-08-09 18:03:12 +0000897 SEQUENCE is a string of concatenated event
898 patterns. An event pattern is of the form
899 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
900 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
901 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
902 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
903 Mod1, M1. TYPE is one of Activate, Enter, Map,
904 ButtonPress, Button, Expose, Motion, ButtonRelease
905 FocusIn, MouseWheel, Circulate, FocusOut, Property,
906 Colormap, Gravity Reparent, Configure, KeyPress, Key,
907 Unmap, Deactivate, KeyRelease Visibility, Destroy,
908 Leave and DETAIL is the button number for ButtonPress,
909 ButtonRelease and DETAIL is the Keysym for KeyPress and
910 KeyRelease. Examples are
911 <Control-Button-1> for pressing Control and mouse button 1 or
912 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
913 An event pattern can also be a virtual event of the form
914 <<AString>> where AString can be arbitrary. This
915 event can be generated by event_generate.
916 If events are concatenated they must appear shortly
917 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000918
Fredrik Lundh06d28152000-08-09 18:03:12 +0000919 FUNC will be called if the event sequence occurs with an
920 instance of Event as argument. If the return value of FUNC is
921 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000922
Fredrik Lundh06d28152000-08-09 18:03:12 +0000923 An additional boolean parameter ADD specifies whether FUNC will
924 be called additionally to the other bound function or whether
925 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000926
Fredrik Lundh06d28152000-08-09 18:03:12 +0000927 Bind will return an identifier to allow deletion of the bound function with
928 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000929
Fredrik Lundh06d28152000-08-09 18:03:12 +0000930 If FUNC or SEQUENCE is omitted the bound function or list
931 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000932
Fredrik Lundh06d28152000-08-09 18:03:12 +0000933 return self._bind(('bind', self._w), sequence, func, add)
934 def unbind(self, sequence, funcid=None):
935 """Unbind for this widget for event SEQUENCE the
936 function identified with FUNCID."""
937 self.tk.call('bind', self._w, sequence, '')
938 if funcid:
939 self.deletecommand(funcid)
940 def bind_all(self, sequence=None, func=None, add=None):
941 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
942 An additional boolean parameter ADD specifies whether FUNC will
943 be called additionally to the other bound function or whether
944 it will replace the previous function. See bind for the return value."""
945 return self._bind(('bind', 'all'), sequence, func, add, 0)
946 def unbind_all(self, sequence):
947 """Unbind for all widgets for event SEQUENCE all functions."""
948 self.tk.call('bind', 'all' , sequence, '')
949 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000950
Fredrik Lundh06d28152000-08-09 18:03:12 +0000951 """Bind to widgets with bindtag CLASSNAME at event
952 SEQUENCE a call of function FUNC. An additional
953 boolean parameter ADD specifies whether FUNC will be
954 called additionally to the other bound function or
955 whether it will replace the previous function. See bind for
956 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000957
Fredrik Lundh06d28152000-08-09 18:03:12 +0000958 return self._bind(('bind', className), sequence, func, add, 0)
959 def unbind_class(self, className, sequence):
960 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
961 all functions."""
962 self.tk.call('bind', className , sequence, '')
963 def mainloop(self, n=0):
964 """Call the mainloop of Tk."""
965 self.tk.mainloop(n)
966 def quit(self):
967 """Quit the Tcl interpreter. All widgets will be destroyed."""
968 self.tk.quit()
969 def _getints(self, string):
970 """Internal function."""
971 if string:
972 return tuple(map(getint, self.tk.splitlist(string)))
973 def _getdoubles(self, string):
974 """Internal function."""
975 if string:
976 return tuple(map(getdouble, self.tk.splitlist(string)))
977 def _getboolean(self, string):
978 """Internal function."""
979 if string:
980 return self.tk.getboolean(string)
981 def _displayof(self, displayof):
982 """Internal function."""
983 if displayof:
984 return ('-displayof', displayof)
985 if displayof is None:
986 return ('-displayof', self._w)
987 return ()
988 def _options(self, cnf, kw = None):
989 """Internal function."""
990 if kw:
991 cnf = _cnfmerge((cnf, kw))
992 else:
993 cnf = _cnfmerge(cnf)
994 res = ()
995 for k, v in cnf.items():
996 if v is not None:
997 if k[-1] == '_': k = k[:-1]
998 if callable(v):
999 v = self._register(v)
1000 res = res + ('-'+k, v)
1001 return res
1002 def nametowidget(self, name):
1003 """Return the Tkinter instance of a widget identified by
1004 its Tcl name NAME."""
1005 w = self
1006 if name[0] == '.':
1007 w = w._root()
1008 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001009 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +00001010 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001011 if i >= 0:
1012 name, tail = name[:i], name[i+1:]
1013 else:
1014 tail = ''
1015 w = w.children[name]
1016 name = tail
1017 return w
1018 _nametowidget = nametowidget
1019 def _register(self, func, subst=None, needcleanup=1):
1020 """Return a newly created Tcl function. If this
1021 function is called, the Python function FUNC will
1022 be executed. An optional function SUBST can
1023 be given which will be executed before FUNC."""
1024 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001025 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001026 try:
1027 func = func.im_func
1028 except AttributeError:
1029 pass
1030 try:
1031 name = name + func.__name__
1032 except AttributeError:
1033 pass
1034 self.tk.createcommand(name, f)
1035 if needcleanup:
1036 if self._tclCommands is None:
1037 self._tclCommands = []
1038 self._tclCommands.append(name)
1039 #print '+ Tkinter created command', name
1040 return name
1041 register = _register
1042 def _root(self):
1043 """Internal function."""
1044 w = self
1045 while w.master: w = w.master
1046 return w
1047 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1048 '%s', '%t', '%w', '%x', '%y',
1049 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001050 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001051 def _substitute(self, *args):
1052 """Internal function."""
1053 if len(args) != len(self._subst_format): return args
1054 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001055
Fredrik Lundh06d28152000-08-09 18:03:12 +00001056 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001057 def getint_event(s):
1058 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1059 try:
1060 return int(s)
1061 except ValueError:
1062 return s
1063
Fredrik Lundh06d28152000-08-09 18:03:12 +00001064 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1065 # Missing: (a, c, d, m, o, v, B, R)
1066 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001067 # serial field: valid vor all events
1068 # number of button: ButtonPress and ButtonRelease events only
1069 # height field: Configure, ConfigureRequest, Create,
1070 # ResizeRequest, and Expose events only
1071 # keycode field: KeyPress and KeyRelease events only
1072 # time field: "valid for events that contain a time field"
1073 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1074 # and Expose events only
1075 # x field: "valid for events that contain a x field"
1076 # y field: "valid for events that contain a y field"
1077 # keysym as decimal: KeyPress and KeyRelease events only
1078 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1079 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001080 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001081 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001082 try: e.focus = getboolean(f)
1083 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001084 e.height = getint_event(h)
1085 e.keycode = getint_event(k)
1086 e.state = getint_event(s)
1087 e.time = getint_event(t)
1088 e.width = getint_event(w)
1089 e.x = getint_event(x)
1090 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001091 e.char = A
1092 try: e.send_event = getboolean(E)
1093 except TclError: pass
1094 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001095 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001096 e.type = T
1097 try:
1098 e.widget = self._nametowidget(W)
1099 except KeyError:
1100 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001101 e.x_root = getint_event(X)
1102 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001103 try:
1104 e.delta = getint(D)
1105 except ValueError:
1106 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001107 return (e,)
1108 def _report_exception(self):
1109 """Internal function."""
1110 import sys
1111 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
1112 root = self._root()
1113 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001114 def _configure(self, cmd, cnf, kw):
1115 """Internal function."""
1116 if kw:
1117 cnf = _cnfmerge((cnf, kw))
1118 elif cnf:
1119 cnf = _cnfmerge(cnf)
1120 if cnf is None:
1121 cnf = {}
1122 for x in self.tk.split(
1123 self.tk.call(_flatten((self._w, cmd)))):
1124 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1125 return cnf
1126 if type(cnf) is StringType:
1127 x = self.tk.split(
1128 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1129 return (x[0][1:],) + x[1:]
1130 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001131 # These used to be defined in Widget:
1132 def configure(self, cnf=None, **kw):
1133 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001134
Fredrik Lundh06d28152000-08-09 18:03:12 +00001135 The values for resources are specified as keyword
1136 arguments. To get an overview about
1137 the allowed keyword arguments call the method keys.
1138 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001139 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001140 config = configure
1141 def cget(self, key):
1142 """Return the resource value for a KEY given as string."""
1143 return self.tk.call(self._w, 'cget', '-' + key)
1144 __getitem__ = cget
1145 def __setitem__(self, key, value):
1146 self.configure({key: value})
1147 def keys(self):
1148 """Return a list of all resource names of this widget."""
1149 return map(lambda x: x[0][1:],
1150 self.tk.split(self.tk.call(self._w, 'configure')))
1151 def __str__(self):
1152 """Return the window path name of this widget."""
1153 return self._w
1154 # Pack methods that apply to the master
1155 _noarg_ = ['_noarg_']
1156 def pack_propagate(self, flag=_noarg_):
1157 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001158
Fredrik Lundh06d28152000-08-09 18:03:12 +00001159 A boolean argument specifies whether the geometry information
1160 of the slaves will determine the size of this widget. If no argument
1161 is given the current setting will be returned.
1162 """
1163 if flag is Misc._noarg_:
1164 return self._getboolean(self.tk.call(
1165 'pack', 'propagate', self._w))
1166 else:
1167 self.tk.call('pack', 'propagate', self._w, flag)
1168 propagate = pack_propagate
1169 def pack_slaves(self):
1170 """Return a list of all slaves of this widget
1171 in its packing order."""
1172 return map(self._nametowidget,
1173 self.tk.splitlist(
1174 self.tk.call('pack', 'slaves', self._w)))
1175 slaves = pack_slaves
1176 # Place method that applies to the master
1177 def place_slaves(self):
1178 """Return a list of all slaves of this widget
1179 in its packing order."""
1180 return map(self._nametowidget,
1181 self.tk.splitlist(
1182 self.tk.call(
1183 'place', 'slaves', self._w)))
1184 # Grid methods that apply to the master
1185 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1186 """Return a tuple of integer coordinates for the bounding
1187 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001188
Fredrik Lundh06d28152000-08-09 18:03:12 +00001189 If COLUMN, ROW is given the bounding box applies from
1190 the cell with row and column 0 to the specified
1191 cell. If COL2 and ROW2 are given the bounding box
1192 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001193
Fredrik Lundh06d28152000-08-09 18:03:12 +00001194 The returned integers specify the offset of the upper left
1195 corner in the master widget and the width and height.
1196 """
1197 args = ('grid', 'bbox', self._w)
1198 if column is not None and row is not None:
1199 args = args + (column, row)
1200 if col2 is not None and row2 is not None:
1201 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001202 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001203
Fredrik Lundh06d28152000-08-09 18:03:12 +00001204 bbox = grid_bbox
1205 def _grid_configure(self, command, index, cnf, kw):
1206 """Internal function."""
1207 if type(cnf) is StringType and not kw:
1208 if cnf[-1:] == '_':
1209 cnf = cnf[:-1]
1210 if cnf[:1] != '-':
1211 cnf = '-'+cnf
1212 options = (cnf,)
1213 else:
1214 options = self._options(cnf, kw)
1215 if not options:
1216 res = self.tk.call('grid',
1217 command, self._w, index)
1218 words = self.tk.splitlist(res)
1219 dict = {}
1220 for i in range(0, len(words), 2):
1221 key = words[i][1:]
1222 value = words[i+1]
1223 if not value:
1224 value = None
1225 elif '.' in value:
1226 value = getdouble(value)
1227 else:
1228 value = getint(value)
1229 dict[key] = value
1230 return dict
1231 res = self.tk.call(
1232 ('grid', command, self._w, index)
1233 + options)
1234 if len(options) == 1:
1235 if not res: return None
1236 # In Tk 7.5, -width can be a float
1237 if '.' in res: return getdouble(res)
1238 return getint(res)
1239 def grid_columnconfigure(self, index, cnf={}, **kw):
1240 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001241
Fredrik Lundh06d28152000-08-09 18:03:12 +00001242 Valid resources are minsize (minimum size of the column),
1243 weight (how much does additional space propagate to this column)
1244 and pad (how much space to let additionally)."""
1245 return self._grid_configure('columnconfigure', index, cnf, kw)
1246 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001247 def grid_location(self, x, y):
1248 """Return a tuple of column and row which identify the cell
1249 at which the pixel at position X and Y inside the master
1250 widget is located."""
1251 return self._getints(
1252 self.tk.call(
1253 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001254 def grid_propagate(self, flag=_noarg_):
1255 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001256
Fredrik Lundh06d28152000-08-09 18:03:12 +00001257 A boolean argument specifies whether the geometry information
1258 of the slaves will determine the size of this widget. If no argument
1259 is given, the current setting will be returned.
1260 """
1261 if flag is Misc._noarg_:
1262 return self._getboolean(self.tk.call(
1263 'grid', 'propagate', self._w))
1264 else:
1265 self.tk.call('grid', 'propagate', self._w, flag)
1266 def grid_rowconfigure(self, index, cnf={}, **kw):
1267 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001268
Fredrik Lundh06d28152000-08-09 18:03:12 +00001269 Valid resources are minsize (minimum size of the row),
1270 weight (how much does additional space propagate to this row)
1271 and pad (how much space to let additionally)."""
1272 return self._grid_configure('rowconfigure', index, cnf, kw)
1273 rowconfigure = grid_rowconfigure
1274 def grid_size(self):
1275 """Return a tuple of the number of column and rows in the grid."""
1276 return self._getints(
1277 self.tk.call('grid', 'size', self._w)) or None
1278 size = grid_size
1279 def grid_slaves(self, row=None, column=None):
1280 """Return a list of all slaves of this widget
1281 in its packing order."""
1282 args = ()
1283 if row is not None:
1284 args = args + ('-row', row)
1285 if column is not None:
1286 args = args + ('-column', column)
1287 return map(self._nametowidget,
1288 self.tk.splitlist(self.tk.call(
1289 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001290
Fredrik Lundh06d28152000-08-09 18:03:12 +00001291 # Support for the "event" command, new in Tk 4.2.
1292 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001293
Fredrik Lundh06d28152000-08-09 18:03:12 +00001294 def event_add(self, virtual, *sequences):
1295 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1296 to an event SEQUENCE such that the virtual event is triggered
1297 whenever SEQUENCE occurs."""
1298 args = ('event', 'add', virtual) + sequences
1299 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001300
Fredrik Lundh06d28152000-08-09 18:03:12 +00001301 def event_delete(self, virtual, *sequences):
1302 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1303 args = ('event', 'delete', virtual) + sequences
1304 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001305
Fredrik Lundh06d28152000-08-09 18:03:12 +00001306 def event_generate(self, sequence, **kw):
1307 """Generate an event SEQUENCE. Additional
1308 keyword arguments specify parameter of the event
1309 (e.g. x, y, rootx, rooty)."""
1310 args = ('event', 'generate', self._w, sequence)
1311 for k, v in kw.items():
1312 args = args + ('-%s' % k, str(v))
1313 self.tk.call(args)
1314
1315 def event_info(self, virtual=None):
1316 """Return a list of all virtual events or the information
1317 about the SEQUENCE bound to the virtual event VIRTUAL."""
1318 return self.tk.splitlist(
1319 self.tk.call('event', 'info', virtual))
1320
1321 # Image related commands
1322
1323 def image_names(self):
1324 """Return a list of all existing image names."""
1325 return self.tk.call('image', 'names')
1326
1327 def image_types(self):
1328 """Return a list of all available image types (e.g. phote bitmap)."""
1329 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001330
Guido van Rossum80f8be81997-12-02 19:51:39 +00001331
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001332class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001333 """Internal class. Stores function to call when some user
1334 defined Tcl function is called e.g. after an event occurred."""
1335 def __init__(self, func, subst, widget):
1336 """Store FUNC, SUBST and WIDGET as members."""
1337 self.func = func
1338 self.subst = subst
1339 self.widget = widget
1340 def __call__(self, *args):
1341 """Apply first function SUBST to arguments, than FUNC."""
1342 try:
1343 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001344 args = self.subst(*args)
1345 return self.func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001346 except SystemExit, msg:
1347 raise SystemExit, msg
1348 except:
1349 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001350
Guido van Rossume365a591998-05-01 19:48:20 +00001351
Guido van Rossum18468821994-06-20 07:49:28 +00001352class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001353 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001354
Fredrik Lundh06d28152000-08-09 18:03:12 +00001355 def wm_aspect(self,
1356 minNumer=None, minDenom=None,
1357 maxNumer=None, maxDenom=None):
1358 """Instruct the window manager to set the aspect ratio (width/height)
1359 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1360 of the actual values if no argument is given."""
1361 return self._getints(
1362 self.tk.call('wm', 'aspect', self._w,
1363 minNumer, minDenom,
1364 maxNumer, maxDenom))
1365 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001366
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001367 def wm_attributes(self, *args):
1368 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001369
1370 The first form returns a list of the platform specific flags and
1371 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001372 option. The third form sets one or more of the values. The values
1373 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001374
1375 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001376 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001377 to toolwindow (as defined in the MSDN). -topmost gets or sets
1378 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001379 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001380
1381 On Macintosh, XXXXX
1382
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001383 On Unix, there are currently no special attribute values.
1384 """
1385 args = ('wm', 'attributes', self._w) + args
1386 return self.tk.call(args)
1387 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001388
Fredrik Lundh06d28152000-08-09 18:03:12 +00001389 def wm_client(self, name=None):
1390 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1391 current value."""
1392 return self.tk.call('wm', 'client', self._w, name)
1393 client = wm_client
1394 def wm_colormapwindows(self, *wlist):
1395 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1396 of this widget. This list contains windows whose colormaps differ from their
1397 parents. Return current list of widgets if WLIST is empty."""
1398 if len(wlist) > 1:
1399 wlist = (wlist,) # Tk needs a list of windows here
1400 args = ('wm', 'colormapwindows', self._w) + wlist
1401 return map(self._nametowidget, self.tk.call(args))
1402 colormapwindows = wm_colormapwindows
1403 def wm_command(self, value=None):
1404 """Store VALUE in WM_COMMAND property. It is the command
1405 which shall be used to invoke the application. Return current
1406 command if VALUE is None."""
1407 return self.tk.call('wm', 'command', self._w, value)
1408 command = wm_command
1409 def wm_deiconify(self):
1410 """Deiconify this widget. If it was never mapped it will not be mapped.
1411 On Windows it will raise this widget and give it the focus."""
1412 return self.tk.call('wm', 'deiconify', self._w)
1413 deiconify = wm_deiconify
1414 def wm_focusmodel(self, model=None):
1415 """Set focus model to MODEL. "active" means that this widget will claim
1416 the focus itself, "passive" means that the window manager shall give
1417 the focus. Return current focus model if MODEL is None."""
1418 return self.tk.call('wm', 'focusmodel', self._w, model)
1419 focusmodel = wm_focusmodel
1420 def wm_frame(self):
1421 """Return identifier for decorative frame of this widget if present."""
1422 return self.tk.call('wm', 'frame', self._w)
1423 frame = wm_frame
1424 def wm_geometry(self, newGeometry=None):
1425 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1426 current value if None is given."""
1427 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1428 geometry = wm_geometry
1429 def wm_grid(self,
1430 baseWidth=None, baseHeight=None,
1431 widthInc=None, heightInc=None):
1432 """Instruct the window manager that this widget shall only be
1433 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1434 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1435 number of grid units requested in Tk_GeometryRequest."""
1436 return self._getints(self.tk.call(
1437 'wm', 'grid', self._w,
1438 baseWidth, baseHeight, widthInc, heightInc))
1439 grid = wm_grid
1440 def wm_group(self, pathName=None):
1441 """Set the group leader widgets for related widgets to PATHNAME. Return
1442 the group leader of this widget if None is given."""
1443 return self.tk.call('wm', 'group', self._w, pathName)
1444 group = wm_group
1445 def wm_iconbitmap(self, bitmap=None):
1446 """Set bitmap for the iconified widget to BITMAP. Return
1447 the bitmap if None is given."""
1448 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1449 iconbitmap = wm_iconbitmap
1450 def wm_iconify(self):
1451 """Display widget as icon."""
1452 return self.tk.call('wm', 'iconify', self._w)
1453 iconify = wm_iconify
1454 def wm_iconmask(self, bitmap=None):
1455 """Set mask for the icon bitmap of this widget. Return the
1456 mask if None is given."""
1457 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1458 iconmask = wm_iconmask
1459 def wm_iconname(self, newName=None):
1460 """Set the name of the icon for this widget. Return the name if
1461 None is given."""
1462 return self.tk.call('wm', 'iconname', self._w, newName)
1463 iconname = wm_iconname
1464 def wm_iconposition(self, x=None, y=None):
1465 """Set the position of the icon of this widget to X and Y. Return
1466 a tuple of the current values of X and X if None is given."""
1467 return self._getints(self.tk.call(
1468 'wm', 'iconposition', self._w, x, y))
1469 iconposition = wm_iconposition
1470 def wm_iconwindow(self, pathName=None):
1471 """Set widget PATHNAME to be displayed instead of icon. Return the current
1472 value if None is given."""
1473 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1474 iconwindow = wm_iconwindow
1475 def wm_maxsize(self, width=None, height=None):
1476 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1477 the values are given in grid units. Return the current values if None
1478 is given."""
1479 return self._getints(self.tk.call(
1480 'wm', 'maxsize', self._w, width, height))
1481 maxsize = wm_maxsize
1482 def wm_minsize(self, width=None, height=None):
1483 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1484 the values are given in grid units. Return the current values if None
1485 is given."""
1486 return self._getints(self.tk.call(
1487 'wm', 'minsize', self._w, width, height))
1488 minsize = wm_minsize
1489 def wm_overrideredirect(self, boolean=None):
1490 """Instruct the window manager to ignore this widget
1491 if BOOLEAN is given with 1. Return the current value if None
1492 is given."""
1493 return self._getboolean(self.tk.call(
1494 'wm', 'overrideredirect', self._w, boolean))
1495 overrideredirect = wm_overrideredirect
1496 def wm_positionfrom(self, who=None):
1497 """Instruct the window manager that the position of this widget shall
1498 be defined by the user if WHO is "user", and by its own policy if WHO is
1499 "program"."""
1500 return self.tk.call('wm', 'positionfrom', self._w, who)
1501 positionfrom = wm_positionfrom
1502 def wm_protocol(self, name=None, func=None):
1503 """Bind function FUNC to command NAME for this widget.
1504 Return the function bound to NAME if None is given. NAME could be
1505 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1506 if callable(func):
1507 command = self._register(func)
1508 else:
1509 command = func
1510 return self.tk.call(
1511 'wm', 'protocol', self._w, name, command)
1512 protocol = wm_protocol
1513 def wm_resizable(self, width=None, height=None):
1514 """Instruct the window manager whether this width can be resized
1515 in WIDTH or HEIGHT. Both values are boolean values."""
1516 return self.tk.call('wm', 'resizable', self._w, width, height)
1517 resizable = wm_resizable
1518 def wm_sizefrom(self, who=None):
1519 """Instruct the window manager that the size of this widget shall
1520 be defined by the user if WHO is "user", and by its own policy if WHO is
1521 "program"."""
1522 return self.tk.call('wm', 'sizefrom', self._w, who)
1523 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001524 def wm_state(self, newstate=None):
1525 """Query or set the state of this widget as one of normal, icon,
1526 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1527 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001528 state = wm_state
1529 def wm_title(self, string=None):
1530 """Set the title of this widget."""
1531 return self.tk.call('wm', 'title', self._w, string)
1532 title = wm_title
1533 def wm_transient(self, master=None):
1534 """Instruct the window manager that this widget is transient
1535 with regard to widget MASTER."""
1536 return self.tk.call('wm', 'transient', self._w, master)
1537 transient = wm_transient
1538 def wm_withdraw(self):
1539 """Withdraw this widget from the screen such that it is unmapped
1540 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1541 return self.tk.call('wm', 'withdraw', self._w)
1542 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001543
Guido van Rossum18468821994-06-20 07:49:28 +00001544
1545class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001546 """Toplevel widget of Tk which represents mostly the main window
1547 of an appliation. It has an associated Tcl interpreter."""
1548 _w = '.'
1549 def __init__(self, screenName=None, baseName=None, className='Tk'):
1550 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1551 be created. BASENAME will be used for the identification of the profile file (see
1552 readprofile).
1553 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1554 is the name of the widget class."""
1555 global _default_root
1556 self.master = None
1557 self.children = {}
1558 if baseName is None:
1559 import sys, os
1560 baseName = os.path.basename(sys.argv[0])
1561 baseName, ext = os.path.splitext(baseName)
1562 if ext not in ('.py', '.pyc', '.pyo'):
1563 baseName = baseName + ext
1564 self.tk = _tkinter.create(screenName, baseName, className)
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001565 self.tk.wantobjects(wantobjects)
Jack Jansenbe92af02001-08-23 13:25:59 +00001566 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001567 # Disable event scanning except for Command-Period
1568 _MacOS.SchedParams(1, 0)
1569 # Work around nasty MacTk bug
1570 # XXX Is this one still needed?
1571 self.update()
1572 # Version sanity checks
1573 tk_version = self.tk.getvar('tk_version')
1574 if tk_version != _tkinter.TK_VERSION:
1575 raise RuntimeError, \
1576 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1577 % (_tkinter.TK_VERSION, tk_version)
Martin v. Löwis54895972003-05-24 11:37:15 +00001578 # Under unknown circumstances, tcl_version gets coerced to float
1579 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001580 if tcl_version != _tkinter.TCL_VERSION:
1581 raise RuntimeError, \
1582 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1583 % (_tkinter.TCL_VERSION, tcl_version)
1584 if TkVersion < 4.0:
1585 raise RuntimeError, \
1586 "Tk 4.0 or higher is required; found Tk %s" \
1587 % str(TkVersion)
1588 self.tk.createcommand('tkerror', _tkerror)
1589 self.tk.createcommand('exit', _exit)
1590 self.readprofile(baseName, className)
1591 if _support_default_root and not _default_root:
1592 _default_root = self
1593 self.protocol("WM_DELETE_WINDOW", self.destroy)
1594 def destroy(self):
1595 """Destroy this and all descendants widgets. This will
1596 end the application of this Tcl interpreter."""
1597 for c in self.children.values(): c.destroy()
1598 self.tk.call('destroy', self._w)
1599 Misc.destroy(self)
1600 global _default_root
1601 if _support_default_root and _default_root is self:
1602 _default_root = None
1603 def readprofile(self, baseName, className):
1604 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1605 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1606 such a file exists in the home directory."""
1607 import os
1608 if os.environ.has_key('HOME'): home = os.environ['HOME']
1609 else: home = os.curdir
1610 class_tcl = os.path.join(home, '.%s.tcl' % className)
1611 class_py = os.path.join(home, '.%s.py' % className)
1612 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1613 base_py = os.path.join(home, '.%s.py' % baseName)
1614 dir = {'self': self}
1615 exec 'from Tkinter import *' in dir
1616 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001617 self.tk.call('source', class_tcl)
1618 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001619 execfile(class_py, dir)
1620 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001621 self.tk.call('source', base_tcl)
1622 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001623 execfile(base_py, dir)
1624 def report_callback_exception(self, exc, val, tb):
1625 """Internal function. It reports exception on sys.stderr."""
1626 import traceback, sys
1627 sys.stderr.write("Exception in Tkinter callback\n")
1628 sys.last_type = exc
1629 sys.last_value = val
1630 sys.last_traceback = tb
1631 traceback.print_exception(exc, val, tb)
Guido van Rossum18468821994-06-20 07:49:28 +00001632
Guido van Rossum368e06b1997-11-07 20:38:49 +00001633# Ideally, the classes Pack, Place and Grid disappear, the
1634# pack/place/grid methods are defined on the Widget class, and
1635# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1636# ...), with pack(), place() and grid() being short for
1637# pack_configure(), place_configure() and grid_columnconfigure(), and
1638# forget() being short for pack_forget(). As a practical matter, I'm
1639# afraid that there is too much code out there that may be using the
1640# Pack, Place or Grid class, so I leave them intact -- but only as
1641# backwards compatibility features. Also note that those methods that
1642# take a master as argument (e.g. pack_propagate) have been moved to
1643# the Misc class (which now incorporates all methods common between
1644# toplevel and interior widgets). Again, for compatibility, these are
1645# copied into the Pack, Place or Grid class.
1646
Guido van Rossum18468821994-06-20 07:49:28 +00001647class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001648 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001649
Fredrik Lundh06d28152000-08-09 18:03:12 +00001650 Base class to use the methods pack_* in every widget."""
1651 def pack_configure(self, cnf={}, **kw):
1652 """Pack a widget in the parent widget. Use as options:
1653 after=widget - pack it after you have packed widget
1654 anchor=NSEW (or subset) - position widget according to
1655 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001656 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001657 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001658 fill=NONE or X or Y or BOTH - fill widget if widget grows
1659 in=master - use master to contain this widget
1660 ipadx=amount - add internal padding in x direction
1661 ipady=amount - add internal padding in y direction
1662 padx=amount - add padding in x direction
1663 pady=amount - add padding in y direction
1664 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1665 """
1666 self.tk.call(
1667 ('pack', 'configure', self._w)
1668 + self._options(cnf, kw))
1669 pack = configure = config = pack_configure
1670 def pack_forget(self):
1671 """Unmap this widget and do not use it for the packing order."""
1672 self.tk.call('pack', 'forget', self._w)
1673 forget = pack_forget
1674 def pack_info(self):
1675 """Return information about the packing options
1676 for this widget."""
1677 words = self.tk.splitlist(
1678 self.tk.call('pack', 'info', self._w))
1679 dict = {}
1680 for i in range(0, len(words), 2):
1681 key = words[i][1:]
1682 value = words[i+1]
1683 if value[:1] == '.':
1684 value = self._nametowidget(value)
1685 dict[key] = value
1686 return dict
1687 info = pack_info
1688 propagate = pack_propagate = Misc.pack_propagate
1689 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001690
1691class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001692 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001693
Fredrik Lundh06d28152000-08-09 18:03:12 +00001694 Base class to use the methods place_* in every widget."""
1695 def place_configure(self, cnf={}, **kw):
1696 """Place a widget in the parent widget. Use as options:
1697 in=master - master relative to which the widget is placed.
1698 x=amount - locate anchor of this widget at position x of master
1699 y=amount - locate anchor of this widget at position y of master
1700 relx=amount - locate anchor of this widget between 0.0 and 1.0
1701 relative to width of master (1.0 is right edge)
1702 rely=amount - locate anchor of this widget between 0.0 and 1.0
1703 relative to height of master (1.0 is bottom edge)
1704 anchor=NSEW (or subset) - position anchor according to given direction
1705 width=amount - width of this widget in pixel
1706 height=amount - height of this widget in pixel
1707 relwidth=amount - width of this widget between 0.0 and 1.0
1708 relative to width of master (1.0 is the same width
1709 as the master)
1710 relheight=amount - height of this widget between 0.0 and 1.0
1711 relative to height of master (1.0 is the same
1712 height as the master)
1713 bordermode="inside" or "outside" - whether to take border width of master widget
1714 into account
1715 """
1716 for k in ['in_']:
1717 if kw.has_key(k):
1718 kw[k[:-1]] = kw[k]
1719 del kw[k]
1720 self.tk.call(
1721 ('place', 'configure', self._w)
1722 + self._options(cnf, kw))
1723 place = configure = config = place_configure
1724 def place_forget(self):
1725 """Unmap this widget."""
1726 self.tk.call('place', 'forget', self._w)
1727 forget = place_forget
1728 def place_info(self):
1729 """Return information about the placing options
1730 for this widget."""
1731 words = self.tk.splitlist(
1732 self.tk.call('place', 'info', self._w))
1733 dict = {}
1734 for i in range(0, len(words), 2):
1735 key = words[i][1:]
1736 value = words[i+1]
1737 if value[:1] == '.':
1738 value = self._nametowidget(value)
1739 dict[key] = value
1740 return dict
1741 info = place_info
1742 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001743
Guido van Rossum37dcab11996-05-16 16:00:19 +00001744class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001745 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001746
Fredrik Lundh06d28152000-08-09 18:03:12 +00001747 Base class to use the methods grid_* in every widget."""
1748 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1749 def grid_configure(self, cnf={}, **kw):
1750 """Position a widget in the parent widget in a grid. Use as options:
1751 column=number - use cell identified with given column (starting with 0)
1752 columnspan=number - this widget will span several columns
1753 in=master - use master to contain this widget
1754 ipadx=amount - add internal padding in x direction
1755 ipady=amount - add internal padding in y direction
1756 padx=amount - add padding in x direction
1757 pady=amount - add padding in y direction
1758 row=number - use cell identified with given row (starting with 0)
1759 rowspan=number - this widget will span several rows
1760 sticky=NSEW - if cell is larger on which sides will this
1761 widget stick to the cell boundary
1762 """
1763 self.tk.call(
1764 ('grid', 'configure', self._w)
1765 + self._options(cnf, kw))
1766 grid = configure = config = grid_configure
1767 bbox = grid_bbox = Misc.grid_bbox
1768 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1769 def grid_forget(self):
1770 """Unmap this widget."""
1771 self.tk.call('grid', 'forget', self._w)
1772 forget = grid_forget
1773 def grid_remove(self):
1774 """Unmap this widget but remember the grid options."""
1775 self.tk.call('grid', 'remove', self._w)
1776 def grid_info(self):
1777 """Return information about the options
1778 for positioning this widget in a grid."""
1779 words = self.tk.splitlist(
1780 self.tk.call('grid', 'info', self._w))
1781 dict = {}
1782 for i in range(0, len(words), 2):
1783 key = words[i][1:]
1784 value = words[i+1]
1785 if value[:1] == '.':
1786 value = self._nametowidget(value)
1787 dict[key] = value
1788 return dict
1789 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001790 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001791 propagate = grid_propagate = Misc.grid_propagate
1792 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1793 size = grid_size = Misc.grid_size
1794 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001795
Guido van Rossum368e06b1997-11-07 20:38:49 +00001796class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001797 """Internal class."""
1798 def _setup(self, master, cnf):
1799 """Internal function. Sets up information about children."""
1800 if _support_default_root:
1801 global _default_root
1802 if not master:
1803 if not _default_root:
1804 _default_root = Tk()
1805 master = _default_root
1806 self.master = master
1807 self.tk = master.tk
1808 name = None
1809 if cnf.has_key('name'):
1810 name = cnf['name']
1811 del cnf['name']
1812 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001813 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001814 self._name = name
1815 if master._w=='.':
1816 self._w = '.' + name
1817 else:
1818 self._w = master._w + '.' + name
1819 self.children = {}
1820 if self.master.children.has_key(self._name):
1821 self.master.children[self._name].destroy()
1822 self.master.children[self._name] = self
1823 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1824 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1825 and appropriate options."""
1826 if kw:
1827 cnf = _cnfmerge((cnf, kw))
1828 self.widgetName = widgetName
1829 BaseWidget._setup(self, master, cnf)
1830 classes = []
1831 for k in cnf.keys():
1832 if type(k) is ClassType:
1833 classes.append((k, cnf[k]))
1834 del cnf[k]
1835 self.tk.call(
1836 (widgetName, self._w) + extra + self._options(cnf))
1837 for k, v in classes:
1838 k.configure(self, v)
1839 def destroy(self):
1840 """Destroy this and all descendants widgets."""
1841 for c in self.children.values(): c.destroy()
1842 if self.master.children.has_key(self._name):
1843 del self.master.children[self._name]
1844 self.tk.call('destroy', self._w)
1845 Misc.destroy(self)
1846 def _do(self, name, args=()):
1847 # XXX Obsolete -- better use self.tk.call directly!
1848 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001849
Guido van Rossum368e06b1997-11-07 20:38:49 +00001850class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001851 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001852
Fredrik Lundh06d28152000-08-09 18:03:12 +00001853 Base class for a widget which can be positioned with the geometry managers
1854 Pack, Place or Grid."""
1855 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001856
1857class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001858 """Toplevel widget, e.g. for dialogs."""
1859 def __init__(self, master=None, cnf={}, **kw):
1860 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001861
Fredrik Lundh06d28152000-08-09 18:03:12 +00001862 Valid resource names: background, bd, bg, borderwidth, class,
1863 colormap, container, cursor, height, highlightbackground,
1864 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1865 use, visual, width."""
1866 if kw:
1867 cnf = _cnfmerge((cnf, kw))
1868 extra = ()
1869 for wmkey in ['screen', 'class_', 'class', 'visual',
1870 'colormap']:
1871 if cnf.has_key(wmkey):
1872 val = cnf[wmkey]
1873 # TBD: a hack needed because some keys
1874 # are not valid as keyword arguments
1875 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1876 else: opt = '-'+wmkey
1877 extra = extra + (opt, val)
1878 del cnf[wmkey]
1879 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1880 root = self._root()
1881 self.iconname(root.iconname())
1882 self.title(root.title())
1883 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001884
1885class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001886 """Button widget."""
1887 def __init__(self, master=None, cnf={}, **kw):
1888 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001889
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001890 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001891
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001892 activebackground, activeforeground, anchor,
1893 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001894 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001895 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001896 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001897 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001898 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001899 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001900
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001901 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001902
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001903 command, compound, default, height,
1904 overrelief, state, width
1905 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001906 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001907
Fredrik Lundh06d28152000-08-09 18:03:12 +00001908 def tkButtonEnter(self, *dummy):
1909 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001910
Fredrik Lundh06d28152000-08-09 18:03:12 +00001911 def tkButtonLeave(self, *dummy):
1912 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001913
Fredrik Lundh06d28152000-08-09 18:03:12 +00001914 def tkButtonDown(self, *dummy):
1915 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001916
Fredrik Lundh06d28152000-08-09 18:03:12 +00001917 def tkButtonUp(self, *dummy):
1918 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001919
Fredrik Lundh06d28152000-08-09 18:03:12 +00001920 def tkButtonInvoke(self, *dummy):
1921 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001922
Fredrik Lundh06d28152000-08-09 18:03:12 +00001923 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001924 """Flash the button.
1925
1926 This is accomplished by redisplaying
1927 the button several times, alternating between active and
1928 normal colors. At the end of the flash the button is left
1929 in the same normal/active state as when the command was
1930 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001931 disabled.
1932 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001933 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00001934
Fredrik Lundh06d28152000-08-09 18:03:12 +00001935 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001936 """Invoke the command associated with the button.
1937
1938 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001939 or an empty string if there is no command associated with
1940 the button. This command is ignored if the button's state
1941 is disabled.
1942 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001943 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001944
1945# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001946# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001947def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001948 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001949def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001950 s = 'insert'
1951 for a in args:
1952 if a: s = s + (' ' + a)
1953 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001954def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001955 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001956def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001957 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001958def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001959 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001960 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001961 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001962 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00001963
1964class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001965 """Canvas widget to display graphical elements like lines or text."""
1966 def __init__(self, master=None, cnf={}, **kw):
1967 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001968
Fredrik Lundh06d28152000-08-09 18:03:12 +00001969 Valid resource names: background, bd, bg, borderwidth, closeenough,
1970 confine, cursor, height, highlightbackground, highlightcolor,
1971 highlightthickness, insertbackground, insertborderwidth,
1972 insertofftime, insertontime, insertwidth, offset, relief,
1973 scrollregion, selectbackground, selectborderwidth, selectforeground,
1974 state, takefocus, width, xscrollcommand, xscrollincrement,
1975 yscrollcommand, yscrollincrement."""
1976 Widget.__init__(self, master, 'canvas', cnf, kw)
1977 def addtag(self, *args):
1978 """Internal function."""
1979 self.tk.call((self._w, 'addtag') + args)
1980 def addtag_above(self, newtag, tagOrId):
1981 """Add tag NEWTAG to all items above TAGORID."""
1982 self.addtag(newtag, 'above', tagOrId)
1983 def addtag_all(self, newtag):
1984 """Add tag NEWTAG to all items."""
1985 self.addtag(newtag, 'all')
1986 def addtag_below(self, newtag, tagOrId):
1987 """Add tag NEWTAG to all items below TAGORID."""
1988 self.addtag(newtag, 'below', tagOrId)
1989 def addtag_closest(self, newtag, x, y, halo=None, start=None):
1990 """Add tag NEWTAG to item which is closest to pixel at X, Y.
1991 If several match take the top-most.
1992 All items closer than HALO are considered overlapping (all are
1993 closests). If START is specified the next below this tag is taken."""
1994 self.addtag(newtag, 'closest', x, y, halo, start)
1995 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
1996 """Add tag NEWTAG to all items in the rectangle defined
1997 by X1,Y1,X2,Y2."""
1998 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
1999 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2000 """Add tag NEWTAG to all items which overlap the rectangle
2001 defined by X1,Y1,X2,Y2."""
2002 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2003 def addtag_withtag(self, newtag, tagOrId):
2004 """Add tag NEWTAG to all items with TAGORID."""
2005 self.addtag(newtag, 'withtag', tagOrId)
2006 def bbox(self, *args):
2007 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2008 which encloses all items with tags specified as arguments."""
2009 return self._getints(
2010 self.tk.call((self._w, 'bbox') + args)) or None
2011 def tag_unbind(self, tagOrId, sequence, funcid=None):
2012 """Unbind for all items with TAGORID for event SEQUENCE the
2013 function identified with FUNCID."""
2014 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2015 if funcid:
2016 self.deletecommand(funcid)
2017 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2018 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002019
Fredrik Lundh06d28152000-08-09 18:03:12 +00002020 An additional boolean parameter ADD specifies whether FUNC will be
2021 called additionally to the other bound function or whether it will
2022 replace the previous function. See bind for the return value."""
2023 return self._bind((self._w, 'bind', tagOrId),
2024 sequence, func, add)
2025 def canvasx(self, screenx, gridspacing=None):
2026 """Return the canvas x coordinate of pixel position SCREENX rounded
2027 to nearest multiple of GRIDSPACING units."""
2028 return getdouble(self.tk.call(
2029 self._w, 'canvasx', screenx, gridspacing))
2030 def canvasy(self, screeny, gridspacing=None):
2031 """Return the canvas y coordinate of pixel position SCREENY rounded
2032 to nearest multiple of GRIDSPACING units."""
2033 return getdouble(self.tk.call(
2034 self._w, 'canvasy', screeny, gridspacing))
2035 def coords(self, *args):
2036 """Return a list of coordinates for the item given in ARGS."""
2037 # XXX Should use _flatten on args
2038 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002039 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002040 self.tk.call((self._w, 'coords') + args)))
2041 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2042 """Internal function."""
2043 args = _flatten(args)
2044 cnf = args[-1]
2045 if type(cnf) in (DictionaryType, TupleType):
2046 args = args[:-1]
2047 else:
2048 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002049 return getint(self.tk.call(
2050 self._w, 'create', itemType,
2051 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002052 def create_arc(self, *args, **kw):
2053 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2054 return self._create('arc', args, kw)
2055 def create_bitmap(self, *args, **kw):
2056 """Create bitmap with coordinates x1,y1."""
2057 return self._create('bitmap', args, kw)
2058 def create_image(self, *args, **kw):
2059 """Create image item with coordinates x1,y1."""
2060 return self._create('image', args, kw)
2061 def create_line(self, *args, **kw):
2062 """Create line with coordinates x1,y1,...,xn,yn."""
2063 return self._create('line', args, kw)
2064 def create_oval(self, *args, **kw):
2065 """Create oval with coordinates x1,y1,x2,y2."""
2066 return self._create('oval', args, kw)
2067 def create_polygon(self, *args, **kw):
2068 """Create polygon with coordinates x1,y1,...,xn,yn."""
2069 return self._create('polygon', args, kw)
2070 def create_rectangle(self, *args, **kw):
2071 """Create rectangle with coordinates x1,y1,x2,y2."""
2072 return self._create('rectangle', args, kw)
2073 def create_text(self, *args, **kw):
2074 """Create text with coordinates x1,y1."""
2075 return self._create('text', args, kw)
2076 def create_window(self, *args, **kw):
2077 """Create window with coordinates x1,y1,x2,y2."""
2078 return self._create('window', args, kw)
2079 def dchars(self, *args):
2080 """Delete characters of text items identified by tag or id in ARGS (possibly
2081 several times) from FIRST to LAST character (including)."""
2082 self.tk.call((self._w, 'dchars') + args)
2083 def delete(self, *args):
2084 """Delete items identified by all tag or ids contained in ARGS."""
2085 self.tk.call((self._w, 'delete') + args)
2086 def dtag(self, *args):
2087 """Delete tag or id given as last arguments in ARGS from items
2088 identified by first argument in ARGS."""
2089 self.tk.call((self._w, 'dtag') + args)
2090 def find(self, *args):
2091 """Internal function."""
2092 return self._getints(
2093 self.tk.call((self._w, 'find') + args)) or ()
2094 def find_above(self, tagOrId):
2095 """Return items above TAGORID."""
2096 return self.find('above', tagOrId)
2097 def find_all(self):
2098 """Return all items."""
2099 return self.find('all')
2100 def find_below(self, tagOrId):
2101 """Return all items below TAGORID."""
2102 return self.find('below', tagOrId)
2103 def find_closest(self, x, y, halo=None, start=None):
2104 """Return item which is closest to pixel at X, Y.
2105 If several match take the top-most.
2106 All items closer than HALO are considered overlapping (all are
2107 closests). If START is specified the next below this tag is taken."""
2108 return self.find('closest', x, y, halo, start)
2109 def find_enclosed(self, x1, y1, x2, y2):
2110 """Return all items in rectangle defined
2111 by X1,Y1,X2,Y2."""
2112 return self.find('enclosed', x1, y1, x2, y2)
2113 def find_overlapping(self, x1, y1, x2, y2):
2114 """Return all items which overlap the rectangle
2115 defined by X1,Y1,X2,Y2."""
2116 return self.find('overlapping', x1, y1, x2, y2)
2117 def find_withtag(self, tagOrId):
2118 """Return all items with TAGORID."""
2119 return self.find('withtag', tagOrId)
2120 def focus(self, *args):
2121 """Set focus to the first item specified in ARGS."""
2122 return self.tk.call((self._w, 'focus') + args)
2123 def gettags(self, *args):
2124 """Return tags associated with the first item specified in ARGS."""
2125 return self.tk.splitlist(
2126 self.tk.call((self._w, 'gettags') + args))
2127 def icursor(self, *args):
2128 """Set cursor at position POS in the item identified by TAGORID.
2129 In ARGS TAGORID must be first."""
2130 self.tk.call((self._w, 'icursor') + args)
2131 def index(self, *args):
2132 """Return position of cursor as integer in item specified in ARGS."""
2133 return getint(self.tk.call((self._w, 'index') + args))
2134 def insert(self, *args):
2135 """Insert TEXT in item TAGORID at position POS. ARGS must
2136 be TAGORID POS TEXT."""
2137 self.tk.call((self._w, 'insert') + args)
2138 def itemcget(self, tagOrId, option):
2139 """Return the resource value for an OPTION for item TAGORID."""
2140 return self.tk.call(
2141 (self._w, 'itemcget') + (tagOrId, '-'+option))
2142 def itemconfigure(self, tagOrId, cnf=None, **kw):
2143 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002144
Fredrik Lundh06d28152000-08-09 18:03:12 +00002145 The values for resources are specified as keyword
2146 arguments. To get an overview about
2147 the allowed keyword arguments call the method without arguments.
2148 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002149 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002150 itemconfig = itemconfigure
2151 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2152 # so the preferred name for them is tag_lower, tag_raise
2153 # (similar to tag_bind, and similar to the Text widget);
2154 # unfortunately can't delete the old ones yet (maybe in 1.6)
2155 def tag_lower(self, *args):
2156 """Lower an item TAGORID given in ARGS
2157 (optional below another item)."""
2158 self.tk.call((self._w, 'lower') + args)
2159 lower = tag_lower
2160 def move(self, *args):
2161 """Move an item TAGORID given in ARGS."""
2162 self.tk.call((self._w, 'move') + args)
2163 def postscript(self, cnf={}, **kw):
2164 """Print the contents of the canvas to a postscript
2165 file. Valid options: colormap, colormode, file, fontmap,
2166 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2167 rotate, witdh, x, y."""
2168 return self.tk.call((self._w, 'postscript') +
2169 self._options(cnf, kw))
2170 def tag_raise(self, *args):
2171 """Raise an item TAGORID given in ARGS
2172 (optional above another item)."""
2173 self.tk.call((self._w, 'raise') + args)
2174 lift = tkraise = tag_raise
2175 def scale(self, *args):
2176 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2177 self.tk.call((self._w, 'scale') + args)
2178 def scan_mark(self, x, y):
2179 """Remember the current X, Y coordinates."""
2180 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002181 def scan_dragto(self, x, y, gain=10):
2182 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002183 difference between X and Y and the coordinates given in
2184 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002185 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002186 def select_adjust(self, tagOrId, index):
2187 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2188 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2189 def select_clear(self):
2190 """Clear the selection if it is in this widget."""
2191 self.tk.call(self._w, 'select', 'clear')
2192 def select_from(self, tagOrId, index):
2193 """Set the fixed end of a selection in item TAGORID to INDEX."""
2194 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2195 def select_item(self):
2196 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002197 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002198 def select_to(self, tagOrId, index):
2199 """Set the variable end of a selection in item TAGORID to INDEX."""
2200 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2201 def type(self, tagOrId):
2202 """Return the type of the item TAGORID."""
2203 return self.tk.call(self._w, 'type', tagOrId) or None
2204 def xview(self, *args):
2205 """Query and change horizontal position of the view."""
2206 if not args:
2207 return self._getdoubles(self.tk.call(self._w, 'xview'))
2208 self.tk.call((self._w, 'xview') + args)
2209 def xview_moveto(self, fraction):
2210 """Adjusts the view in the window so that FRACTION of the
2211 total width of the canvas is off-screen to the left."""
2212 self.tk.call(self._w, 'xview', 'moveto', fraction)
2213 def xview_scroll(self, number, what):
2214 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2215 self.tk.call(self._w, 'xview', 'scroll', number, what)
2216 def yview(self, *args):
2217 """Query and change vertical position of the view."""
2218 if not args:
2219 return self._getdoubles(self.tk.call(self._w, 'yview'))
2220 self.tk.call((self._w, 'yview') + args)
2221 def yview_moveto(self, fraction):
2222 """Adjusts the view in the window so that FRACTION of the
2223 total height of the canvas is off-screen to the top."""
2224 self.tk.call(self._w, 'yview', 'moveto', fraction)
2225 def yview_scroll(self, number, what):
2226 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2227 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002228
2229class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002230 """Checkbutton widget which is either in on- or off-state."""
2231 def __init__(self, master=None, cnf={}, **kw):
2232 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002233
Fredrik Lundh06d28152000-08-09 18:03:12 +00002234 Valid resource names: activebackground, activeforeground, anchor,
2235 background, bd, bg, bitmap, borderwidth, command, cursor,
2236 disabledforeground, fg, font, foreground, height,
2237 highlightbackground, highlightcolor, highlightthickness, image,
2238 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2239 selectcolor, selectimage, state, takefocus, text, textvariable,
2240 underline, variable, width, wraplength."""
2241 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2242 def deselect(self):
2243 """Put the button in off-state."""
2244 self.tk.call(self._w, 'deselect')
2245 def flash(self):
2246 """Flash the button."""
2247 self.tk.call(self._w, 'flash')
2248 def invoke(self):
2249 """Toggle the button and invoke a command if given as resource."""
2250 return self.tk.call(self._w, 'invoke')
2251 def select(self):
2252 """Put the button in on-state."""
2253 self.tk.call(self._w, 'select')
2254 def toggle(self):
2255 """Toggle the button."""
2256 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002257
2258class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002259 """Entry widget which allows to display simple text."""
2260 def __init__(self, master=None, cnf={}, **kw):
2261 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002262
Fredrik Lundh06d28152000-08-09 18:03:12 +00002263 Valid resource names: background, bd, bg, borderwidth, cursor,
2264 exportselection, fg, font, foreground, highlightbackground,
2265 highlightcolor, highlightthickness, insertbackground,
2266 insertborderwidth, insertofftime, insertontime, insertwidth,
2267 invalidcommand, invcmd, justify, relief, selectbackground,
2268 selectborderwidth, selectforeground, show, state, takefocus,
2269 textvariable, validate, validatecommand, vcmd, width,
2270 xscrollcommand."""
2271 Widget.__init__(self, master, 'entry', cnf, kw)
2272 def delete(self, first, last=None):
2273 """Delete text from FIRST to LAST (not included)."""
2274 self.tk.call(self._w, 'delete', first, last)
2275 def get(self):
2276 """Return the text."""
2277 return self.tk.call(self._w, 'get')
2278 def icursor(self, index):
2279 """Insert cursor at INDEX."""
2280 self.tk.call(self._w, 'icursor', index)
2281 def index(self, index):
2282 """Return position of cursor."""
2283 return getint(self.tk.call(
2284 self._w, 'index', index))
2285 def insert(self, index, string):
2286 """Insert STRING at INDEX."""
2287 self.tk.call(self._w, 'insert', index, string)
2288 def scan_mark(self, x):
2289 """Remember the current X, Y coordinates."""
2290 self.tk.call(self._w, 'scan', 'mark', x)
2291 def scan_dragto(self, x):
2292 """Adjust the view of the canvas to 10 times the
2293 difference between X and Y and the coordinates given in
2294 scan_mark."""
2295 self.tk.call(self._w, 'scan', 'dragto', x)
2296 def selection_adjust(self, index):
2297 """Adjust the end of the selection near the cursor to INDEX."""
2298 self.tk.call(self._w, 'selection', 'adjust', index)
2299 select_adjust = selection_adjust
2300 def selection_clear(self):
2301 """Clear the selection if it is in this widget."""
2302 self.tk.call(self._w, 'selection', 'clear')
2303 select_clear = selection_clear
2304 def selection_from(self, index):
2305 """Set the fixed end of a selection to INDEX."""
2306 self.tk.call(self._w, 'selection', 'from', index)
2307 select_from = selection_from
2308 def selection_present(self):
2309 """Return whether the widget has the selection."""
2310 return self.tk.getboolean(
2311 self.tk.call(self._w, 'selection', 'present'))
2312 select_present = selection_present
2313 def selection_range(self, start, end):
2314 """Set the selection from START to END (not included)."""
2315 self.tk.call(self._w, 'selection', 'range', start, end)
2316 select_range = selection_range
2317 def selection_to(self, index):
2318 """Set the variable end of a selection to INDEX."""
2319 self.tk.call(self._w, 'selection', 'to', index)
2320 select_to = selection_to
2321 def xview(self, index):
2322 """Query and change horizontal position of the view."""
2323 self.tk.call(self._w, 'xview', index)
2324 def xview_moveto(self, fraction):
2325 """Adjust the view in the window so that FRACTION of the
2326 total width of the entry is off-screen to the left."""
2327 self.tk.call(self._w, 'xview', 'moveto', fraction)
2328 def xview_scroll(self, number, what):
2329 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2330 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002331
2332class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002333 """Frame widget which may contain other widgets and can have a 3D border."""
2334 def __init__(self, master=None, cnf={}, **kw):
2335 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002336
Fredrik Lundh06d28152000-08-09 18:03:12 +00002337 Valid resource names: background, bd, bg, borderwidth, class,
2338 colormap, container, cursor, height, highlightbackground,
2339 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2340 cnf = _cnfmerge((cnf, kw))
2341 extra = ()
2342 if cnf.has_key('class_'):
2343 extra = ('-class', cnf['class_'])
2344 del cnf['class_']
2345 elif cnf.has_key('class'):
2346 extra = ('-class', cnf['class'])
2347 del cnf['class']
2348 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002349
2350class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002351 """Label widget which can display text and bitmaps."""
2352 def __init__(self, master=None, cnf={}, **kw):
2353 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002354
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002355 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002356
2357 activebackground, activeforeground, anchor,
2358 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002359 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002360 highlightbackground, highlightcolor,
2361 highlightthickness, image, justify,
2362 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002363 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002364
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002365 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002366
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002367 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002368
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002369 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002370 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002371
Guido van Rossum18468821994-06-20 07:49:28 +00002372class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002373 """Listbox widget which can display a list of strings."""
2374 def __init__(self, master=None, cnf={}, **kw):
2375 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002376
Fredrik Lundh06d28152000-08-09 18:03:12 +00002377 Valid resource names: background, bd, bg, borderwidth, cursor,
2378 exportselection, fg, font, foreground, height, highlightbackground,
2379 highlightcolor, highlightthickness, relief, selectbackground,
2380 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2381 width, xscrollcommand, yscrollcommand, listvariable."""
2382 Widget.__init__(self, master, 'listbox', cnf, kw)
2383 def activate(self, index):
2384 """Activate item identified by INDEX."""
2385 self.tk.call(self._w, 'activate', index)
2386 def bbox(self, *args):
2387 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2388 which encloses the item identified by index in ARGS."""
2389 return self._getints(
2390 self.tk.call((self._w, 'bbox') + args)) or None
2391 def curselection(self):
2392 """Return list of indices of currently selected item."""
2393 # XXX Ought to apply self._getints()...
2394 return self.tk.splitlist(self.tk.call(
2395 self._w, 'curselection'))
2396 def delete(self, first, last=None):
2397 """Delete items from FIRST to LAST (not included)."""
2398 self.tk.call(self._w, 'delete', first, last)
2399 def get(self, first, last=None):
2400 """Get list of items from FIRST to LAST (not included)."""
2401 if last:
2402 return self.tk.splitlist(self.tk.call(
2403 self._w, 'get', first, last))
2404 else:
2405 return self.tk.call(self._w, 'get', first)
2406 def index(self, index):
2407 """Return index of item identified with INDEX."""
2408 i = self.tk.call(self._w, 'index', index)
2409 if i == 'none': return None
2410 return getint(i)
2411 def insert(self, index, *elements):
2412 """Insert ELEMENTS at INDEX."""
2413 self.tk.call((self._w, 'insert', index) + elements)
2414 def nearest(self, y):
2415 """Get index of item which is nearest to y coordinate Y."""
2416 return getint(self.tk.call(
2417 self._w, 'nearest', y))
2418 def scan_mark(self, x, y):
2419 """Remember the current X, Y coordinates."""
2420 self.tk.call(self._w, 'scan', 'mark', x, y)
2421 def scan_dragto(self, x, y):
2422 """Adjust the view of the listbox to 10 times the
2423 difference between X and Y and the coordinates given in
2424 scan_mark."""
2425 self.tk.call(self._w, 'scan', 'dragto', x, y)
2426 def see(self, index):
2427 """Scroll such that INDEX is visible."""
2428 self.tk.call(self._w, 'see', index)
2429 def selection_anchor(self, index):
2430 """Set the fixed end oft the selection to INDEX."""
2431 self.tk.call(self._w, 'selection', 'anchor', index)
2432 select_anchor = selection_anchor
2433 def selection_clear(self, first, last=None):
2434 """Clear the selection from FIRST to LAST (not included)."""
2435 self.tk.call(self._w,
2436 'selection', 'clear', first, last)
2437 select_clear = selection_clear
2438 def selection_includes(self, index):
2439 """Return 1 if INDEX is part of the selection."""
2440 return self.tk.getboolean(self.tk.call(
2441 self._w, 'selection', 'includes', index))
2442 select_includes = selection_includes
2443 def selection_set(self, first, last=None):
2444 """Set the selection from FIRST to LAST (not included) without
2445 changing the currently selected elements."""
2446 self.tk.call(self._w, 'selection', 'set', first, last)
2447 select_set = selection_set
2448 def size(self):
2449 """Return the number of elements in the listbox."""
2450 return getint(self.tk.call(self._w, 'size'))
2451 def xview(self, *what):
2452 """Query and change horizontal position of the view."""
2453 if not what:
2454 return self._getdoubles(self.tk.call(self._w, 'xview'))
2455 self.tk.call((self._w, 'xview') + what)
2456 def xview_moveto(self, fraction):
2457 """Adjust the view in the window so that FRACTION of the
2458 total width of the entry is off-screen to the left."""
2459 self.tk.call(self._w, 'xview', 'moveto', fraction)
2460 def xview_scroll(self, number, what):
2461 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2462 self.tk.call(self._w, 'xview', 'scroll', number, what)
2463 def yview(self, *what):
2464 """Query and change vertical position of the view."""
2465 if not what:
2466 return self._getdoubles(self.tk.call(self._w, 'yview'))
2467 self.tk.call((self._w, 'yview') + what)
2468 def yview_moveto(self, fraction):
2469 """Adjust the view in the window so that FRACTION of the
2470 total width of the entry is off-screen to the top."""
2471 self.tk.call(self._w, 'yview', 'moveto', fraction)
2472 def yview_scroll(self, number, what):
2473 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2474 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002475 def itemcget(self, index, option):
2476 """Return the resource value for an ITEM and an OPTION."""
2477 return self.tk.call(
2478 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002479 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002480 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002481
2482 The values for resources are specified as keyword arguments.
2483 To get an overview about the allowed keyword arguments
2484 call the method without arguments.
2485 Valid resource names: background, bg, foreground, fg,
2486 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002487 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002488 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002489
2490class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002491 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2492 def __init__(self, master=None, cnf={}, **kw):
2493 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002494
Fredrik Lundh06d28152000-08-09 18:03:12 +00002495 Valid resource names: activebackground, activeborderwidth,
2496 activeforeground, background, bd, bg, borderwidth, cursor,
2497 disabledforeground, fg, font, foreground, postcommand, relief,
2498 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2499 Widget.__init__(self, master, 'menu', cnf, kw)
2500 def tk_bindForTraversal(self):
2501 pass # obsolete since Tk 4.0
2502 def tk_mbPost(self):
2503 self.tk.call('tk_mbPost', self._w)
2504 def tk_mbUnpost(self):
2505 self.tk.call('tk_mbUnpost')
2506 def tk_traverseToMenu(self, char):
2507 self.tk.call('tk_traverseToMenu', self._w, char)
2508 def tk_traverseWithinMenu(self, char):
2509 self.tk.call('tk_traverseWithinMenu', self._w, char)
2510 def tk_getMenuButtons(self):
2511 return self.tk.call('tk_getMenuButtons', self._w)
2512 def tk_nextMenu(self, count):
2513 self.tk.call('tk_nextMenu', count)
2514 def tk_nextMenuEntry(self, count):
2515 self.tk.call('tk_nextMenuEntry', count)
2516 def tk_invokeMenu(self):
2517 self.tk.call('tk_invokeMenu', self._w)
2518 def tk_firstMenu(self):
2519 self.tk.call('tk_firstMenu', self._w)
2520 def tk_mbButtonDown(self):
2521 self.tk.call('tk_mbButtonDown', self._w)
2522 def tk_popup(self, x, y, entry=""):
2523 """Post the menu at position X,Y with entry ENTRY."""
2524 self.tk.call('tk_popup', self._w, x, y, entry)
2525 def activate(self, index):
2526 """Activate entry at INDEX."""
2527 self.tk.call(self._w, 'activate', index)
2528 def add(self, itemType, cnf={}, **kw):
2529 """Internal function."""
2530 self.tk.call((self._w, 'add', itemType) +
2531 self._options(cnf, kw))
2532 def add_cascade(self, cnf={}, **kw):
2533 """Add hierarchical menu item."""
2534 self.add('cascade', cnf or kw)
2535 def add_checkbutton(self, cnf={}, **kw):
2536 """Add checkbutton menu item."""
2537 self.add('checkbutton', cnf or kw)
2538 def add_command(self, cnf={}, **kw):
2539 """Add command menu item."""
2540 self.add('command', cnf or kw)
2541 def add_radiobutton(self, cnf={}, **kw):
2542 """Addd radio menu item."""
2543 self.add('radiobutton', cnf or kw)
2544 def add_separator(self, cnf={}, **kw):
2545 """Add separator."""
2546 self.add('separator', cnf or kw)
2547 def insert(self, index, itemType, cnf={}, **kw):
2548 """Internal function."""
2549 self.tk.call((self._w, 'insert', index, itemType) +
2550 self._options(cnf, kw))
2551 def insert_cascade(self, index, cnf={}, **kw):
2552 """Add hierarchical menu item at INDEX."""
2553 self.insert(index, 'cascade', cnf or kw)
2554 def insert_checkbutton(self, index, cnf={}, **kw):
2555 """Add checkbutton menu item at INDEX."""
2556 self.insert(index, 'checkbutton', cnf or kw)
2557 def insert_command(self, index, cnf={}, **kw):
2558 """Add command menu item at INDEX."""
2559 self.insert(index, 'command', cnf or kw)
2560 def insert_radiobutton(self, index, cnf={}, **kw):
2561 """Addd radio menu item at INDEX."""
2562 self.insert(index, 'radiobutton', cnf or kw)
2563 def insert_separator(self, index, cnf={}, **kw):
2564 """Add separator at INDEX."""
2565 self.insert(index, 'separator', cnf or kw)
2566 def delete(self, index1, index2=None):
2567 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2568 self.tk.call(self._w, 'delete', index1, index2)
2569 def entrycget(self, index, option):
2570 """Return the resource value of an menu item for OPTION at INDEX."""
2571 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2572 def entryconfigure(self, index, cnf=None, **kw):
2573 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002574 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002575 entryconfig = entryconfigure
2576 def index(self, index):
2577 """Return the index of a menu item identified by INDEX."""
2578 i = self.tk.call(self._w, 'index', index)
2579 if i == 'none': return None
2580 return getint(i)
2581 def invoke(self, index):
2582 """Invoke a menu item identified by INDEX and execute
2583 the associated command."""
2584 return self.tk.call(self._w, 'invoke', index)
2585 def post(self, x, y):
2586 """Display a menu at position X,Y."""
2587 self.tk.call(self._w, 'post', x, y)
2588 def type(self, index):
2589 """Return the type of the menu item at INDEX."""
2590 return self.tk.call(self._w, 'type', index)
2591 def unpost(self):
2592 """Unmap a menu."""
2593 self.tk.call(self._w, 'unpost')
2594 def yposition(self, index):
2595 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2596 return getint(self.tk.call(
2597 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002598
2599class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002600 """Menubutton widget, obsolete since Tk8.0."""
2601 def __init__(self, master=None, cnf={}, **kw):
2602 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002603
2604class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002605 """Message widget to display multiline text. Obsolete since Label does it too."""
2606 def __init__(self, master=None, cnf={}, **kw):
2607 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002608
2609class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002610 """Radiobutton widget which shows only one of several buttons in on-state."""
2611 def __init__(self, master=None, cnf={}, **kw):
2612 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002613
Fredrik Lundh06d28152000-08-09 18:03:12 +00002614 Valid resource names: activebackground, activeforeground, anchor,
2615 background, bd, bg, bitmap, borderwidth, command, cursor,
2616 disabledforeground, fg, font, foreground, height,
2617 highlightbackground, highlightcolor, highlightthickness, image,
2618 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2619 state, takefocus, text, textvariable, underline, value, variable,
2620 width, wraplength."""
2621 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2622 def deselect(self):
2623 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002624
Fredrik Lundh06d28152000-08-09 18:03:12 +00002625 self.tk.call(self._w, 'deselect')
2626 def flash(self):
2627 """Flash the button."""
2628 self.tk.call(self._w, 'flash')
2629 def invoke(self):
2630 """Toggle the button and invoke a command if given as resource."""
2631 return self.tk.call(self._w, 'invoke')
2632 def select(self):
2633 """Put the button in on-state."""
2634 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002635
2636class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002637 """Scale widget which can display a numerical scale."""
2638 def __init__(self, master=None, cnf={}, **kw):
2639 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002640
Fredrik Lundh06d28152000-08-09 18:03:12 +00002641 Valid resource names: activebackground, background, bigincrement, bd,
2642 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2643 highlightbackground, highlightcolor, highlightthickness, label,
2644 length, orient, relief, repeatdelay, repeatinterval, resolution,
2645 showvalue, sliderlength, sliderrelief, state, takefocus,
2646 tickinterval, to, troughcolor, variable, width."""
2647 Widget.__init__(self, master, 'scale', cnf, kw)
2648 def get(self):
2649 """Get the current value as integer or float."""
2650 value = self.tk.call(self._w, 'get')
2651 try:
2652 return getint(value)
2653 except ValueError:
2654 return getdouble(value)
2655 def set(self, value):
2656 """Set the value to VALUE."""
2657 self.tk.call(self._w, 'set', value)
2658 def coords(self, value=None):
2659 """Return a tuple (X,Y) of the point along the centerline of the
2660 trough that corresponds to VALUE or the current value if None is
2661 given."""
2662
2663 return self._getints(self.tk.call(self._w, 'coords', value))
2664 def identify(self, x, y):
2665 """Return where the point X,Y lies. Valid return values are "slider",
2666 "though1" and "though2"."""
2667 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002668
2669class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002670 """Scrollbar widget which displays a slider at a certain position."""
2671 def __init__(self, master=None, cnf={}, **kw):
2672 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002673
Fredrik Lundh06d28152000-08-09 18:03:12 +00002674 Valid resource names: activebackground, activerelief,
2675 background, bd, bg, borderwidth, command, cursor,
2676 elementborderwidth, highlightbackground,
2677 highlightcolor, highlightthickness, jump, orient,
2678 relief, repeatdelay, repeatinterval, takefocus,
2679 troughcolor, width."""
2680 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2681 def activate(self, index):
2682 """Display the element at INDEX with activebackground and activerelief.
2683 INDEX can be "arrow1","slider" or "arrow2"."""
2684 self.tk.call(self._w, 'activate', index)
2685 def delta(self, deltax, deltay):
2686 """Return the fractional change of the scrollbar setting if it
2687 would be moved by DELTAX or DELTAY pixels."""
2688 return getdouble(
2689 self.tk.call(self._w, 'delta', deltax, deltay))
2690 def fraction(self, x, y):
2691 """Return the fractional value which corresponds to a slider
2692 position of X,Y."""
2693 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2694 def identify(self, x, y):
2695 """Return the element under position X,Y as one of
2696 "arrow1","slider","arrow2" or ""."""
2697 return self.tk.call(self._w, 'identify', x, y)
2698 def get(self):
2699 """Return the current fractional values (upper and lower end)
2700 of the slider position."""
2701 return self._getdoubles(self.tk.call(self._w, 'get'))
2702 def set(self, *args):
2703 """Set the fractional values of the slider position (upper and
2704 lower ends as value between 0 and 1)."""
2705 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002706
2707
2708
Guido van Rossum18468821994-06-20 07:49:28 +00002709class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002710 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002711 def __init__(self, master=None, cnf={}, **kw):
2712 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002713
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002714 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002715
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002716 background, borderwidth, cursor,
2717 exportselection, font, foreground,
2718 highlightbackground, highlightcolor,
2719 highlightthickness, insertbackground,
2720 insertborderwidth, insertofftime,
2721 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002722 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002723 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002724 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002725 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002726
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002727 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002728
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002729 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002730 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002731 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002732
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002733 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002734 Widget.__init__(self, master, 'text', cnf, kw)
2735 def bbox(self, *args):
2736 """Return a tuple of (x,y,width,height) which gives the bounding
2737 box of the visible part of the character at the index in ARGS."""
2738 return self._getints(
2739 self.tk.call((self._w, 'bbox') + args)) or None
2740 def tk_textSelectTo(self, index):
2741 self.tk.call('tk_textSelectTo', self._w, index)
2742 def tk_textBackspace(self):
2743 self.tk.call('tk_textBackspace', self._w)
2744 def tk_textIndexCloser(self, a, b, c):
2745 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2746 def tk_textResetAnchor(self, index):
2747 self.tk.call('tk_textResetAnchor', self._w, index)
2748 def compare(self, index1, op, index2):
2749 """Return whether between index INDEX1 and index INDEX2 the
2750 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2751 return self.tk.getboolean(self.tk.call(
2752 self._w, 'compare', index1, op, index2))
2753 def debug(self, boolean=None):
2754 """Turn on the internal consistency checks of the B-Tree inside the text
2755 widget according to BOOLEAN."""
2756 return self.tk.getboolean(self.tk.call(
2757 self._w, 'debug', boolean))
2758 def delete(self, index1, index2=None):
2759 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2760 self.tk.call(self._w, 'delete', index1, index2)
2761 def dlineinfo(self, index):
2762 """Return tuple (x,y,width,height,baseline) giving the bounding box
2763 and baseline position of the visible part of the line containing
2764 the character at INDEX."""
2765 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002766 def dump(self, index1, index2=None, command=None, **kw):
2767 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002768
Guido van Rossum256705b2002-04-23 13:29:43 +00002769 The type of contents returned in filtered based on the keyword
2770 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2771 given and true, then the corresponding items are returned. The result
2772 is a list of triples of the form (key, value, index). If none of the
2773 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002774
Guido van Rossum256705b2002-04-23 13:29:43 +00002775 If the 'command' argument is given, it is called once for each element
2776 of the list of triples, with the values of each triple serving as the
2777 arguments to the function. In this case the list is not returned."""
2778 args = []
2779 func_name = None
2780 result = None
2781 if not command:
2782 # Never call the dump command without the -command flag, since the
2783 # output could involve Tcl quoting and would be a pain to parse
2784 # right. Instead just set the command to build a list of triples
2785 # as if we had done the parsing.
2786 result = []
2787 def append_triple(key, value, index, result=result):
2788 result.append((key, value, index))
2789 command = append_triple
2790 try:
2791 if not isinstance(command, str):
2792 func_name = command = self._register(command)
2793 args += ["-command", command]
2794 for key in kw:
2795 if kw[key]: args.append("-" + key)
2796 args.append(index1)
2797 if index2:
2798 args.append(index2)
2799 self.tk.call(self._w, "dump", *args)
2800 return result
2801 finally:
2802 if func_name:
2803 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002804
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002805 ## new in tk8.4
2806 def edit(self, *args):
2807 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002808
2809 This method controls the undo mechanism and
2810 the modified flag. The exact behavior of the
2811 command depends on the option argument that
2812 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002813 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002814
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002815 edit_modified, edit_redo, edit_reset, edit_separator
2816 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002817
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002818 """
2819 return self._getints(
2820 self.tk.call((self._w, 'edit') + args)) or ()
2821
2822 def edit_modified(self, arg=None):
2823 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002824
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002825 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002826 flag of the widget. The insert, delete, edit undo and
2827 edit redo commands or the user can set or clear the
2828 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002829 modified flag of the widget to arg.
2830 """
2831 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002832
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002833 def edit_redo(self):
2834 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002835
2836 When the undo option is true, reapplies the last
2837 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002838 then. Generates an error when the redo stack is empty.
2839 Does nothing when the undo option is false.
2840 """
2841 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002842
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002843 def edit_reset(self):
2844 """Clears the undo and redo stacks
2845 """
2846 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002847
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002848 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002849 """Inserts a separator (boundary) on the undo stack.
2850
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002851 Does nothing when the undo option is false
2852 """
2853 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002854
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002855 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002856 """Undoes the last edit action
2857
2858 If the undo option is true. An edit action is defined
2859 as all the insert and delete commands that are recorded
2860 on the undo stack in between two separators. Generates
2861 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002862 when the undo option is false
2863 """
2864 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002865
Fredrik Lundh06d28152000-08-09 18:03:12 +00002866 def get(self, index1, index2=None):
2867 """Return the text from INDEX1 to INDEX2 (not included)."""
2868 return self.tk.call(self._w, 'get', index1, index2)
2869 # (Image commands are new in 8.0)
2870 def image_cget(self, index, option):
2871 """Return the value of OPTION of an embedded image at INDEX."""
2872 if option[:1] != "-":
2873 option = "-" + option
2874 if option[-1:] == "_":
2875 option = option[:-1]
2876 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002877 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002878 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002879 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002880 def image_create(self, index, cnf={}, **kw):
2881 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002882 return self.tk.call(
2883 self._w, "image", "create", index,
2884 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002885 def image_names(self):
2886 """Return all names of embedded images in this widget."""
2887 return self.tk.call(self._w, "image", "names")
2888 def index(self, index):
2889 """Return the index in the form line.char for INDEX."""
2890 return self.tk.call(self._w, 'index', index)
2891 def insert(self, index, chars, *args):
2892 """Insert CHARS before the characters at INDEX. An additional
2893 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2894 self.tk.call((self._w, 'insert', index, chars) + args)
2895 def mark_gravity(self, markName, direction=None):
2896 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2897 Return the current value if None is given for DIRECTION."""
2898 return self.tk.call(
2899 (self._w, 'mark', 'gravity', markName, direction))
2900 def mark_names(self):
2901 """Return all mark names."""
2902 return self.tk.splitlist(self.tk.call(
2903 self._w, 'mark', 'names'))
2904 def mark_set(self, markName, index):
2905 """Set mark MARKNAME before the character at INDEX."""
2906 self.tk.call(self._w, 'mark', 'set', markName, index)
2907 def mark_unset(self, *markNames):
2908 """Delete all marks in MARKNAMES."""
2909 self.tk.call((self._w, 'mark', 'unset') + markNames)
2910 def mark_next(self, index):
2911 """Return the name of the next mark after INDEX."""
2912 return self.tk.call(self._w, 'mark', 'next', index) or None
2913 def mark_previous(self, index):
2914 """Return the name of the previous mark before INDEX."""
2915 return self.tk.call(self._w, 'mark', 'previous', index) or None
2916 def scan_mark(self, x, y):
2917 """Remember the current X, Y coordinates."""
2918 self.tk.call(self._w, 'scan', 'mark', x, y)
2919 def scan_dragto(self, x, y):
2920 """Adjust the view of the text to 10 times the
2921 difference between X and Y and the coordinates given in
2922 scan_mark."""
2923 self.tk.call(self._w, 'scan', 'dragto', x, y)
2924 def search(self, pattern, index, stopindex=None,
2925 forwards=None, backwards=None, exact=None,
2926 regexp=None, nocase=None, count=None):
2927 """Search PATTERN beginning from INDEX until STOPINDEX.
2928 Return the index of the first character of a match or an empty string."""
2929 args = [self._w, 'search']
2930 if forwards: args.append('-forwards')
2931 if backwards: args.append('-backwards')
2932 if exact: args.append('-exact')
2933 if regexp: args.append('-regexp')
2934 if nocase: args.append('-nocase')
2935 if count: args.append('-count'); args.append(count)
2936 if pattern[0] == '-': args.append('--')
2937 args.append(pattern)
2938 args.append(index)
2939 if stopindex: args.append(stopindex)
2940 return self.tk.call(tuple(args))
2941 def see(self, index):
2942 """Scroll such that the character at INDEX is visible."""
2943 self.tk.call(self._w, 'see', index)
2944 def tag_add(self, tagName, index1, *args):
2945 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2946 Additional pairs of indices may follow in ARGS."""
2947 self.tk.call(
2948 (self._w, 'tag', 'add', tagName, index1) + args)
2949 def tag_unbind(self, tagName, sequence, funcid=None):
2950 """Unbind for all characters with TAGNAME for event SEQUENCE the
2951 function identified with FUNCID."""
2952 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2953 if funcid:
2954 self.deletecommand(funcid)
2955 def tag_bind(self, tagName, sequence, func, add=None):
2956 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002957
Fredrik Lundh06d28152000-08-09 18:03:12 +00002958 An additional boolean parameter ADD specifies whether FUNC will be
2959 called additionally to the other bound function or whether it will
2960 replace the previous function. See bind for the return value."""
2961 return self._bind((self._w, 'tag', 'bind', tagName),
2962 sequence, func, add)
2963 def tag_cget(self, tagName, option):
2964 """Return the value of OPTION for tag TAGNAME."""
2965 if option[:1] != '-':
2966 option = '-' + option
2967 if option[-1:] == '_':
2968 option = option[:-1]
2969 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002970 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002971 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002972 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002973 tag_config = tag_configure
2974 def tag_delete(self, *tagNames):
2975 """Delete all tags in TAGNAMES."""
2976 self.tk.call((self._w, 'tag', 'delete') + tagNames)
2977 def tag_lower(self, tagName, belowThis=None):
2978 """Change the priority of tag TAGNAME such that it is lower
2979 than the priority of BELOWTHIS."""
2980 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
2981 def tag_names(self, index=None):
2982 """Return a list of all tag names."""
2983 return self.tk.splitlist(
2984 self.tk.call(self._w, 'tag', 'names', index))
2985 def tag_nextrange(self, tagName, index1, index2=None):
2986 """Return a list of start and end index for the first sequence of
2987 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2988 The text is searched forward from INDEX1."""
2989 return self.tk.splitlist(self.tk.call(
2990 self._w, 'tag', 'nextrange', tagName, index1, index2))
2991 def tag_prevrange(self, tagName, index1, index2=None):
2992 """Return a list of start and end index for the first sequence of
2993 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
2994 The text is searched backwards from INDEX1."""
2995 return self.tk.splitlist(self.tk.call(
2996 self._w, 'tag', 'prevrange', tagName, index1, index2))
2997 def tag_raise(self, tagName, aboveThis=None):
2998 """Change the priority of tag TAGNAME such that it is higher
2999 than the priority of ABOVETHIS."""
3000 self.tk.call(
3001 self._w, 'tag', 'raise', tagName, aboveThis)
3002 def tag_ranges(self, tagName):
3003 """Return a list of ranges of text which have tag TAGNAME."""
3004 return self.tk.splitlist(self.tk.call(
3005 self._w, 'tag', 'ranges', tagName))
3006 def tag_remove(self, tagName, index1, index2=None):
3007 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3008 self.tk.call(
3009 self._w, 'tag', 'remove', tagName, index1, index2)
3010 def window_cget(self, index, option):
3011 """Return the value of OPTION of an embedded window at INDEX."""
3012 if option[:1] != '-':
3013 option = '-' + option
3014 if option[-1:] == '_':
3015 option = option[:-1]
3016 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003017 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003018 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003019 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003020 window_config = window_configure
3021 def window_create(self, index, cnf={}, **kw):
3022 """Create a window at INDEX."""
3023 self.tk.call(
3024 (self._w, 'window', 'create', index)
3025 + self._options(cnf, kw))
3026 def window_names(self):
3027 """Return all names of embedded windows in this widget."""
3028 return self.tk.splitlist(
3029 self.tk.call(self._w, 'window', 'names'))
3030 def xview(self, *what):
3031 """Query and change horizontal position of the view."""
3032 if not what:
3033 return self._getdoubles(self.tk.call(self._w, 'xview'))
3034 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003035 def xview_moveto(self, fraction):
3036 """Adjusts the view in the window so that FRACTION of the
3037 total width of the canvas is off-screen to the left."""
3038 self.tk.call(self._w, 'xview', 'moveto', fraction)
3039 def xview_scroll(self, number, what):
3040 """Shift the x-view according to NUMBER which is measured
3041 in "units" or "pages" (WHAT)."""
3042 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003043 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003044 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003045 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003046 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003047 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003048 def yview_moveto(self, fraction):
3049 """Adjusts the view in the window so that FRACTION of the
3050 total height of the canvas is off-screen to the top."""
3051 self.tk.call(self._w, 'yview', 'moveto', fraction)
3052 def yview_scroll(self, number, what):
3053 """Shift the y-view according to NUMBER which is measured
3054 in "units" or "pages" (WHAT)."""
3055 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003056 def yview_pickplace(self, *what):
3057 """Obsolete function, use see."""
3058 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003059
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003060
Guido van Rossum28574b51996-10-21 15:16:51 +00003061class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003062 """Internal class. It wraps the command in the widget OptionMenu."""
3063 def __init__(self, var, value, callback=None):
3064 self.__value = value
3065 self.__var = var
3066 self.__callback = callback
3067 def __call__(self, *args):
3068 self.__var.set(self.__value)
3069 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003070 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003071
3072class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003073 """OptionMenu which allows the user to select a value from a menu."""
3074 def __init__(self, master, variable, value, *values, **kwargs):
3075 """Construct an optionmenu widget with the parent MASTER, with
3076 the resource textvariable set to VARIABLE, the initially selected
3077 value VALUE, the other menu values VALUES and an additional
3078 keyword argument command."""
3079 kw = {"borderwidth": 2, "textvariable": variable,
3080 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3081 "highlightthickness": 2}
3082 Widget.__init__(self, master, "menubutton", kw)
3083 self.widgetName = 'tk_optionMenu'
3084 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3085 self.menuname = menu._w
3086 # 'command' is the only supported keyword
3087 callback = kwargs.get('command')
3088 if kwargs.has_key('command'):
3089 del kwargs['command']
3090 if kwargs:
3091 raise TclError, 'unknown option -'+kwargs.keys()[0]
3092 menu.add_command(label=value,
3093 command=_setit(variable, value, callback))
3094 for v in values:
3095 menu.add_command(label=v,
3096 command=_setit(variable, v, callback))
3097 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003098
Fredrik Lundh06d28152000-08-09 18:03:12 +00003099 def __getitem__(self, name):
3100 if name == 'menu':
3101 return self.__menu
3102 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003103
Fredrik Lundh06d28152000-08-09 18:03:12 +00003104 def destroy(self):
3105 """Destroy this widget and the associated menu."""
3106 Menubutton.destroy(self)
3107 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003108
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003109class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003110 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003111 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003112 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3113 self.name = None
3114 if not master:
3115 master = _default_root
3116 if not master:
3117 raise RuntimeError, 'Too early to create image'
3118 self.tk = master.tk
3119 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003120 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003121 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003122 # The following is needed for systems where id(x)
3123 # can return a negative number, such as Linux/m68k:
3124 if name[0] == '-': name = '_' + name[1:]
3125 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3126 elif kw: cnf = kw
3127 options = ()
3128 for k, v in cnf.items():
3129 if callable(v):
3130 v = self._register(v)
3131 options = options + ('-'+k, v)
3132 self.tk.call(('image', 'create', imgtype, name,) + options)
3133 self.name = name
3134 def __str__(self): return self.name
3135 def __del__(self):
3136 if self.name:
3137 try:
3138 self.tk.call('image', 'delete', self.name)
3139 except TclError:
3140 # May happen if the root was destroyed
3141 pass
3142 def __setitem__(self, key, value):
3143 self.tk.call(self.name, 'configure', '-'+key, value)
3144 def __getitem__(self, key):
3145 return self.tk.call(self.name, 'configure', '-'+key)
3146 def configure(self, **kw):
3147 """Configure the image."""
3148 res = ()
3149 for k, v in _cnfmerge(kw).items():
3150 if v is not None:
3151 if k[-1] == '_': k = k[:-1]
3152 if callable(v):
3153 v = self._register(v)
3154 res = res + ('-'+k, v)
3155 self.tk.call((self.name, 'config') + res)
3156 config = configure
3157 def height(self):
3158 """Return the height of the image."""
3159 return getint(
3160 self.tk.call('image', 'height', self.name))
3161 def type(self):
3162 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3163 return self.tk.call('image', 'type', self.name)
3164 def width(self):
3165 """Return the width of the image."""
3166 return getint(
3167 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003168
3169class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003170 """Widget which can display colored images in GIF, PPM/PGM format."""
3171 def __init__(self, name=None, cnf={}, master=None, **kw):
3172 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003173
Fredrik Lundh06d28152000-08-09 18:03:12 +00003174 Valid resource names: data, format, file, gamma, height, palette,
3175 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003176 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003177 def blank(self):
3178 """Display a transparent image."""
3179 self.tk.call(self.name, 'blank')
3180 def cget(self, option):
3181 """Return the value of OPTION."""
3182 return self.tk.call(self.name, 'cget', '-' + option)
3183 # XXX config
3184 def __getitem__(self, key):
3185 return self.tk.call(self.name, 'cget', '-' + key)
3186 # XXX copy -from, -to, ...?
3187 def copy(self):
3188 """Return a new PhotoImage with the same image as this widget."""
3189 destImage = PhotoImage()
3190 self.tk.call(destImage, 'copy', self.name)
3191 return destImage
3192 def zoom(self,x,y=''):
3193 """Return a new PhotoImage with the same image as this widget
3194 but zoom it with X and Y."""
3195 destImage = PhotoImage()
3196 if y=='': y=x
3197 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3198 return destImage
3199 def subsample(self,x,y=''):
3200 """Return a new PhotoImage based on the same image as this widget
3201 but use only every Xth or Yth pixel."""
3202 destImage = PhotoImage()
3203 if y=='': y=x
3204 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3205 return destImage
3206 def get(self, x, y):
3207 """Return the color (red, green, blue) of the pixel at X,Y."""
3208 return self.tk.call(self.name, 'get', x, y)
3209 def put(self, data, to=None):
3210 """Put row formated colors to image starting from
3211 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3212 args = (self.name, 'put', data)
3213 if to:
3214 if to[0] == '-to':
3215 to = to[1:]
3216 args = args + ('-to',) + tuple(to)
3217 self.tk.call(args)
3218 # XXX read
3219 def write(self, filename, format=None, from_coords=None):
3220 """Write image to file FILENAME in FORMAT starting from
3221 position FROM_COORDS."""
3222 args = (self.name, 'write', filename)
3223 if format:
3224 args = args + ('-format', format)
3225 if from_coords:
3226 args = args + ('-from',) + tuple(from_coords)
3227 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003228
3229class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003230 """Widget which can display a bitmap."""
3231 def __init__(self, name=None, cnf={}, master=None, **kw):
3232 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003233
Fredrik Lundh06d28152000-08-09 18:03:12 +00003234 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003235 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003236
3237def image_names(): return _default_root.tk.call('image', 'names')
3238def image_types(): return _default_root.tk.call('image', 'types')
3239
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003240
3241class Spinbox(Widget):
3242 """spinbox widget."""
3243 def __init__(self, master=None, cnf={}, **kw):
3244 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003245
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003246 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003247
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003248 activebackground, background, borderwidth,
3249 cursor, exportselection, font, foreground,
3250 highlightbackground, highlightcolor,
3251 highlightthickness, insertbackground,
3252 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003253 insertontime, insertwidth, justify, relief,
3254 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003255 selectbackground, selectborderwidth
3256 selectforeground, takefocus, textvariable
3257 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003258
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003259 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003260
3261 buttonbackground, buttoncursor,
3262 buttondownrelief, buttonuprelief,
3263 command, disabledbackground,
3264 disabledforeground, format, from,
3265 invalidcommand, increment,
3266 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003267 validate, validatecommand values,
3268 width, wrap,
3269 """
3270 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003271
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003272 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003273 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3274 rectangle which encloses the character given by index.
3275
3276 The first two elements of the list give the x and y
3277 coordinates of the upper-left corner of the screen
3278 area covered by the character (in pixels relative
3279 to the widget) and the last two elements give the
3280 width and height of the character, in pixels. The
3281 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003282 visible area of the window.
3283 """
3284 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003285
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003286 def delete(self, first, last=None):
3287 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003288
3289 First is the index of the first character to delete,
3290 and last is the index of the character just after
3291 the last one to delete. If last isn't specified it
3292 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003293 deleted. This command returns an empty string.
3294 """
3295 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003296
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003297 def get(self):
3298 """Returns the spinbox's string"""
3299 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003300
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003301 def icursor(self, index):
3302 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003303
3304 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003305 the character given by index. Returns an empty string
3306 """
3307 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003308
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003309 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003310 """Returns the name of the widget at position x, y
3311
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003312 Return value is one of: none, buttondown, buttonup, entry
3313 """
3314 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003315
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003316 def index(self, index):
3317 """Returns the numerical index corresponding to index
3318 """
3319 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003320
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003321 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003322 """Insert string s at index
3323
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003324 Returns an empty string.
3325 """
3326 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003327
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003328 def invoke(self, element):
3329 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003330
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003331 The element could be buttondown or buttonup
3332 triggering the action associated with it.
3333 """
3334 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003335
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003336 def scan(self, *args):
3337 """Internal function."""
3338 return self._getints(
3339 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003340
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003341 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003342 """Records x and the current view in the spinbox window;
3343
3344 used in conjunction with later scan dragto commands.
3345 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003346 press in the widget. It returns an empty string.
3347 """
3348 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003349
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003350 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003351 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003352 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003353
3354 It then adjusts the view left or right by 10 times the
3355 difference in x-coordinates. This command is typically
3356 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003357 produce the effect of dragging the spinbox at high speed
3358 through the window. The return value is an empty string.
3359 """
3360 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003361
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003362 def selection(self, *args):
3363 """Internal function."""
3364 return self._getints(
3365 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003366
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003367 def selection_adjust(self, index):
3368 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003369 given by index,
3370
3371 Then adjust that end of the selection to be at index
3372 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003373 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003374 select to commands. If the selection isn't currently in
3375 the spinbox, then a new selection is created to include
3376 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003377 anchor point, inclusive. Returns an empty string.
3378 """
3379 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003380
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003381 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003382 """Clear the selection
3383
3384 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003385 command has no effect. Returns an empty string.
3386 """
3387 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003388
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003389 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003390 """Sets or gets the currently selected element.
3391
3392 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003393 displayed depressed
3394 """
3395 return self.selection("element", element)
3396
3397###########################################################################
3398
3399class LabelFrame(Widget):
3400 """labelframe widget."""
3401 def __init__(self, master=None, cnf={}, **kw):
3402 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003403
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003404 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003405
3406 borderwidth, cursor, font, foreground,
3407 highlightbackground, highlightcolor,
3408 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003409 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003410
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003411 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003412
3413 background, class, colormap, container,
3414 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003415 visual, width
3416 """
3417 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003418
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003419########################################################################
3420
3421class PanedWindow(Widget):
3422 """panedwindow widget."""
3423 def __init__(self, master=None, cnf={}, **kw):
3424 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003425
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003426 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003427
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003428 background, borderwidth, cursor, height,
3429 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003430
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003431 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003432
3433 handlepad, handlesize, opaqueresize,
3434 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003435 sashwidth, showhandle,
3436 """
3437 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3438
3439 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003440 """Add a child widget to the panedwindow in a new pane.
3441
3442 The child argument is the name of the child widget
3443 followed by pairs of arguments that specify how to
3444 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003445 accepted by the configure subcommand.
3446 """
3447 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003448
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003449 def remove(self, child):
3450 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003451
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003452 All geometry management options for child will be forgotten.
3453 """
3454 self.tk.call(self._w, 'forget', child)
3455 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003456
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003457 def identify(self, x, y):
3458 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003459
3460 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003461 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003462 handle, and a word indicating whether it is over a sash
3463 or a handle, such as {0 sash} or {2 handle}. If the point
3464 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003465 an empty list.
3466 """
3467 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003468
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003469 def proxy(self, *args):
3470 """Internal function."""
3471 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003472 self.tk.call((self._w, 'proxy') + args)) or ()
3473
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003474 def proxy_coord(self):
3475 """Return the x and y pair of the most recent proxy location
3476 """
3477 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003478
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003479 def proxy_forget(self):
3480 """Remove the proxy from the display.
3481 """
3482 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003483
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003484 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003485 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003486 """
3487 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003488
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003489 def sash(self, *args):
3490 """Internal function."""
3491 return self._getints(
3492 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003493
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003494 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003495 """Return the current x and y pair for the sash given by index.
3496
3497 Index must be an integer between 0 and 1 less than the
3498 number of panes in the panedwindow. The coordinates given are
3499 those of the top left corner of the region containing the sash.
3500 pathName sash dragto index x y This command computes the
3501 difference between the given coordinates and the coordinates
3502 given to the last sash coord command for the given sash. It then
3503 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003504 empty string.
3505 """
3506 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003507
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003508 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003509 """Records x and y for the sash given by index;
3510
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003511 Used in conjunction with later dragto commands to move the sash.
3512 """
3513 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003514
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003515 def sash_place(self, index, x, y):
3516 """Place the sash given by index at the given coordinates
3517 """
3518 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003519
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003520 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521 """Query a management option for window.
3522
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003523 Option may be any value allowed by the paneconfigure subcommand
3524 """
3525 return self.tk.call(
3526 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003527
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003528 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003529 """Query or modify the management options for window.
3530
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003531 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003532 of the available options for pathName. If option is
3533 specified with no value, then the command returns a list
3534 describing the one named option (this list will be identical
3535 to the corresponding sublist of the value returned if no
3536 option is specified). If one or more option-value pairs are
3537 specified, then the command modifies the given widget
3538 option(s) to have the given value(s); in this case the
3539 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003540 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003541
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003542 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003543 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003544 should be the name of a window already managed by pathName.
3545 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003546 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003547 should be the name of a window already managed by pathName.
3548 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003549 Specify a height for the window. The height will be the
3550 outer dimension of the window including its border, if
3551 any. If size is an empty string, or if -height is not
3552 specified, then the height requested internally by the
3553 window will be used initially; the height may later be
3554 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003555 Size may be any value accepted by Tk_GetPixels.
3556 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003557 Specifies that the size of the window cannot be made
3558 less than n. This constraint only affects the size of
3559 the widget in the paned dimension -- the x dimension
3560 for horizontal panedwindows, the y dimension for
3561 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003562 Tk_GetPixels.
3563 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003564 Specifies a non-negative value indicating how much
3565 extra space to leave on each side of the window in
3566 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003567 accepted by Tk_GetPixels.
3568 pady n
3569 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003570 extra space to leave on each side of the window in
3571 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003572 accepted by Tk_GetPixels.
3573 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003574 If a window's pane is larger than the requested
3575 dimensions of the window, this option may be used
3576 to position (or stretch) the window within its pane.
3577 Style is a string that contains zero or more of the
3578 characters n, s, e or w. The string can optionally
3579 contains spaces or commas, but they are ignored. Each
3580 letter refers to a side (north, south, east, or west)
3581 that the window will "stick" to. If both n and s
3582 (or e and w) are specified, the window will be
3583 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003584 its cavity.
3585 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003586 Specify a width for the window. The width will be
3587 the outer dimension of the window including its
3588 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003589 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003590 internally by the window will be used initially; the
3591 width may later be adjusted by the movement of sashes
3592 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003593 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003594
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003595 """
3596 if cnf is None and not kw:
3597 cnf = {}
3598 for x in self.tk.split(
3599 self.tk.call(self._w,
3600 'paneconfigure', tagOrId)):
3601 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3602 return cnf
3603 if type(cnf) == StringType and not kw:
3604 x = self.tk.split(self.tk.call(
3605 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3606 return (x[0][1:],) + x[1:]
3607 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3608 self._options(cnf, kw))
3609 paneconfig = paneconfigure
3610
3611 def panes(self):
3612 """Returns an ordered list of the child panes."""
3613 return self.tk.call(self._w, 'panes')
3614
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003615######################################################################
3616# Extensions:
3617
3618class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003619 def __init__(self, master=None, cnf={}, **kw):
3620 Widget.__init__(self, master, 'studbutton', cnf, kw)
3621 self.bind('<Any-Enter>', self.tkButtonEnter)
3622 self.bind('<Any-Leave>', self.tkButtonLeave)
3623 self.bind('<1>', self.tkButtonDown)
3624 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003625
3626class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003627 def __init__(self, master=None, cnf={}, **kw):
3628 Widget.__init__(self, master, 'tributton', cnf, kw)
3629 self.bind('<Any-Enter>', self.tkButtonEnter)
3630 self.bind('<Any-Leave>', self.tkButtonLeave)
3631 self.bind('<1>', self.tkButtonDown)
3632 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3633 self['fg'] = self['bg']
3634 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003635
Guido van Rossumc417ef81996-08-21 23:38:59 +00003636######################################################################
3637# Test:
3638
3639def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003640 root = Tk()
3641 text = "This is Tcl/Tk version %s" % TclVersion
3642 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003643 try:
3644 text = text + unicode("\nThis should be a cedilla: \347",
3645 "iso-8859-1")
3646 except NameError:
3647 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003648 label = Label(root, text=text)
3649 label.pack()
3650 test = Button(root, text="Click me!",
3651 command=lambda root=root: root.test.configure(
3652 text="[%s]" % root.test['text']))
3653 test.pack()
3654 root.test = test
3655 quit = Button(root, text="QUIT", command=root.destroy)
3656 quit.pack()
3657 # The following three commands are needed so the window pops
3658 # up on top on Windows...
3659 root.iconify()
3660 root.update()
3661 root.deiconify()
3662 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003663
3664if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003665 _test()