blob: 0ba954ee6c3dff2d7914f4397e310b121286e3ee [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
Walter Dörwald966c2642005-11-09 17:12:43 +0000133 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000134 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:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000452 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000453 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000454 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000455 finally:
456 try:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000457 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000458 except TclError:
459 pass
460 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000461 return self.tk.call('after', ms, name)
462 def after_idle(self, func, *args):
463 """Call FUNC once if the Tcl main loop has no event to
464 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000465
Fredrik Lundh06d28152000-08-09 18:03:12 +0000466 Return an identifier to cancel the scheduling with
467 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000468 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000469 def after_cancel(self, id):
470 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000471
Fredrik Lundh06d28152000-08-09 18:03:12 +0000472 Identifier returned by after or after_idle must be
473 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000474 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000475 data = self.tk.call('after', 'info', id)
476 # In Tk 8.3, splitlist returns: (script, type)
477 # In Tk 8.4, splitlist may return (script, type) or (script,)
478 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000479 self.deletecommand(script)
480 except TclError:
481 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000482 self.tk.call('after', 'cancel', id)
483 def bell(self, displayof=0):
484 """Ring a display's bell."""
485 self.tk.call(('bell',) + self._displayof(displayof))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000486
Fredrik Lundh06d28152000-08-09 18:03:12 +0000487 # Clipboard handling:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000488 def clipboard_get(self, **kw):
489 """Retrieve data from the clipboard on window's display.
490
491 The window keyword defaults to the root window of the Tkinter
492 application.
493
494 The type keyword specifies the form in which the data is
495 to be returned and should be an atom name such as STRING
496 or FILE_NAME. Type defaults to STRING.
497
498 This command is equivalent to:
499
500 selection_get(CLIPBOARD)
501 """
502 return self.tk.call(('clipboard', 'get') + self._options(kw))
503
Fredrik Lundh06d28152000-08-09 18:03:12 +0000504 def clipboard_clear(self, **kw):
505 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000506
Fredrik Lundh06d28152000-08-09 18:03:12 +0000507 A widget specified for the optional displayof keyword
508 argument specifies the target display."""
509 if not kw.has_key('displayof'): kw['displayof'] = self._w
510 self.tk.call(('clipboard', 'clear') + self._options(kw))
511 def clipboard_append(self, string, **kw):
512 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000513
Fredrik Lundh06d28152000-08-09 18:03:12 +0000514 A widget specified at the optional displayof keyword
515 argument specifies the target display. The clipboard
516 can be retrieved with selection_get."""
517 if not kw.has_key('displayof'): kw['displayof'] = self._w
518 self.tk.call(('clipboard', 'append') + self._options(kw)
519 + ('--', string))
520 # XXX grab current w/o window argument
521 def grab_current(self):
522 """Return widget which has currently the grab in this application
523 or None."""
524 name = self.tk.call('grab', 'current', self._w)
525 if not name: return None
526 return self._nametowidget(name)
527 def grab_release(self):
528 """Release grab for this widget if currently set."""
529 self.tk.call('grab', 'release', self._w)
530 def grab_set(self):
531 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000532
Fredrik Lundh06d28152000-08-09 18:03:12 +0000533 A grab directs all events to this and descendant
534 widgets in the application."""
535 self.tk.call('grab', 'set', self._w)
536 def grab_set_global(self):
537 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000538
Fredrik Lundh06d28152000-08-09 18:03:12 +0000539 A global grab directs all events to this and
540 descendant widgets on the display. Use with caution -
541 other applications do not get events anymore."""
542 self.tk.call('grab', 'set', '-global', self._w)
543 def grab_status(self):
544 """Return None, "local" or "global" if this widget has
545 no, a local or a global grab."""
546 status = self.tk.call('grab', 'status', self._w)
547 if status == 'none': status = None
548 return status
549 def lower(self, belowThis=None):
550 """Lower this widget in the stacking order."""
551 self.tk.call('lower', self._w, belowThis)
552 def option_add(self, pattern, value, priority = None):
553 """Set a VALUE (second parameter) for an option
554 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000555
Fredrik Lundh06d28152000-08-09 18:03:12 +0000556 An optional third parameter gives the numeric priority
557 (defaults to 80)."""
558 self.tk.call('option', 'add', pattern, value, priority)
559 def option_clear(self):
560 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000561
Fredrik Lundh06d28152000-08-09 18:03:12 +0000562 It will be reloaded if option_add is called."""
563 self.tk.call('option', 'clear')
564 def option_get(self, name, className):
565 """Return the value for an option NAME for this widget
566 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000567
Fredrik Lundh06d28152000-08-09 18:03:12 +0000568 Values with higher priority override lower values."""
569 return self.tk.call('option', 'get', self._w, name, className)
570 def option_readfile(self, fileName, priority = None):
571 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000572
Fredrik Lundh06d28152000-08-09 18:03:12 +0000573 An optional second parameter gives the numeric
574 priority."""
575 self.tk.call('option', 'readfile', fileName, priority)
576 def selection_clear(self, **kw):
577 """Clear the current X selection."""
578 if not kw.has_key('displayof'): kw['displayof'] = self._w
579 self.tk.call(('selection', 'clear') + self._options(kw))
580 def selection_get(self, **kw):
581 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000582
Fredrik Lundh06d28152000-08-09 18:03:12 +0000583 A keyword parameter selection specifies the name of
584 the selection and defaults to PRIMARY. A keyword
585 parameter displayof specifies a widget on the display
586 to use."""
587 if not kw.has_key('displayof'): kw['displayof'] = self._w
588 return self.tk.call(('selection', 'get') + self._options(kw))
589 def selection_handle(self, command, **kw):
590 """Specify a function COMMAND to call if the X
591 selection owned by this widget is queried by another
592 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000593
Fredrik Lundh06d28152000-08-09 18:03:12 +0000594 This function must return the contents of the
595 selection. The function will be called with the
596 arguments OFFSET and LENGTH which allows the chunking
597 of very long selections. The following keyword
598 parameters can be provided:
599 selection - name of the selection (default PRIMARY),
600 type - type of the selection (e.g. STRING, FILE_NAME)."""
601 name = self._register(command)
602 self.tk.call(('selection', 'handle') + self._options(kw)
603 + (self._w, name))
604 def selection_own(self, **kw):
605 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000606
Fredrik Lundh06d28152000-08-09 18:03:12 +0000607 A keyword parameter selection specifies the name of
608 the selection (default PRIMARY)."""
609 self.tk.call(('selection', 'own') +
610 self._options(kw) + (self._w,))
611 def selection_own_get(self, **kw):
612 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000613
Fredrik Lundh06d28152000-08-09 18:03:12 +0000614 The following keyword parameter can
615 be provided:
616 selection - name of the selection (default PRIMARY),
617 type - type of the selection (e.g. STRING, FILE_NAME)."""
618 if not kw.has_key('displayof'): kw['displayof'] = self._w
619 name = self.tk.call(('selection', 'own') + self._options(kw))
620 if not name: return None
621 return self._nametowidget(name)
622 def send(self, interp, cmd, *args):
623 """Send Tcl command CMD to different interpreter INTERP to be executed."""
624 return self.tk.call(('send', interp, cmd) + args)
625 def lower(self, belowThis=None):
626 """Lower this widget in the stacking order."""
627 self.tk.call('lower', self._w, belowThis)
628 def tkraise(self, aboveThis=None):
629 """Raise this widget in the stacking order."""
630 self.tk.call('raise', self._w, aboveThis)
631 lift = tkraise
632 def colormodel(self, value=None):
633 """Useless. Not implemented in Tk."""
634 return self.tk.call('tk', 'colormodel', self._w, value)
635 def winfo_atom(self, name, displayof=0):
636 """Return integer which represents atom NAME."""
637 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
638 return getint(self.tk.call(args))
639 def winfo_atomname(self, id, displayof=0):
640 """Return name of atom with identifier ID."""
641 args = ('winfo', 'atomname') \
642 + self._displayof(displayof) + (id,)
643 return self.tk.call(args)
644 def winfo_cells(self):
645 """Return number of cells in the colormap for this widget."""
646 return getint(
647 self.tk.call('winfo', 'cells', self._w))
648 def winfo_children(self):
649 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000650 result = []
651 for child in self.tk.splitlist(
652 self.tk.call('winfo', 'children', self._w)):
653 try:
654 # Tcl sometimes returns extra windows, e.g. for
655 # menus; those need to be skipped
656 result.append(self._nametowidget(child))
657 except KeyError:
658 pass
659 return result
660
Fredrik Lundh06d28152000-08-09 18:03:12 +0000661 def winfo_class(self):
662 """Return window class name of this widget."""
663 return self.tk.call('winfo', 'class', self._w)
664 def winfo_colormapfull(self):
665 """Return true if at the last color request the colormap was full."""
666 return self.tk.getboolean(
667 self.tk.call('winfo', 'colormapfull', self._w))
668 def winfo_containing(self, rootX, rootY, displayof=0):
669 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
670 args = ('winfo', 'containing') \
671 + self._displayof(displayof) + (rootX, rootY)
672 name = self.tk.call(args)
673 if not name: return None
674 return self._nametowidget(name)
675 def winfo_depth(self):
676 """Return the number of bits per pixel."""
677 return getint(self.tk.call('winfo', 'depth', self._w))
678 def winfo_exists(self):
679 """Return true if this widget exists."""
680 return getint(
681 self.tk.call('winfo', 'exists', self._w))
682 def winfo_fpixels(self, number):
683 """Return the number of pixels for the given distance NUMBER
684 (e.g. "3c") as float."""
685 return getdouble(self.tk.call(
686 'winfo', 'fpixels', self._w, number))
687 def winfo_geometry(self):
688 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
689 return self.tk.call('winfo', 'geometry', self._w)
690 def winfo_height(self):
691 """Return height of this widget."""
692 return getint(
693 self.tk.call('winfo', 'height', self._w))
694 def winfo_id(self):
695 """Return identifier ID for this widget."""
696 return self.tk.getint(
697 self.tk.call('winfo', 'id', self._w))
698 def winfo_interps(self, displayof=0):
699 """Return the name of all Tcl interpreters for this display."""
700 args = ('winfo', 'interps') + self._displayof(displayof)
701 return self.tk.splitlist(self.tk.call(args))
702 def winfo_ismapped(self):
703 """Return true if this widget is mapped."""
704 return getint(
705 self.tk.call('winfo', 'ismapped', self._w))
706 def winfo_manager(self):
707 """Return the window mananger name for this widget."""
708 return self.tk.call('winfo', 'manager', self._w)
709 def winfo_name(self):
710 """Return the name of this widget."""
711 return self.tk.call('winfo', 'name', self._w)
712 def winfo_parent(self):
713 """Return the name of the parent of this widget."""
714 return self.tk.call('winfo', 'parent', self._w)
715 def winfo_pathname(self, id, displayof=0):
716 """Return the pathname of the widget given by ID."""
717 args = ('winfo', 'pathname') \
718 + self._displayof(displayof) + (id,)
719 return self.tk.call(args)
720 def winfo_pixels(self, number):
721 """Rounded integer value of winfo_fpixels."""
722 return getint(
723 self.tk.call('winfo', 'pixels', self._w, number))
724 def winfo_pointerx(self):
725 """Return the x coordinate of the pointer on the root window."""
726 return getint(
727 self.tk.call('winfo', 'pointerx', self._w))
728 def winfo_pointerxy(self):
729 """Return a tuple of x and y coordinates of the pointer on the root window."""
730 return self._getints(
731 self.tk.call('winfo', 'pointerxy', self._w))
732 def winfo_pointery(self):
733 """Return the y coordinate of the pointer on the root window."""
734 return getint(
735 self.tk.call('winfo', 'pointery', self._w))
736 def winfo_reqheight(self):
737 """Return requested height of this widget."""
738 return getint(
739 self.tk.call('winfo', 'reqheight', self._w))
740 def winfo_reqwidth(self):
741 """Return requested width of this widget."""
742 return getint(
743 self.tk.call('winfo', 'reqwidth', self._w))
744 def winfo_rgb(self, color):
745 """Return tuple of decimal values for red, green, blue for
746 COLOR in this widget."""
747 return self._getints(
748 self.tk.call('winfo', 'rgb', self._w, color))
749 def winfo_rootx(self):
750 """Return x coordinate of upper left corner of this widget on the
751 root window."""
752 return getint(
753 self.tk.call('winfo', 'rootx', self._w))
754 def winfo_rooty(self):
755 """Return y coordinate of upper left corner of this widget on the
756 root window."""
757 return getint(
758 self.tk.call('winfo', 'rooty', self._w))
759 def winfo_screen(self):
760 """Return the screen name of this widget."""
761 return self.tk.call('winfo', 'screen', self._w)
762 def winfo_screencells(self):
763 """Return the number of the cells in the colormap of the screen
764 of this widget."""
765 return getint(
766 self.tk.call('winfo', 'screencells', self._w))
767 def winfo_screendepth(self):
768 """Return the number of bits per pixel of the root window of the
769 screen of this widget."""
770 return getint(
771 self.tk.call('winfo', 'screendepth', self._w))
772 def winfo_screenheight(self):
773 """Return the number of pixels of the height of the screen of this widget
774 in pixel."""
775 return getint(
776 self.tk.call('winfo', 'screenheight', self._w))
777 def winfo_screenmmheight(self):
778 """Return the number of pixels of the height of the screen of
779 this widget in mm."""
780 return getint(
781 self.tk.call('winfo', 'screenmmheight', self._w))
782 def winfo_screenmmwidth(self):
783 """Return the number of pixels of the width of the screen of
784 this widget in mm."""
785 return getint(
786 self.tk.call('winfo', 'screenmmwidth', self._w))
787 def winfo_screenvisual(self):
788 """Return one of the strings directcolor, grayscale, pseudocolor,
789 staticcolor, staticgray, or truecolor for the default
790 colormodel of this screen."""
791 return self.tk.call('winfo', 'screenvisual', self._w)
792 def winfo_screenwidth(self):
793 """Return the number of pixels of the width of the screen of
794 this widget in pixel."""
795 return getint(
796 self.tk.call('winfo', 'screenwidth', self._w))
797 def winfo_server(self):
798 """Return information of the X-Server of the screen of this widget in
799 the form "XmajorRminor vendor vendorVersion"."""
800 return self.tk.call('winfo', 'server', self._w)
801 def winfo_toplevel(self):
802 """Return the toplevel widget of this widget."""
803 return self._nametowidget(self.tk.call(
804 'winfo', 'toplevel', self._w))
805 def winfo_viewable(self):
806 """Return true if the widget and all its higher ancestors are mapped."""
807 return getint(
808 self.tk.call('winfo', 'viewable', self._w))
809 def winfo_visual(self):
810 """Return one of the strings directcolor, grayscale, pseudocolor,
811 staticcolor, staticgray, or truecolor for the
812 colormodel of this widget."""
813 return self.tk.call('winfo', 'visual', self._w)
814 def winfo_visualid(self):
815 """Return the X identifier for the visual for this widget."""
816 return self.tk.call('winfo', 'visualid', self._w)
817 def winfo_visualsavailable(self, includeids=0):
818 """Return a list of all visuals available for the screen
819 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000820
Fredrik Lundh06d28152000-08-09 18:03:12 +0000821 Each item in the list consists of a visual name (see winfo_visual), a
822 depth and if INCLUDEIDS=1 is given also the X identifier."""
823 data = self.tk.split(
824 self.tk.call('winfo', 'visualsavailable', self._w,
825 includeids and 'includeids' or None))
Fredrik Lundh24037f72000-08-09 19:26:47 +0000826 if type(data) is StringType:
827 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000828 return map(self.__winfo_parseitem, data)
829 def __winfo_parseitem(self, t):
830 """Internal function."""
831 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
832 def __winfo_getint(self, x):
833 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000834 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000835 def winfo_vrootheight(self):
836 """Return the height of the virtual root window associated with this
837 widget in pixels. If there is no virtual root window return the
838 height of the screen."""
839 return getint(
840 self.tk.call('winfo', 'vrootheight', self._w))
841 def winfo_vrootwidth(self):
842 """Return the width of the virtual root window associated with this
843 widget in pixel. If there is no virtual root window return the
844 width of the screen."""
845 return getint(
846 self.tk.call('winfo', 'vrootwidth', self._w))
847 def winfo_vrootx(self):
848 """Return the x offset of the virtual root relative to the root
849 window of the screen of this widget."""
850 return getint(
851 self.tk.call('winfo', 'vrootx', self._w))
852 def winfo_vrooty(self):
853 """Return the y offset of the virtual root relative to the root
854 window of the screen of this widget."""
855 return getint(
856 self.tk.call('winfo', 'vrooty', self._w))
857 def winfo_width(self):
858 """Return the width of this widget."""
859 return getint(
860 self.tk.call('winfo', 'width', self._w))
861 def winfo_x(self):
862 """Return the x coordinate of the upper left corner of this widget
863 in the parent."""
864 return getint(
865 self.tk.call('winfo', 'x', self._w))
866 def winfo_y(self):
867 """Return the y coordinate of the upper left corner of this widget
868 in the parent."""
869 return getint(
870 self.tk.call('winfo', 'y', self._w))
871 def update(self):
872 """Enter event loop until all pending events have been processed by Tcl."""
873 self.tk.call('update')
874 def update_idletasks(self):
875 """Enter event loop until all idle callbacks have been called. This
876 will update the display of windows but not process events caused by
877 the user."""
878 self.tk.call('update', 'idletasks')
879 def bindtags(self, tagList=None):
880 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000881
Fredrik Lundh06d28152000-08-09 18:03:12 +0000882 With no argument return the list of all bindtags associated with
883 this widget. With a list of strings as argument the bindtags are
884 set to this list. The bindtags determine in which order events are
885 processed (see bind)."""
886 if tagList is None:
887 return self.tk.splitlist(
888 self.tk.call('bindtags', self._w))
889 else:
890 self.tk.call('bindtags', self._w, tagList)
891 def _bind(self, what, sequence, func, add, needcleanup=1):
892 """Internal function."""
893 if type(func) is StringType:
894 self.tk.call(what + (sequence, func))
895 elif func:
896 funcid = self._register(func, self._substitute,
897 needcleanup)
898 cmd = ('%sif {"[%s %s]" == "break"} break\n'
899 %
900 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000901 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000902 self.tk.call(what + (sequence, cmd))
903 return funcid
904 elif sequence:
905 return self.tk.call(what + (sequence,))
906 else:
907 return self.tk.splitlist(self.tk.call(what))
908 def bind(self, sequence=None, func=None, add=None):
909 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000910
Fredrik Lundh06d28152000-08-09 18:03:12 +0000911 SEQUENCE is a string of concatenated event
912 patterns. An event pattern is of the form
913 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
914 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
915 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
916 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
917 Mod1, M1. TYPE is one of Activate, Enter, Map,
918 ButtonPress, Button, Expose, Motion, ButtonRelease
919 FocusIn, MouseWheel, Circulate, FocusOut, Property,
920 Colormap, Gravity Reparent, Configure, KeyPress, Key,
921 Unmap, Deactivate, KeyRelease Visibility, Destroy,
922 Leave and DETAIL is the button number for ButtonPress,
923 ButtonRelease and DETAIL is the Keysym for KeyPress and
924 KeyRelease. Examples are
925 <Control-Button-1> for pressing Control and mouse button 1 or
926 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
927 An event pattern can also be a virtual event of the form
928 <<AString>> where AString can be arbitrary. This
929 event can be generated by event_generate.
930 If events are concatenated they must appear shortly
931 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000932
Fredrik Lundh06d28152000-08-09 18:03:12 +0000933 FUNC will be called if the event sequence occurs with an
934 instance of Event as argument. If the return value of FUNC is
935 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000936
Fredrik Lundh06d28152000-08-09 18:03:12 +0000937 An additional boolean parameter ADD specifies whether FUNC will
938 be called additionally to the other bound function or whether
939 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000940
Fredrik Lundh06d28152000-08-09 18:03:12 +0000941 Bind will return an identifier to allow deletion of the bound function with
942 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000943
Fredrik Lundh06d28152000-08-09 18:03:12 +0000944 If FUNC or SEQUENCE is omitted the bound function or list
945 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000946
Fredrik Lundh06d28152000-08-09 18:03:12 +0000947 return self._bind(('bind', self._w), sequence, func, add)
948 def unbind(self, sequence, funcid=None):
949 """Unbind for this widget for event SEQUENCE the
950 function identified with FUNCID."""
951 self.tk.call('bind', self._w, sequence, '')
952 if funcid:
953 self.deletecommand(funcid)
954 def bind_all(self, sequence=None, func=None, add=None):
955 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
956 An additional boolean parameter ADD specifies whether FUNC will
957 be called additionally to the other bound function or whether
958 it will replace the previous function. See bind for the return value."""
959 return self._bind(('bind', 'all'), sequence, func, add, 0)
960 def unbind_all(self, sequence):
961 """Unbind for all widgets for event SEQUENCE all functions."""
962 self.tk.call('bind', 'all' , sequence, '')
963 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000964
Fredrik Lundh06d28152000-08-09 18:03:12 +0000965 """Bind to widgets with bindtag CLASSNAME at event
966 SEQUENCE a call of function FUNC. An additional
967 boolean parameter ADD specifies whether FUNC will be
968 called additionally to the other bound function or
969 whether it will replace the previous function. See bind for
970 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000971
Fredrik Lundh06d28152000-08-09 18:03:12 +0000972 return self._bind(('bind', className), sequence, func, add, 0)
973 def unbind_class(self, className, sequence):
974 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
975 all functions."""
976 self.tk.call('bind', className , sequence, '')
977 def mainloop(self, n=0):
978 """Call the mainloop of Tk."""
979 self.tk.mainloop(n)
980 def quit(self):
981 """Quit the Tcl interpreter. All widgets will be destroyed."""
982 self.tk.quit()
983 def _getints(self, string):
984 """Internal function."""
985 if string:
986 return tuple(map(getint, self.tk.splitlist(string)))
987 def _getdoubles(self, string):
988 """Internal function."""
989 if string:
990 return tuple(map(getdouble, self.tk.splitlist(string)))
991 def _getboolean(self, string):
992 """Internal function."""
993 if string:
994 return self.tk.getboolean(string)
995 def _displayof(self, displayof):
996 """Internal function."""
997 if displayof:
998 return ('-displayof', displayof)
999 if displayof is None:
1000 return ('-displayof', self._w)
1001 return ()
1002 def _options(self, cnf, kw = None):
1003 """Internal function."""
1004 if kw:
1005 cnf = _cnfmerge((cnf, kw))
1006 else:
1007 cnf = _cnfmerge(cnf)
1008 res = ()
1009 for k, v in cnf.items():
1010 if v is not None:
1011 if k[-1] == '_': k = k[:-1]
1012 if callable(v):
1013 v = self._register(v)
1014 res = res + ('-'+k, v)
1015 return res
1016 def nametowidget(self, name):
1017 """Return the Tkinter instance of a widget identified by
1018 its Tcl name NAME."""
1019 w = self
1020 if name[0] == '.':
1021 w = w._root()
1022 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001023 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +00001024 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001025 if i >= 0:
1026 name, tail = name[:i], name[i+1:]
1027 else:
1028 tail = ''
1029 w = w.children[name]
1030 name = tail
1031 return w
1032 _nametowidget = nametowidget
1033 def _register(self, func, subst=None, needcleanup=1):
1034 """Return a newly created Tcl function. If this
1035 function is called, the Python function FUNC will
1036 be executed. An optional function SUBST can
1037 be given which will be executed before FUNC."""
1038 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001039 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001040 try:
1041 func = func.im_func
1042 except AttributeError:
1043 pass
1044 try:
1045 name = name + func.__name__
1046 except AttributeError:
1047 pass
1048 self.tk.createcommand(name, f)
1049 if needcleanup:
1050 if self._tclCommands is None:
1051 self._tclCommands = []
1052 self._tclCommands.append(name)
1053 #print '+ Tkinter created command', name
1054 return name
1055 register = _register
1056 def _root(self):
1057 """Internal function."""
1058 w = self
1059 while w.master: w = w.master
1060 return w
1061 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1062 '%s', '%t', '%w', '%x', '%y',
1063 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001064 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001065 def _substitute(self, *args):
1066 """Internal function."""
1067 if len(args) != len(self._subst_format): return args
1068 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001069
Fredrik Lundh06d28152000-08-09 18:03:12 +00001070 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001071 def getint_event(s):
1072 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1073 try:
1074 return int(s)
1075 except ValueError:
1076 return s
1077
Fredrik Lundh06d28152000-08-09 18:03:12 +00001078 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1079 # Missing: (a, c, d, m, o, v, B, R)
1080 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001081 # serial field: valid vor all events
1082 # number of button: ButtonPress and ButtonRelease events only
1083 # height field: Configure, ConfigureRequest, Create,
1084 # ResizeRequest, and Expose events only
1085 # keycode field: KeyPress and KeyRelease events only
1086 # time field: "valid for events that contain a time field"
1087 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1088 # and Expose events only
1089 # x field: "valid for events that contain a x field"
1090 # y field: "valid for events that contain a y field"
1091 # keysym as decimal: KeyPress and KeyRelease events only
1092 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1093 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001094 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001095 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001096 try: e.focus = getboolean(f)
1097 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001098 e.height = getint_event(h)
1099 e.keycode = getint_event(k)
1100 e.state = getint_event(s)
1101 e.time = getint_event(t)
1102 e.width = getint_event(w)
1103 e.x = getint_event(x)
1104 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001105 e.char = A
1106 try: e.send_event = getboolean(E)
1107 except TclError: pass
1108 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001109 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001110 e.type = T
1111 try:
1112 e.widget = self._nametowidget(W)
1113 except KeyError:
1114 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001115 e.x_root = getint_event(X)
1116 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001117 try:
1118 e.delta = getint(D)
1119 except ValueError:
1120 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001121 return (e,)
1122 def _report_exception(self):
1123 """Internal function."""
1124 import sys
Neal Norwitzac3625f2006-03-17 05:49:33 +00001125 exc, val, tb = sys.exc_info()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001126 root = self._root()
1127 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001128 def _configure(self, cmd, cnf, kw):
1129 """Internal function."""
1130 if kw:
1131 cnf = _cnfmerge((cnf, kw))
1132 elif cnf:
1133 cnf = _cnfmerge(cnf)
1134 if cnf is None:
1135 cnf = {}
1136 for x in self.tk.split(
1137 self.tk.call(_flatten((self._w, cmd)))):
1138 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1139 return cnf
1140 if type(cnf) is StringType:
1141 x = self.tk.split(
1142 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1143 return (x[0][1:],) + x[1:]
1144 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001145 # These used to be defined in Widget:
1146 def configure(self, cnf=None, **kw):
1147 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001148
Fredrik Lundh06d28152000-08-09 18:03:12 +00001149 The values for resources are specified as keyword
1150 arguments. To get an overview about
1151 the allowed keyword arguments call the method keys.
1152 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001153 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001154 config = configure
1155 def cget(self, key):
1156 """Return the resource value for a KEY given as string."""
1157 return self.tk.call(self._w, 'cget', '-' + key)
1158 __getitem__ = cget
1159 def __setitem__(self, key, value):
1160 self.configure({key: value})
1161 def keys(self):
1162 """Return a list of all resource names of this widget."""
1163 return map(lambda x: x[0][1:],
1164 self.tk.split(self.tk.call(self._w, 'configure')))
1165 def __str__(self):
1166 """Return the window path name of this widget."""
1167 return self._w
1168 # Pack methods that apply to the master
1169 _noarg_ = ['_noarg_']
1170 def pack_propagate(self, flag=_noarg_):
1171 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001172
Fredrik Lundh06d28152000-08-09 18:03:12 +00001173 A boolean argument specifies whether the geometry information
1174 of the slaves will determine the size of this widget. If no argument
1175 is given the current setting will be returned.
1176 """
1177 if flag is Misc._noarg_:
1178 return self._getboolean(self.tk.call(
1179 'pack', 'propagate', self._w))
1180 else:
1181 self.tk.call('pack', 'propagate', self._w, flag)
1182 propagate = pack_propagate
1183 def pack_slaves(self):
1184 """Return a list of all slaves of this widget
1185 in its packing order."""
1186 return map(self._nametowidget,
1187 self.tk.splitlist(
1188 self.tk.call('pack', 'slaves', self._w)))
1189 slaves = pack_slaves
1190 # Place method that applies to the master
1191 def place_slaves(self):
1192 """Return a list of all slaves of this widget
1193 in its packing order."""
1194 return map(self._nametowidget,
1195 self.tk.splitlist(
1196 self.tk.call(
1197 'place', 'slaves', self._w)))
1198 # Grid methods that apply to the master
1199 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1200 """Return a tuple of integer coordinates for the bounding
1201 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001202
Fredrik Lundh06d28152000-08-09 18:03:12 +00001203 If COLUMN, ROW is given the bounding box applies from
1204 the cell with row and column 0 to the specified
1205 cell. If COL2 and ROW2 are given the bounding box
1206 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001207
Fredrik Lundh06d28152000-08-09 18:03:12 +00001208 The returned integers specify the offset of the upper left
1209 corner in the master widget and the width and height.
1210 """
1211 args = ('grid', 'bbox', self._w)
1212 if column is not None and row is not None:
1213 args = args + (column, row)
1214 if col2 is not None and row2 is not None:
1215 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001216 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001217
Fredrik Lundh06d28152000-08-09 18:03:12 +00001218 bbox = grid_bbox
1219 def _grid_configure(self, command, index, cnf, kw):
1220 """Internal function."""
1221 if type(cnf) is StringType and not kw:
1222 if cnf[-1:] == '_':
1223 cnf = cnf[:-1]
1224 if cnf[:1] != '-':
1225 cnf = '-'+cnf
1226 options = (cnf,)
1227 else:
1228 options = self._options(cnf, kw)
1229 if not options:
1230 res = self.tk.call('grid',
1231 command, self._w, index)
1232 words = self.tk.splitlist(res)
1233 dict = {}
1234 for i in range(0, len(words), 2):
1235 key = words[i][1:]
1236 value = words[i+1]
1237 if not value:
1238 value = None
1239 elif '.' in value:
1240 value = getdouble(value)
1241 else:
1242 value = getint(value)
1243 dict[key] = value
1244 return dict
1245 res = self.tk.call(
1246 ('grid', command, self._w, index)
1247 + options)
1248 if len(options) == 1:
1249 if not res: return None
1250 # In Tk 7.5, -width can be a float
1251 if '.' in res: return getdouble(res)
1252 return getint(res)
1253 def grid_columnconfigure(self, index, cnf={}, **kw):
1254 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001255
Fredrik Lundh06d28152000-08-09 18:03:12 +00001256 Valid resources are minsize (minimum size of the column),
1257 weight (how much does additional space propagate to this column)
1258 and pad (how much space to let additionally)."""
1259 return self._grid_configure('columnconfigure', index, cnf, kw)
1260 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001261 def grid_location(self, x, y):
1262 """Return a tuple of column and row which identify the cell
1263 at which the pixel at position X and Y inside the master
1264 widget is located."""
1265 return self._getints(
1266 self.tk.call(
1267 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001268 def grid_propagate(self, flag=_noarg_):
1269 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001270
Fredrik Lundh06d28152000-08-09 18:03:12 +00001271 A boolean argument specifies whether the geometry information
1272 of the slaves will determine the size of this widget. If no argument
1273 is given, the current setting will be returned.
1274 """
1275 if flag is Misc._noarg_:
1276 return self._getboolean(self.tk.call(
1277 'grid', 'propagate', self._w))
1278 else:
1279 self.tk.call('grid', 'propagate', self._w, flag)
1280 def grid_rowconfigure(self, index, cnf={}, **kw):
1281 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001282
Fredrik Lundh06d28152000-08-09 18:03:12 +00001283 Valid resources are minsize (minimum size of the row),
1284 weight (how much does additional space propagate to this row)
1285 and pad (how much space to let additionally)."""
1286 return self._grid_configure('rowconfigure', index, cnf, kw)
1287 rowconfigure = grid_rowconfigure
1288 def grid_size(self):
1289 """Return a tuple of the number of column and rows in the grid."""
1290 return self._getints(
1291 self.tk.call('grid', 'size', self._w)) or None
1292 size = grid_size
1293 def grid_slaves(self, row=None, column=None):
1294 """Return a list of all slaves of this widget
1295 in its packing order."""
1296 args = ()
1297 if row is not None:
1298 args = args + ('-row', row)
1299 if column is not None:
1300 args = args + ('-column', column)
1301 return map(self._nametowidget,
1302 self.tk.splitlist(self.tk.call(
1303 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001304
Fredrik Lundh06d28152000-08-09 18:03:12 +00001305 # Support for the "event" command, new in Tk 4.2.
1306 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001307
Fredrik Lundh06d28152000-08-09 18:03:12 +00001308 def event_add(self, virtual, *sequences):
1309 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1310 to an event SEQUENCE such that the virtual event is triggered
1311 whenever SEQUENCE occurs."""
1312 args = ('event', 'add', virtual) + sequences
1313 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001314
Fredrik Lundh06d28152000-08-09 18:03:12 +00001315 def event_delete(self, virtual, *sequences):
1316 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1317 args = ('event', 'delete', virtual) + sequences
1318 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001319
Fredrik Lundh06d28152000-08-09 18:03:12 +00001320 def event_generate(self, sequence, **kw):
1321 """Generate an event SEQUENCE. Additional
1322 keyword arguments specify parameter of the event
1323 (e.g. x, y, rootx, rooty)."""
1324 args = ('event', 'generate', self._w, sequence)
1325 for k, v in kw.items():
1326 args = args + ('-%s' % k, str(v))
1327 self.tk.call(args)
1328
1329 def event_info(self, virtual=None):
1330 """Return a list of all virtual events or the information
1331 about the SEQUENCE bound to the virtual event VIRTUAL."""
1332 return self.tk.splitlist(
1333 self.tk.call('event', 'info', virtual))
1334
1335 # Image related commands
1336
1337 def image_names(self):
1338 """Return a list of all existing image names."""
1339 return self.tk.call('image', 'names')
1340
1341 def image_types(self):
1342 """Return a list of all available image types (e.g. phote bitmap)."""
1343 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001344
Guido van Rossum80f8be81997-12-02 19:51:39 +00001345
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001346class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001347 """Internal class. Stores function to call when some user
1348 defined Tcl function is called e.g. after an event occurred."""
1349 def __init__(self, func, subst, widget):
1350 """Store FUNC, SUBST and WIDGET as members."""
1351 self.func = func
1352 self.subst = subst
1353 self.widget = widget
1354 def __call__(self, *args):
1355 """Apply first function SUBST to arguments, than FUNC."""
1356 try:
1357 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001358 args = self.subst(*args)
1359 return self.func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001360 except SystemExit, msg:
1361 raise SystemExit, msg
1362 except:
1363 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001364
Guido van Rossume365a591998-05-01 19:48:20 +00001365
Guido van Rossum18468821994-06-20 07:49:28 +00001366class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001367 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001368
Fredrik Lundh06d28152000-08-09 18:03:12 +00001369 def wm_aspect(self,
1370 minNumer=None, minDenom=None,
1371 maxNumer=None, maxDenom=None):
1372 """Instruct the window manager to set the aspect ratio (width/height)
1373 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1374 of the actual values if no argument is given."""
1375 return self._getints(
1376 self.tk.call('wm', 'aspect', self._w,
1377 minNumer, minDenom,
1378 maxNumer, maxDenom))
1379 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001380
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001381 def wm_attributes(self, *args):
1382 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001383
1384 The first form returns a list of the platform specific flags and
1385 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001386 option. The third form sets one or more of the values. The values
1387 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001388
1389 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001390 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001391 to toolwindow (as defined in the MSDN). -topmost gets or sets
1392 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001393 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001394
1395 On Macintosh, XXXXX
1396
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001397 On Unix, there are currently no special attribute values.
1398 """
1399 args = ('wm', 'attributes', self._w) + args
1400 return self.tk.call(args)
1401 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001402
Fredrik Lundh06d28152000-08-09 18:03:12 +00001403 def wm_client(self, name=None):
1404 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1405 current value."""
1406 return self.tk.call('wm', 'client', self._w, name)
1407 client = wm_client
1408 def wm_colormapwindows(self, *wlist):
1409 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1410 of this widget. This list contains windows whose colormaps differ from their
1411 parents. Return current list of widgets if WLIST is empty."""
1412 if len(wlist) > 1:
1413 wlist = (wlist,) # Tk needs a list of windows here
1414 args = ('wm', 'colormapwindows', self._w) + wlist
1415 return map(self._nametowidget, self.tk.call(args))
1416 colormapwindows = wm_colormapwindows
1417 def wm_command(self, value=None):
1418 """Store VALUE in WM_COMMAND property. It is the command
1419 which shall be used to invoke the application. Return current
1420 command if VALUE is None."""
1421 return self.tk.call('wm', 'command', self._w, value)
1422 command = wm_command
1423 def wm_deiconify(self):
1424 """Deiconify this widget. If it was never mapped it will not be mapped.
1425 On Windows it will raise this widget and give it the focus."""
1426 return self.tk.call('wm', 'deiconify', self._w)
1427 deiconify = wm_deiconify
1428 def wm_focusmodel(self, model=None):
1429 """Set focus model to MODEL. "active" means that this widget will claim
1430 the focus itself, "passive" means that the window manager shall give
1431 the focus. Return current focus model if MODEL is None."""
1432 return self.tk.call('wm', 'focusmodel', self._w, model)
1433 focusmodel = wm_focusmodel
1434 def wm_frame(self):
1435 """Return identifier for decorative frame of this widget if present."""
1436 return self.tk.call('wm', 'frame', self._w)
1437 frame = wm_frame
1438 def wm_geometry(self, newGeometry=None):
1439 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1440 current value if None is given."""
1441 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1442 geometry = wm_geometry
1443 def wm_grid(self,
1444 baseWidth=None, baseHeight=None,
1445 widthInc=None, heightInc=None):
1446 """Instruct the window manager that this widget shall only be
1447 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1448 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1449 number of grid units requested in Tk_GeometryRequest."""
1450 return self._getints(self.tk.call(
1451 'wm', 'grid', self._w,
1452 baseWidth, baseHeight, widthInc, heightInc))
1453 grid = wm_grid
1454 def wm_group(self, pathName=None):
1455 """Set the group leader widgets for related widgets to PATHNAME. Return
1456 the group leader of this widget if None is given."""
1457 return self.tk.call('wm', 'group', self._w, pathName)
1458 group = wm_group
1459 def wm_iconbitmap(self, bitmap=None):
1460 """Set bitmap for the iconified widget to BITMAP. Return
1461 the bitmap if None is given."""
1462 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1463 iconbitmap = wm_iconbitmap
1464 def wm_iconify(self):
1465 """Display widget as icon."""
1466 return self.tk.call('wm', 'iconify', self._w)
1467 iconify = wm_iconify
1468 def wm_iconmask(self, bitmap=None):
1469 """Set mask for the icon bitmap of this widget. Return the
1470 mask if None is given."""
1471 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1472 iconmask = wm_iconmask
1473 def wm_iconname(self, newName=None):
1474 """Set the name of the icon for this widget. Return the name if
1475 None is given."""
1476 return self.tk.call('wm', 'iconname', self._w, newName)
1477 iconname = wm_iconname
1478 def wm_iconposition(self, x=None, y=None):
1479 """Set the position of the icon of this widget to X and Y. Return
1480 a tuple of the current values of X and X if None is given."""
1481 return self._getints(self.tk.call(
1482 'wm', 'iconposition', self._w, x, y))
1483 iconposition = wm_iconposition
1484 def wm_iconwindow(self, pathName=None):
1485 """Set widget PATHNAME to be displayed instead of icon. Return the current
1486 value if None is given."""
1487 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1488 iconwindow = wm_iconwindow
1489 def wm_maxsize(self, width=None, height=None):
1490 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1491 the values are given in grid units. Return the current values if None
1492 is given."""
1493 return self._getints(self.tk.call(
1494 'wm', 'maxsize', self._w, width, height))
1495 maxsize = wm_maxsize
1496 def wm_minsize(self, width=None, height=None):
1497 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1498 the values are given in grid units. Return the current values if None
1499 is given."""
1500 return self._getints(self.tk.call(
1501 'wm', 'minsize', self._w, width, height))
1502 minsize = wm_minsize
1503 def wm_overrideredirect(self, boolean=None):
1504 """Instruct the window manager to ignore this widget
1505 if BOOLEAN is given with 1. Return the current value if None
1506 is given."""
1507 return self._getboolean(self.tk.call(
1508 'wm', 'overrideredirect', self._w, boolean))
1509 overrideredirect = wm_overrideredirect
1510 def wm_positionfrom(self, who=None):
1511 """Instruct the window manager that the position of this widget shall
1512 be defined by the user if WHO is "user", and by its own policy if WHO is
1513 "program"."""
1514 return self.tk.call('wm', 'positionfrom', self._w, who)
1515 positionfrom = wm_positionfrom
1516 def wm_protocol(self, name=None, func=None):
1517 """Bind function FUNC to command NAME for this widget.
1518 Return the function bound to NAME if None is given. NAME could be
1519 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1520 if callable(func):
1521 command = self._register(func)
1522 else:
1523 command = func
1524 return self.tk.call(
1525 'wm', 'protocol', self._w, name, command)
1526 protocol = wm_protocol
1527 def wm_resizable(self, width=None, height=None):
1528 """Instruct the window manager whether this width can be resized
1529 in WIDTH or HEIGHT. Both values are boolean values."""
1530 return self.tk.call('wm', 'resizable', self._w, width, height)
1531 resizable = wm_resizable
1532 def wm_sizefrom(self, who=None):
1533 """Instruct the window manager that the size of this widget shall
1534 be defined by the user if WHO is "user", and by its own policy if WHO is
1535 "program"."""
1536 return self.tk.call('wm', 'sizefrom', self._w, who)
1537 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001538 def wm_state(self, newstate=None):
1539 """Query or set the state of this widget as one of normal, icon,
1540 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1541 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001542 state = wm_state
1543 def wm_title(self, string=None):
1544 """Set the title of this widget."""
1545 return self.tk.call('wm', 'title', self._w, string)
1546 title = wm_title
1547 def wm_transient(self, master=None):
1548 """Instruct the window manager that this widget is transient
1549 with regard to widget MASTER."""
1550 return self.tk.call('wm', 'transient', self._w, master)
1551 transient = wm_transient
1552 def wm_withdraw(self):
1553 """Withdraw this widget from the screen such that it is unmapped
1554 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1555 return self.tk.call('wm', 'withdraw', self._w)
1556 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001557
Guido van Rossum18468821994-06-20 07:49:28 +00001558
1559class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001560 """Toplevel widget of Tk which represents mostly the main window
1561 of an appliation. It has an associated Tcl interpreter."""
1562 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001563 def __init__(self, screenName=None, baseName=None, className='Tk',
1564 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001565 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1566 be created. BASENAME will be used for the identification of the profile file (see
1567 readprofile).
1568 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1569 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001570 self.master = None
1571 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001572 self._tkloaded = 0
1573 # to avoid recursions in the getattr code in case of failure, we
1574 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001575 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001576 if baseName is None:
1577 import sys, os
1578 baseName = os.path.basename(sys.argv[0])
1579 baseName, ext = os.path.splitext(baseName)
1580 if ext not in ('.py', '.pyc', '.pyo'):
1581 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001582 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001583 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001584 if useTk:
1585 self._loadtk()
1586 self.readprofile(baseName, className)
1587 def loadtk(self):
1588 if not self._tkloaded:
1589 self.tk.loadtk()
1590 self._loadtk()
1591 def _loadtk(self):
1592 self._tkloaded = 1
1593 global _default_root
Jack Jansenbe92af02001-08-23 13:25:59 +00001594 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001595 # Disable event scanning except for Command-Period
1596 _MacOS.SchedParams(1, 0)
1597 # Work around nasty MacTk bug
1598 # XXX Is this one still needed?
1599 self.update()
1600 # Version sanity checks
1601 tk_version = self.tk.getvar('tk_version')
1602 if tk_version != _tkinter.TK_VERSION:
1603 raise RuntimeError, \
1604 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1605 % (_tkinter.TK_VERSION, tk_version)
Martin v. Löwis54895972003-05-24 11:37:15 +00001606 # Under unknown circumstances, tcl_version gets coerced to float
1607 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001608 if tcl_version != _tkinter.TCL_VERSION:
1609 raise RuntimeError, \
1610 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1611 % (_tkinter.TCL_VERSION, tcl_version)
1612 if TkVersion < 4.0:
1613 raise RuntimeError, \
1614 "Tk 4.0 or higher is required; found Tk %s" \
1615 % str(TkVersion)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001616 # Create and register the tkerror and exit commands
1617 # We need to inline parts of _register here, _ register
1618 # would register differently-named commands.
1619 if self._tclCommands is None:
1620 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001621 self.tk.createcommand('tkerror', _tkerror)
1622 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001623 self._tclCommands.append('tkerror')
1624 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001625 if _support_default_root and not _default_root:
1626 _default_root = self
1627 self.protocol("WM_DELETE_WINDOW", self.destroy)
1628 def destroy(self):
1629 """Destroy this and all descendants widgets. This will
1630 end the application of this Tcl interpreter."""
1631 for c in self.children.values(): c.destroy()
1632 self.tk.call('destroy', self._w)
1633 Misc.destroy(self)
1634 global _default_root
1635 if _support_default_root and _default_root is self:
1636 _default_root = None
1637 def readprofile(self, baseName, className):
1638 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1639 the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1640 such a file exists in the home directory."""
1641 import os
1642 if os.environ.has_key('HOME'): home = os.environ['HOME']
1643 else: home = os.curdir
1644 class_tcl = os.path.join(home, '.%s.tcl' % className)
1645 class_py = os.path.join(home, '.%s.py' % className)
1646 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1647 base_py = os.path.join(home, '.%s.py' % baseName)
1648 dir = {'self': self}
1649 exec 'from Tkinter import *' in dir
1650 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001651 self.tk.call('source', class_tcl)
1652 if os.path.isfile(class_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001653 execfile(class_py, dir)
1654 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001655 self.tk.call('source', base_tcl)
1656 if os.path.isfile(base_py):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001657 execfile(base_py, dir)
1658 def report_callback_exception(self, exc, val, tb):
1659 """Internal function. It reports exception on sys.stderr."""
1660 import traceback, sys
1661 sys.stderr.write("Exception in Tkinter callback\n")
1662 sys.last_type = exc
1663 sys.last_value = val
1664 sys.last_traceback = tb
1665 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001666 def __getattr__(self, attr):
1667 "Delegate attribute access to the interpreter object"
1668 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001669
Guido van Rossum368e06b1997-11-07 20:38:49 +00001670# Ideally, the classes Pack, Place and Grid disappear, the
1671# pack/place/grid methods are defined on the Widget class, and
1672# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1673# ...), with pack(), place() and grid() being short for
1674# pack_configure(), place_configure() and grid_columnconfigure(), and
1675# forget() being short for pack_forget(). As a practical matter, I'm
1676# afraid that there is too much code out there that may be using the
1677# Pack, Place or Grid class, so I leave them intact -- but only as
1678# backwards compatibility features. Also note that those methods that
1679# take a master as argument (e.g. pack_propagate) have been moved to
1680# the Misc class (which now incorporates all methods common between
1681# toplevel and interior widgets). Again, for compatibility, these are
1682# copied into the Pack, Place or Grid class.
1683
David Aschere2b4b322004-02-18 05:59:53 +00001684
1685def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1686 return Tk(screenName, baseName, className, useTk)
1687
Guido van Rossum18468821994-06-20 07:49:28 +00001688class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001689 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001690
Fredrik Lundh06d28152000-08-09 18:03:12 +00001691 Base class to use the methods pack_* in every widget."""
1692 def pack_configure(self, cnf={}, **kw):
1693 """Pack a widget in the parent widget. Use as options:
1694 after=widget - pack it after you have packed widget
1695 anchor=NSEW (or subset) - position widget according to
1696 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001697 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001698 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001699 fill=NONE or X or Y or BOTH - fill widget if widget grows
1700 in=master - use master to contain this widget
1701 ipadx=amount - add internal padding in x direction
1702 ipady=amount - add internal padding in y direction
1703 padx=amount - add padding in x direction
1704 pady=amount - add padding in y direction
1705 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1706 """
1707 self.tk.call(
1708 ('pack', 'configure', self._w)
1709 + self._options(cnf, kw))
1710 pack = configure = config = pack_configure
1711 def pack_forget(self):
1712 """Unmap this widget and do not use it for the packing order."""
1713 self.tk.call('pack', 'forget', self._w)
1714 forget = pack_forget
1715 def pack_info(self):
1716 """Return information about the packing options
1717 for this widget."""
1718 words = self.tk.splitlist(
1719 self.tk.call('pack', 'info', self._w))
1720 dict = {}
1721 for i in range(0, len(words), 2):
1722 key = words[i][1:]
1723 value = words[i+1]
1724 if value[:1] == '.':
1725 value = self._nametowidget(value)
1726 dict[key] = value
1727 return dict
1728 info = pack_info
1729 propagate = pack_propagate = Misc.pack_propagate
1730 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001731
1732class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001733 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001734
Fredrik Lundh06d28152000-08-09 18:03:12 +00001735 Base class to use the methods place_* in every widget."""
1736 def place_configure(self, cnf={}, **kw):
1737 """Place a widget in the parent widget. Use as options:
1738 in=master - master relative to which the widget is placed.
1739 x=amount - locate anchor of this widget at position x of master
1740 y=amount - locate anchor of this widget at position y of master
1741 relx=amount - locate anchor of this widget between 0.0 and 1.0
1742 relative to width of master (1.0 is right edge)
1743 rely=amount - locate anchor of this widget between 0.0 and 1.0
1744 relative to height of master (1.0 is bottom edge)
1745 anchor=NSEW (or subset) - position anchor according to given direction
1746 width=amount - width of this widget in pixel
1747 height=amount - height of this widget in pixel
1748 relwidth=amount - width of this widget between 0.0 and 1.0
1749 relative to width of master (1.0 is the same width
1750 as the master)
1751 relheight=amount - height of this widget between 0.0 and 1.0
1752 relative to height of master (1.0 is the same
1753 height as the master)
1754 bordermode="inside" or "outside" - whether to take border width of master widget
1755 into account
1756 """
1757 for k in ['in_']:
1758 if kw.has_key(k):
1759 kw[k[:-1]] = kw[k]
1760 del kw[k]
1761 self.tk.call(
1762 ('place', 'configure', self._w)
1763 + self._options(cnf, kw))
1764 place = configure = config = place_configure
1765 def place_forget(self):
1766 """Unmap this widget."""
1767 self.tk.call('place', 'forget', self._w)
1768 forget = place_forget
1769 def place_info(self):
1770 """Return information about the placing options
1771 for this widget."""
1772 words = self.tk.splitlist(
1773 self.tk.call('place', 'info', self._w))
1774 dict = {}
1775 for i in range(0, len(words), 2):
1776 key = words[i][1:]
1777 value = words[i+1]
1778 if value[:1] == '.':
1779 value = self._nametowidget(value)
1780 dict[key] = value
1781 return dict
1782 info = place_info
1783 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001784
Guido van Rossum37dcab11996-05-16 16:00:19 +00001785class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001786 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001787
Fredrik Lundh06d28152000-08-09 18:03:12 +00001788 Base class to use the methods grid_* in every widget."""
1789 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1790 def grid_configure(self, cnf={}, **kw):
1791 """Position a widget in the parent widget in a grid. Use as options:
1792 column=number - use cell identified with given column (starting with 0)
1793 columnspan=number - this widget will span several columns
1794 in=master - use master to contain this widget
1795 ipadx=amount - add internal padding in x direction
1796 ipady=amount - add internal padding in y direction
1797 padx=amount - add padding in x direction
1798 pady=amount - add padding in y direction
1799 row=number - use cell identified with given row (starting with 0)
1800 rowspan=number - this widget will span several rows
1801 sticky=NSEW - if cell is larger on which sides will this
1802 widget stick to the cell boundary
1803 """
1804 self.tk.call(
1805 ('grid', 'configure', self._w)
1806 + self._options(cnf, kw))
1807 grid = configure = config = grid_configure
1808 bbox = grid_bbox = Misc.grid_bbox
1809 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1810 def grid_forget(self):
1811 """Unmap this widget."""
1812 self.tk.call('grid', 'forget', self._w)
1813 forget = grid_forget
1814 def grid_remove(self):
1815 """Unmap this widget but remember the grid options."""
1816 self.tk.call('grid', 'remove', self._w)
1817 def grid_info(self):
1818 """Return information about the options
1819 for positioning this widget in a grid."""
1820 words = self.tk.splitlist(
1821 self.tk.call('grid', 'info', self._w))
1822 dict = {}
1823 for i in range(0, len(words), 2):
1824 key = words[i][1:]
1825 value = words[i+1]
1826 if value[:1] == '.':
1827 value = self._nametowidget(value)
1828 dict[key] = value
1829 return dict
1830 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001831 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001832 propagate = grid_propagate = Misc.grid_propagate
1833 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1834 size = grid_size = Misc.grid_size
1835 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001836
Guido van Rossum368e06b1997-11-07 20:38:49 +00001837class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001838 """Internal class."""
1839 def _setup(self, master, cnf):
1840 """Internal function. Sets up information about children."""
1841 if _support_default_root:
1842 global _default_root
1843 if not master:
1844 if not _default_root:
1845 _default_root = Tk()
1846 master = _default_root
1847 self.master = master
1848 self.tk = master.tk
1849 name = None
1850 if cnf.has_key('name'):
1851 name = cnf['name']
1852 del cnf['name']
1853 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001854 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001855 self._name = name
1856 if master._w=='.':
1857 self._w = '.' + name
1858 else:
1859 self._w = master._w + '.' + name
1860 self.children = {}
1861 if self.master.children.has_key(self._name):
1862 self.master.children[self._name].destroy()
1863 self.master.children[self._name] = self
1864 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1865 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1866 and appropriate options."""
1867 if kw:
1868 cnf = _cnfmerge((cnf, kw))
1869 self.widgetName = widgetName
1870 BaseWidget._setup(self, master, cnf)
1871 classes = []
1872 for k in cnf.keys():
1873 if type(k) is ClassType:
1874 classes.append((k, cnf[k]))
1875 del cnf[k]
1876 self.tk.call(
1877 (widgetName, self._w) + extra + self._options(cnf))
1878 for k, v in classes:
1879 k.configure(self, v)
1880 def destroy(self):
1881 """Destroy this and all descendants widgets."""
1882 for c in self.children.values(): c.destroy()
1883 if self.master.children.has_key(self._name):
1884 del self.master.children[self._name]
1885 self.tk.call('destroy', self._w)
1886 Misc.destroy(self)
1887 def _do(self, name, args=()):
1888 # XXX Obsolete -- better use self.tk.call directly!
1889 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001890
Guido van Rossum368e06b1997-11-07 20:38:49 +00001891class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001892 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001893
Fredrik Lundh06d28152000-08-09 18:03:12 +00001894 Base class for a widget which can be positioned with the geometry managers
1895 Pack, Place or Grid."""
1896 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001897
1898class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001899 """Toplevel widget, e.g. for dialogs."""
1900 def __init__(self, master=None, cnf={}, **kw):
1901 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001902
Fredrik Lundh06d28152000-08-09 18:03:12 +00001903 Valid resource names: background, bd, bg, borderwidth, class,
1904 colormap, container, cursor, height, highlightbackground,
1905 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1906 use, visual, width."""
1907 if kw:
1908 cnf = _cnfmerge((cnf, kw))
1909 extra = ()
1910 for wmkey in ['screen', 'class_', 'class', 'visual',
1911 'colormap']:
1912 if cnf.has_key(wmkey):
1913 val = cnf[wmkey]
1914 # TBD: a hack needed because some keys
1915 # are not valid as keyword arguments
1916 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1917 else: opt = '-'+wmkey
1918 extra = extra + (opt, val)
1919 del cnf[wmkey]
1920 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1921 root = self._root()
1922 self.iconname(root.iconname())
1923 self.title(root.title())
1924 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001925
1926class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001927 """Button widget."""
1928 def __init__(self, master=None, cnf={}, **kw):
1929 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001930
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001931 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001932
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001933 activebackground, activeforeground, anchor,
1934 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001935 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001936 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001937 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001938 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001939 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001940 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001941
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001942 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001943
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001944 command, compound, default, height,
1945 overrelief, state, width
1946 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001947 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001948
Fredrik Lundh06d28152000-08-09 18:03:12 +00001949 def tkButtonEnter(self, *dummy):
1950 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001951
Fredrik Lundh06d28152000-08-09 18:03:12 +00001952 def tkButtonLeave(self, *dummy):
1953 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001954
Fredrik Lundh06d28152000-08-09 18:03:12 +00001955 def tkButtonDown(self, *dummy):
1956 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001957
Fredrik Lundh06d28152000-08-09 18:03:12 +00001958 def tkButtonUp(self, *dummy):
1959 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001960
Fredrik Lundh06d28152000-08-09 18:03:12 +00001961 def tkButtonInvoke(self, *dummy):
1962 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001963
Fredrik Lundh06d28152000-08-09 18:03:12 +00001964 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001965 """Flash the button.
1966
1967 This is accomplished by redisplaying
1968 the button several times, alternating between active and
1969 normal colors. At the end of the flash the button is left
1970 in the same normal/active state as when the command was
1971 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001972 disabled.
1973 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001974 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00001975
Fredrik Lundh06d28152000-08-09 18:03:12 +00001976 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001977 """Invoke the command associated with the button.
1978
1979 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001980 or an empty string if there is no command associated with
1981 the button. This command is ignored if the button's state
1982 is disabled.
1983 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001984 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00001985
1986# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00001987# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00001988def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001989 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00001990def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001991 s = 'insert'
1992 for a in args:
1993 if a: s = s + (' ' + a)
1994 return s
Guido van Rossum18468821994-06-20 07:49:28 +00001995def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001996 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00001997def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00001998 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00001999def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002000 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002001 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002002 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002003 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002004
2005class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002006 """Canvas widget to display graphical elements like lines or text."""
2007 def __init__(self, master=None, cnf={}, **kw):
2008 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002009
Fredrik Lundh06d28152000-08-09 18:03:12 +00002010 Valid resource names: background, bd, bg, borderwidth, closeenough,
2011 confine, cursor, height, highlightbackground, highlightcolor,
2012 highlightthickness, insertbackground, insertborderwidth,
2013 insertofftime, insertontime, insertwidth, offset, relief,
2014 scrollregion, selectbackground, selectborderwidth, selectforeground,
2015 state, takefocus, width, xscrollcommand, xscrollincrement,
2016 yscrollcommand, yscrollincrement."""
2017 Widget.__init__(self, master, 'canvas', cnf, kw)
2018 def addtag(self, *args):
2019 """Internal function."""
2020 self.tk.call((self._w, 'addtag') + args)
2021 def addtag_above(self, newtag, tagOrId):
2022 """Add tag NEWTAG to all items above TAGORID."""
2023 self.addtag(newtag, 'above', tagOrId)
2024 def addtag_all(self, newtag):
2025 """Add tag NEWTAG to all items."""
2026 self.addtag(newtag, 'all')
2027 def addtag_below(self, newtag, tagOrId):
2028 """Add tag NEWTAG to all items below TAGORID."""
2029 self.addtag(newtag, 'below', tagOrId)
2030 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2031 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2032 If several match take the top-most.
2033 All items closer than HALO are considered overlapping (all are
2034 closests). If START is specified the next below this tag is taken."""
2035 self.addtag(newtag, 'closest', x, y, halo, start)
2036 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2037 """Add tag NEWTAG to all items in the rectangle defined
2038 by X1,Y1,X2,Y2."""
2039 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2040 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2041 """Add tag NEWTAG to all items which overlap the rectangle
2042 defined by X1,Y1,X2,Y2."""
2043 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2044 def addtag_withtag(self, newtag, tagOrId):
2045 """Add tag NEWTAG to all items with TAGORID."""
2046 self.addtag(newtag, 'withtag', tagOrId)
2047 def bbox(self, *args):
2048 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2049 which encloses all items with tags specified as arguments."""
2050 return self._getints(
2051 self.tk.call((self._w, 'bbox') + args)) or None
2052 def tag_unbind(self, tagOrId, sequence, funcid=None):
2053 """Unbind for all items with TAGORID for event SEQUENCE the
2054 function identified with FUNCID."""
2055 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2056 if funcid:
2057 self.deletecommand(funcid)
2058 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2059 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002060
Fredrik Lundh06d28152000-08-09 18:03:12 +00002061 An additional boolean parameter ADD specifies whether FUNC will be
2062 called additionally to the other bound function or whether it will
2063 replace the previous function. See bind for the return value."""
2064 return self._bind((self._w, 'bind', tagOrId),
2065 sequence, func, add)
2066 def canvasx(self, screenx, gridspacing=None):
2067 """Return the canvas x coordinate of pixel position SCREENX rounded
2068 to nearest multiple of GRIDSPACING units."""
2069 return getdouble(self.tk.call(
2070 self._w, 'canvasx', screenx, gridspacing))
2071 def canvasy(self, screeny, gridspacing=None):
2072 """Return the canvas y coordinate of pixel position SCREENY rounded
2073 to nearest multiple of GRIDSPACING units."""
2074 return getdouble(self.tk.call(
2075 self._w, 'canvasy', screeny, gridspacing))
2076 def coords(self, *args):
2077 """Return a list of coordinates for the item given in ARGS."""
2078 # XXX Should use _flatten on args
2079 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002080 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002081 self.tk.call((self._w, 'coords') + args)))
2082 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2083 """Internal function."""
2084 args = _flatten(args)
2085 cnf = args[-1]
2086 if type(cnf) in (DictionaryType, TupleType):
2087 args = args[:-1]
2088 else:
2089 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002090 return getint(self.tk.call(
2091 self._w, 'create', itemType,
2092 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002093 def create_arc(self, *args, **kw):
2094 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2095 return self._create('arc', args, kw)
2096 def create_bitmap(self, *args, **kw):
2097 """Create bitmap with coordinates x1,y1."""
2098 return self._create('bitmap', args, kw)
2099 def create_image(self, *args, **kw):
2100 """Create image item with coordinates x1,y1."""
2101 return self._create('image', args, kw)
2102 def create_line(self, *args, **kw):
2103 """Create line with coordinates x1,y1,...,xn,yn."""
2104 return self._create('line', args, kw)
2105 def create_oval(self, *args, **kw):
2106 """Create oval with coordinates x1,y1,x2,y2."""
2107 return self._create('oval', args, kw)
2108 def create_polygon(self, *args, **kw):
2109 """Create polygon with coordinates x1,y1,...,xn,yn."""
2110 return self._create('polygon', args, kw)
2111 def create_rectangle(self, *args, **kw):
2112 """Create rectangle with coordinates x1,y1,x2,y2."""
2113 return self._create('rectangle', args, kw)
2114 def create_text(self, *args, **kw):
2115 """Create text with coordinates x1,y1."""
2116 return self._create('text', args, kw)
2117 def create_window(self, *args, **kw):
2118 """Create window with coordinates x1,y1,x2,y2."""
2119 return self._create('window', args, kw)
2120 def dchars(self, *args):
2121 """Delete characters of text items identified by tag or id in ARGS (possibly
2122 several times) from FIRST to LAST character (including)."""
2123 self.tk.call((self._w, 'dchars') + args)
2124 def delete(self, *args):
2125 """Delete items identified by all tag or ids contained in ARGS."""
2126 self.tk.call((self._w, 'delete') + args)
2127 def dtag(self, *args):
2128 """Delete tag or id given as last arguments in ARGS from items
2129 identified by first argument in ARGS."""
2130 self.tk.call((self._w, 'dtag') + args)
2131 def find(self, *args):
2132 """Internal function."""
2133 return self._getints(
2134 self.tk.call((self._w, 'find') + args)) or ()
2135 def find_above(self, tagOrId):
2136 """Return items above TAGORID."""
2137 return self.find('above', tagOrId)
2138 def find_all(self):
2139 """Return all items."""
2140 return self.find('all')
2141 def find_below(self, tagOrId):
2142 """Return all items below TAGORID."""
2143 return self.find('below', tagOrId)
2144 def find_closest(self, x, y, halo=None, start=None):
2145 """Return item which is closest to pixel at X, Y.
2146 If several match take the top-most.
2147 All items closer than HALO are considered overlapping (all are
2148 closests). If START is specified the next below this tag is taken."""
2149 return self.find('closest', x, y, halo, start)
2150 def find_enclosed(self, x1, y1, x2, y2):
2151 """Return all items in rectangle defined
2152 by X1,Y1,X2,Y2."""
2153 return self.find('enclosed', x1, y1, x2, y2)
2154 def find_overlapping(self, x1, y1, x2, y2):
2155 """Return all items which overlap the rectangle
2156 defined by X1,Y1,X2,Y2."""
2157 return self.find('overlapping', x1, y1, x2, y2)
2158 def find_withtag(self, tagOrId):
2159 """Return all items with TAGORID."""
2160 return self.find('withtag', tagOrId)
2161 def focus(self, *args):
2162 """Set focus to the first item specified in ARGS."""
2163 return self.tk.call((self._w, 'focus') + args)
2164 def gettags(self, *args):
2165 """Return tags associated with the first item specified in ARGS."""
2166 return self.tk.splitlist(
2167 self.tk.call((self._w, 'gettags') + args))
2168 def icursor(self, *args):
2169 """Set cursor at position POS in the item identified by TAGORID.
2170 In ARGS TAGORID must be first."""
2171 self.tk.call((self._w, 'icursor') + args)
2172 def index(self, *args):
2173 """Return position of cursor as integer in item specified in ARGS."""
2174 return getint(self.tk.call((self._w, 'index') + args))
2175 def insert(self, *args):
2176 """Insert TEXT in item TAGORID at position POS. ARGS must
2177 be TAGORID POS TEXT."""
2178 self.tk.call((self._w, 'insert') + args)
2179 def itemcget(self, tagOrId, option):
2180 """Return the resource value for an OPTION for item TAGORID."""
2181 return self.tk.call(
2182 (self._w, 'itemcget') + (tagOrId, '-'+option))
2183 def itemconfigure(self, tagOrId, cnf=None, **kw):
2184 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002185
Fredrik Lundh06d28152000-08-09 18:03:12 +00002186 The values for resources are specified as keyword
2187 arguments. To get an overview about
2188 the allowed keyword arguments call the method without arguments.
2189 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002190 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002191 itemconfig = itemconfigure
2192 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2193 # so the preferred name for them is tag_lower, tag_raise
2194 # (similar to tag_bind, and similar to the Text widget);
2195 # unfortunately can't delete the old ones yet (maybe in 1.6)
2196 def tag_lower(self, *args):
2197 """Lower an item TAGORID given in ARGS
2198 (optional below another item)."""
2199 self.tk.call((self._w, 'lower') + args)
2200 lower = tag_lower
2201 def move(self, *args):
2202 """Move an item TAGORID given in ARGS."""
2203 self.tk.call((self._w, 'move') + args)
2204 def postscript(self, cnf={}, **kw):
2205 """Print the contents of the canvas to a postscript
2206 file. Valid options: colormap, colormode, file, fontmap,
2207 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2208 rotate, witdh, x, y."""
2209 return self.tk.call((self._w, 'postscript') +
2210 self._options(cnf, kw))
2211 def tag_raise(self, *args):
2212 """Raise an item TAGORID given in ARGS
2213 (optional above another item)."""
2214 self.tk.call((self._w, 'raise') + args)
2215 lift = tkraise = tag_raise
2216 def scale(self, *args):
2217 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2218 self.tk.call((self._w, 'scale') + args)
2219 def scan_mark(self, x, y):
2220 """Remember the current X, Y coordinates."""
2221 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002222 def scan_dragto(self, x, y, gain=10):
2223 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002224 difference between X and Y and the coordinates given in
2225 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002226 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002227 def select_adjust(self, tagOrId, index):
2228 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2229 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2230 def select_clear(self):
2231 """Clear the selection if it is in this widget."""
2232 self.tk.call(self._w, 'select', 'clear')
2233 def select_from(self, tagOrId, index):
2234 """Set the fixed end of a selection in item TAGORID to INDEX."""
2235 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2236 def select_item(self):
2237 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002238 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002239 def select_to(self, tagOrId, index):
2240 """Set the variable end of a selection in item TAGORID to INDEX."""
2241 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2242 def type(self, tagOrId):
2243 """Return the type of the item TAGORID."""
2244 return self.tk.call(self._w, 'type', tagOrId) or None
2245 def xview(self, *args):
2246 """Query and change horizontal position of the view."""
2247 if not args:
2248 return self._getdoubles(self.tk.call(self._w, 'xview'))
2249 self.tk.call((self._w, 'xview') + args)
2250 def xview_moveto(self, fraction):
2251 """Adjusts the view in the window so that FRACTION of the
2252 total width of the canvas is off-screen to the left."""
2253 self.tk.call(self._w, 'xview', 'moveto', fraction)
2254 def xview_scroll(self, number, what):
2255 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2256 self.tk.call(self._w, 'xview', 'scroll', number, what)
2257 def yview(self, *args):
2258 """Query and change vertical position of the view."""
2259 if not args:
2260 return self._getdoubles(self.tk.call(self._w, 'yview'))
2261 self.tk.call((self._w, 'yview') + args)
2262 def yview_moveto(self, fraction):
2263 """Adjusts the view in the window so that FRACTION of the
2264 total height of the canvas is off-screen to the top."""
2265 self.tk.call(self._w, 'yview', 'moveto', fraction)
2266 def yview_scroll(self, number, what):
2267 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2268 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002269
2270class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002271 """Checkbutton widget which is either in on- or off-state."""
2272 def __init__(self, master=None, cnf={}, **kw):
2273 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002274
Fredrik Lundh06d28152000-08-09 18:03:12 +00002275 Valid resource names: activebackground, activeforeground, anchor,
2276 background, bd, bg, bitmap, borderwidth, command, cursor,
2277 disabledforeground, fg, font, foreground, height,
2278 highlightbackground, highlightcolor, highlightthickness, image,
2279 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2280 selectcolor, selectimage, state, takefocus, text, textvariable,
2281 underline, variable, width, wraplength."""
2282 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2283 def deselect(self):
2284 """Put the button in off-state."""
2285 self.tk.call(self._w, 'deselect')
2286 def flash(self):
2287 """Flash the button."""
2288 self.tk.call(self._w, 'flash')
2289 def invoke(self):
2290 """Toggle the button and invoke a command if given as resource."""
2291 return self.tk.call(self._w, 'invoke')
2292 def select(self):
2293 """Put the button in on-state."""
2294 self.tk.call(self._w, 'select')
2295 def toggle(self):
2296 """Toggle the button."""
2297 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002298
2299class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002300 """Entry widget which allows to display simple text."""
2301 def __init__(self, master=None, cnf={}, **kw):
2302 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002303
Fredrik Lundh06d28152000-08-09 18:03:12 +00002304 Valid resource names: background, bd, bg, borderwidth, cursor,
2305 exportselection, fg, font, foreground, highlightbackground,
2306 highlightcolor, highlightthickness, insertbackground,
2307 insertborderwidth, insertofftime, insertontime, insertwidth,
2308 invalidcommand, invcmd, justify, relief, selectbackground,
2309 selectborderwidth, selectforeground, show, state, takefocus,
2310 textvariable, validate, validatecommand, vcmd, width,
2311 xscrollcommand."""
2312 Widget.__init__(self, master, 'entry', cnf, kw)
2313 def delete(self, first, last=None):
2314 """Delete text from FIRST to LAST (not included)."""
2315 self.tk.call(self._w, 'delete', first, last)
2316 def get(self):
2317 """Return the text."""
2318 return self.tk.call(self._w, 'get')
2319 def icursor(self, index):
2320 """Insert cursor at INDEX."""
2321 self.tk.call(self._w, 'icursor', index)
2322 def index(self, index):
2323 """Return position of cursor."""
2324 return getint(self.tk.call(
2325 self._w, 'index', index))
2326 def insert(self, index, string):
2327 """Insert STRING at INDEX."""
2328 self.tk.call(self._w, 'insert', index, string)
2329 def scan_mark(self, x):
2330 """Remember the current X, Y coordinates."""
2331 self.tk.call(self._w, 'scan', 'mark', x)
2332 def scan_dragto(self, x):
2333 """Adjust the view of the canvas to 10 times the
2334 difference between X and Y and the coordinates given in
2335 scan_mark."""
2336 self.tk.call(self._w, 'scan', 'dragto', x)
2337 def selection_adjust(self, index):
2338 """Adjust the end of the selection near the cursor to INDEX."""
2339 self.tk.call(self._w, 'selection', 'adjust', index)
2340 select_adjust = selection_adjust
2341 def selection_clear(self):
2342 """Clear the selection if it is in this widget."""
2343 self.tk.call(self._w, 'selection', 'clear')
2344 select_clear = selection_clear
2345 def selection_from(self, index):
2346 """Set the fixed end of a selection to INDEX."""
2347 self.tk.call(self._w, 'selection', 'from', index)
2348 select_from = selection_from
2349 def selection_present(self):
2350 """Return whether the widget has the selection."""
2351 return self.tk.getboolean(
2352 self.tk.call(self._w, 'selection', 'present'))
2353 select_present = selection_present
2354 def selection_range(self, start, end):
2355 """Set the selection from START to END (not included)."""
2356 self.tk.call(self._w, 'selection', 'range', start, end)
2357 select_range = selection_range
2358 def selection_to(self, index):
2359 """Set the variable end of a selection to INDEX."""
2360 self.tk.call(self._w, 'selection', 'to', index)
2361 select_to = selection_to
2362 def xview(self, index):
2363 """Query and change horizontal position of the view."""
2364 self.tk.call(self._w, 'xview', index)
2365 def xview_moveto(self, fraction):
2366 """Adjust the view in the window so that FRACTION of the
2367 total width of the entry is off-screen to the left."""
2368 self.tk.call(self._w, 'xview', 'moveto', fraction)
2369 def xview_scroll(self, number, what):
2370 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2371 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002372
2373class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002374 """Frame widget which may contain other widgets and can have a 3D border."""
2375 def __init__(self, master=None, cnf={}, **kw):
2376 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002377
Fredrik Lundh06d28152000-08-09 18:03:12 +00002378 Valid resource names: background, bd, bg, borderwidth, class,
2379 colormap, container, cursor, height, highlightbackground,
2380 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2381 cnf = _cnfmerge((cnf, kw))
2382 extra = ()
2383 if cnf.has_key('class_'):
2384 extra = ('-class', cnf['class_'])
2385 del cnf['class_']
2386 elif cnf.has_key('class'):
2387 extra = ('-class', cnf['class'])
2388 del cnf['class']
2389 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002390
2391class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002392 """Label widget which can display text and bitmaps."""
2393 def __init__(self, master=None, cnf={}, **kw):
2394 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002395
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002396 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002397
2398 activebackground, activeforeground, anchor,
2399 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002400 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002401 highlightbackground, highlightcolor,
2402 highlightthickness, image, justify,
2403 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002404 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002405
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002406 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002407
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002408 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002409
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002410 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002411 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002412
Guido van Rossum18468821994-06-20 07:49:28 +00002413class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002414 """Listbox widget which can display a list of strings."""
2415 def __init__(self, master=None, cnf={}, **kw):
2416 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002417
Fredrik Lundh06d28152000-08-09 18:03:12 +00002418 Valid resource names: background, bd, bg, borderwidth, cursor,
2419 exportselection, fg, font, foreground, height, highlightbackground,
2420 highlightcolor, highlightthickness, relief, selectbackground,
2421 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2422 width, xscrollcommand, yscrollcommand, listvariable."""
2423 Widget.__init__(self, master, 'listbox', cnf, kw)
2424 def activate(self, index):
2425 """Activate item identified by INDEX."""
2426 self.tk.call(self._w, 'activate', index)
2427 def bbox(self, *args):
2428 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2429 which encloses the item identified by index in ARGS."""
2430 return self._getints(
2431 self.tk.call((self._w, 'bbox') + args)) or None
2432 def curselection(self):
2433 """Return list of indices of currently selected item."""
2434 # XXX Ought to apply self._getints()...
2435 return self.tk.splitlist(self.tk.call(
2436 self._w, 'curselection'))
2437 def delete(self, first, last=None):
2438 """Delete items from FIRST to LAST (not included)."""
2439 self.tk.call(self._w, 'delete', first, last)
2440 def get(self, first, last=None):
2441 """Get list of items from FIRST to LAST (not included)."""
2442 if last:
2443 return self.tk.splitlist(self.tk.call(
2444 self._w, 'get', first, last))
2445 else:
2446 return self.tk.call(self._w, 'get', first)
2447 def index(self, index):
2448 """Return index of item identified with INDEX."""
2449 i = self.tk.call(self._w, 'index', index)
2450 if i == 'none': return None
2451 return getint(i)
2452 def insert(self, index, *elements):
2453 """Insert ELEMENTS at INDEX."""
2454 self.tk.call((self._w, 'insert', index) + elements)
2455 def nearest(self, y):
2456 """Get index of item which is nearest to y coordinate Y."""
2457 return getint(self.tk.call(
2458 self._w, 'nearest', y))
2459 def scan_mark(self, x, y):
2460 """Remember the current X, Y coordinates."""
2461 self.tk.call(self._w, 'scan', 'mark', x, y)
2462 def scan_dragto(self, x, y):
2463 """Adjust the view of the listbox to 10 times the
2464 difference between X and Y and the coordinates given in
2465 scan_mark."""
2466 self.tk.call(self._w, 'scan', 'dragto', x, y)
2467 def see(self, index):
2468 """Scroll such that INDEX is visible."""
2469 self.tk.call(self._w, 'see', index)
2470 def selection_anchor(self, index):
2471 """Set the fixed end oft the selection to INDEX."""
2472 self.tk.call(self._w, 'selection', 'anchor', index)
2473 select_anchor = selection_anchor
2474 def selection_clear(self, first, last=None):
2475 """Clear the selection from FIRST to LAST (not included)."""
2476 self.tk.call(self._w,
2477 'selection', 'clear', first, last)
2478 select_clear = selection_clear
2479 def selection_includes(self, index):
2480 """Return 1 if INDEX is part of the selection."""
2481 return self.tk.getboolean(self.tk.call(
2482 self._w, 'selection', 'includes', index))
2483 select_includes = selection_includes
2484 def selection_set(self, first, last=None):
2485 """Set the selection from FIRST to LAST (not included) without
2486 changing the currently selected elements."""
2487 self.tk.call(self._w, 'selection', 'set', first, last)
2488 select_set = selection_set
2489 def size(self):
2490 """Return the number of elements in the listbox."""
2491 return getint(self.tk.call(self._w, 'size'))
2492 def xview(self, *what):
2493 """Query and change horizontal position of the view."""
2494 if not what:
2495 return self._getdoubles(self.tk.call(self._w, 'xview'))
2496 self.tk.call((self._w, 'xview') + what)
2497 def xview_moveto(self, fraction):
2498 """Adjust the view in the window so that FRACTION of the
2499 total width of the entry is off-screen to the left."""
2500 self.tk.call(self._w, 'xview', 'moveto', fraction)
2501 def xview_scroll(self, number, what):
2502 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2503 self.tk.call(self._w, 'xview', 'scroll', number, what)
2504 def yview(self, *what):
2505 """Query and change vertical position of the view."""
2506 if not what:
2507 return self._getdoubles(self.tk.call(self._w, 'yview'))
2508 self.tk.call((self._w, 'yview') + what)
2509 def yview_moveto(self, fraction):
2510 """Adjust the view in the window so that FRACTION of the
2511 total width of the entry is off-screen to the top."""
2512 self.tk.call(self._w, 'yview', 'moveto', fraction)
2513 def yview_scroll(self, number, what):
2514 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2515 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002516 def itemcget(self, index, option):
2517 """Return the resource value for an ITEM and an OPTION."""
2518 return self.tk.call(
2519 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002520 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002521 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002522
2523 The values for resources are specified as keyword arguments.
2524 To get an overview about the allowed keyword arguments
2525 call the method without arguments.
2526 Valid resource names: background, bg, foreground, fg,
2527 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002528 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002529 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002530
2531class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002532 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2533 def __init__(self, master=None, cnf={}, **kw):
2534 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002535
Fredrik Lundh06d28152000-08-09 18:03:12 +00002536 Valid resource names: activebackground, activeborderwidth,
2537 activeforeground, background, bd, bg, borderwidth, cursor,
2538 disabledforeground, fg, font, foreground, postcommand, relief,
2539 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2540 Widget.__init__(self, master, 'menu', cnf, kw)
2541 def tk_bindForTraversal(self):
2542 pass # obsolete since Tk 4.0
2543 def tk_mbPost(self):
2544 self.tk.call('tk_mbPost', self._w)
2545 def tk_mbUnpost(self):
2546 self.tk.call('tk_mbUnpost')
2547 def tk_traverseToMenu(self, char):
2548 self.tk.call('tk_traverseToMenu', self._w, char)
2549 def tk_traverseWithinMenu(self, char):
2550 self.tk.call('tk_traverseWithinMenu', self._w, char)
2551 def tk_getMenuButtons(self):
2552 return self.tk.call('tk_getMenuButtons', self._w)
2553 def tk_nextMenu(self, count):
2554 self.tk.call('tk_nextMenu', count)
2555 def tk_nextMenuEntry(self, count):
2556 self.tk.call('tk_nextMenuEntry', count)
2557 def tk_invokeMenu(self):
2558 self.tk.call('tk_invokeMenu', self._w)
2559 def tk_firstMenu(self):
2560 self.tk.call('tk_firstMenu', self._w)
2561 def tk_mbButtonDown(self):
2562 self.tk.call('tk_mbButtonDown', self._w)
2563 def tk_popup(self, x, y, entry=""):
2564 """Post the menu at position X,Y with entry ENTRY."""
2565 self.tk.call('tk_popup', self._w, x, y, entry)
2566 def activate(self, index):
2567 """Activate entry at INDEX."""
2568 self.tk.call(self._w, 'activate', index)
2569 def add(self, itemType, cnf={}, **kw):
2570 """Internal function."""
2571 self.tk.call((self._w, 'add', itemType) +
2572 self._options(cnf, kw))
2573 def add_cascade(self, cnf={}, **kw):
2574 """Add hierarchical menu item."""
2575 self.add('cascade', cnf or kw)
2576 def add_checkbutton(self, cnf={}, **kw):
2577 """Add checkbutton menu item."""
2578 self.add('checkbutton', cnf or kw)
2579 def add_command(self, cnf={}, **kw):
2580 """Add command menu item."""
2581 self.add('command', cnf or kw)
2582 def add_radiobutton(self, cnf={}, **kw):
2583 """Addd radio menu item."""
2584 self.add('radiobutton', cnf or kw)
2585 def add_separator(self, cnf={}, **kw):
2586 """Add separator."""
2587 self.add('separator', cnf or kw)
2588 def insert(self, index, itemType, cnf={}, **kw):
2589 """Internal function."""
2590 self.tk.call((self._w, 'insert', index, itemType) +
2591 self._options(cnf, kw))
2592 def insert_cascade(self, index, cnf={}, **kw):
2593 """Add hierarchical menu item at INDEX."""
2594 self.insert(index, 'cascade', cnf or kw)
2595 def insert_checkbutton(self, index, cnf={}, **kw):
2596 """Add checkbutton menu item at INDEX."""
2597 self.insert(index, 'checkbutton', cnf or kw)
2598 def insert_command(self, index, cnf={}, **kw):
2599 """Add command menu item at INDEX."""
2600 self.insert(index, 'command', cnf or kw)
2601 def insert_radiobutton(self, index, cnf={}, **kw):
2602 """Addd radio menu item at INDEX."""
2603 self.insert(index, 'radiobutton', cnf or kw)
2604 def insert_separator(self, index, cnf={}, **kw):
2605 """Add separator at INDEX."""
2606 self.insert(index, 'separator', cnf or kw)
2607 def delete(self, index1, index2=None):
2608 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2609 self.tk.call(self._w, 'delete', index1, index2)
2610 def entrycget(self, index, option):
2611 """Return the resource value of an menu item for OPTION at INDEX."""
2612 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2613 def entryconfigure(self, index, cnf=None, **kw):
2614 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002615 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002616 entryconfig = entryconfigure
2617 def index(self, index):
2618 """Return the index of a menu item identified by INDEX."""
2619 i = self.tk.call(self._w, 'index', index)
2620 if i == 'none': return None
2621 return getint(i)
2622 def invoke(self, index):
2623 """Invoke a menu item identified by INDEX and execute
2624 the associated command."""
2625 return self.tk.call(self._w, 'invoke', index)
2626 def post(self, x, y):
2627 """Display a menu at position X,Y."""
2628 self.tk.call(self._w, 'post', x, y)
2629 def type(self, index):
2630 """Return the type of the menu item at INDEX."""
2631 return self.tk.call(self._w, 'type', index)
2632 def unpost(self):
2633 """Unmap a menu."""
2634 self.tk.call(self._w, 'unpost')
2635 def yposition(self, index):
2636 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2637 return getint(self.tk.call(
2638 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002639
2640class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002641 """Menubutton widget, obsolete since Tk8.0."""
2642 def __init__(self, master=None, cnf={}, **kw):
2643 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002644
2645class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002646 """Message widget to display multiline text. Obsolete since Label does it too."""
2647 def __init__(self, master=None, cnf={}, **kw):
2648 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002649
2650class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002651 """Radiobutton widget which shows only one of several buttons in on-state."""
2652 def __init__(self, master=None, cnf={}, **kw):
2653 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002654
Fredrik Lundh06d28152000-08-09 18:03:12 +00002655 Valid resource names: activebackground, activeforeground, anchor,
2656 background, bd, bg, bitmap, borderwidth, command, cursor,
2657 disabledforeground, fg, font, foreground, height,
2658 highlightbackground, highlightcolor, highlightthickness, image,
2659 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2660 state, takefocus, text, textvariable, underline, value, variable,
2661 width, wraplength."""
2662 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2663 def deselect(self):
2664 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002665
Fredrik Lundh06d28152000-08-09 18:03:12 +00002666 self.tk.call(self._w, 'deselect')
2667 def flash(self):
2668 """Flash the button."""
2669 self.tk.call(self._w, 'flash')
2670 def invoke(self):
2671 """Toggle the button and invoke a command if given as resource."""
2672 return self.tk.call(self._w, 'invoke')
2673 def select(self):
2674 """Put the button in on-state."""
2675 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002676
2677class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002678 """Scale widget which can display a numerical scale."""
2679 def __init__(self, master=None, cnf={}, **kw):
2680 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002681
Fredrik Lundh06d28152000-08-09 18:03:12 +00002682 Valid resource names: activebackground, background, bigincrement, bd,
2683 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2684 highlightbackground, highlightcolor, highlightthickness, label,
2685 length, orient, relief, repeatdelay, repeatinterval, resolution,
2686 showvalue, sliderlength, sliderrelief, state, takefocus,
2687 tickinterval, to, troughcolor, variable, width."""
2688 Widget.__init__(self, master, 'scale', cnf, kw)
2689 def get(self):
2690 """Get the current value as integer or float."""
2691 value = self.tk.call(self._w, 'get')
2692 try:
2693 return getint(value)
2694 except ValueError:
2695 return getdouble(value)
2696 def set(self, value):
2697 """Set the value to VALUE."""
2698 self.tk.call(self._w, 'set', value)
2699 def coords(self, value=None):
2700 """Return a tuple (X,Y) of the point along the centerline of the
2701 trough that corresponds to VALUE or the current value if None is
2702 given."""
2703
2704 return self._getints(self.tk.call(self._w, 'coords', value))
2705 def identify(self, x, y):
2706 """Return where the point X,Y lies. Valid return values are "slider",
2707 "though1" and "though2"."""
2708 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002709
2710class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002711 """Scrollbar widget which displays a slider at a certain position."""
2712 def __init__(self, master=None, cnf={}, **kw):
2713 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002714
Fredrik Lundh06d28152000-08-09 18:03:12 +00002715 Valid resource names: activebackground, activerelief,
2716 background, bd, bg, borderwidth, command, cursor,
2717 elementborderwidth, highlightbackground,
2718 highlightcolor, highlightthickness, jump, orient,
2719 relief, repeatdelay, repeatinterval, takefocus,
2720 troughcolor, width."""
2721 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2722 def activate(self, index):
2723 """Display the element at INDEX with activebackground and activerelief.
2724 INDEX can be "arrow1","slider" or "arrow2"."""
2725 self.tk.call(self._w, 'activate', index)
2726 def delta(self, deltax, deltay):
2727 """Return the fractional change of the scrollbar setting if it
2728 would be moved by DELTAX or DELTAY pixels."""
2729 return getdouble(
2730 self.tk.call(self._w, 'delta', deltax, deltay))
2731 def fraction(self, x, y):
2732 """Return the fractional value which corresponds to a slider
2733 position of X,Y."""
2734 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2735 def identify(self, x, y):
2736 """Return the element under position X,Y as one of
2737 "arrow1","slider","arrow2" or ""."""
2738 return self.tk.call(self._w, 'identify', x, y)
2739 def get(self):
2740 """Return the current fractional values (upper and lower end)
2741 of the slider position."""
2742 return self._getdoubles(self.tk.call(self._w, 'get'))
2743 def set(self, *args):
2744 """Set the fractional values of the slider position (upper and
2745 lower ends as value between 0 and 1)."""
2746 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002747
2748
2749
Guido van Rossum18468821994-06-20 07:49:28 +00002750class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002751 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002752 def __init__(self, master=None, cnf={}, **kw):
2753 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002754
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002755 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002756
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002757 background, borderwidth, cursor,
2758 exportselection, font, foreground,
2759 highlightbackground, highlightcolor,
2760 highlightthickness, insertbackground,
2761 insertborderwidth, insertofftime,
2762 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002763 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002764 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002765 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002766 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002767
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002768 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002769
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002770 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002771 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002772 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002773
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002774 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002775 Widget.__init__(self, master, 'text', cnf, kw)
2776 def bbox(self, *args):
2777 """Return a tuple of (x,y,width,height) which gives the bounding
2778 box of the visible part of the character at the index in ARGS."""
2779 return self._getints(
2780 self.tk.call((self._w, 'bbox') + args)) or None
2781 def tk_textSelectTo(self, index):
2782 self.tk.call('tk_textSelectTo', self._w, index)
2783 def tk_textBackspace(self):
2784 self.tk.call('tk_textBackspace', self._w)
2785 def tk_textIndexCloser(self, a, b, c):
2786 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2787 def tk_textResetAnchor(self, index):
2788 self.tk.call('tk_textResetAnchor', self._w, index)
2789 def compare(self, index1, op, index2):
2790 """Return whether between index INDEX1 and index INDEX2 the
2791 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2792 return self.tk.getboolean(self.tk.call(
2793 self._w, 'compare', index1, op, index2))
2794 def debug(self, boolean=None):
2795 """Turn on the internal consistency checks of the B-Tree inside the text
2796 widget according to BOOLEAN."""
2797 return self.tk.getboolean(self.tk.call(
2798 self._w, 'debug', boolean))
2799 def delete(self, index1, index2=None):
2800 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2801 self.tk.call(self._w, 'delete', index1, index2)
2802 def dlineinfo(self, index):
2803 """Return tuple (x,y,width,height,baseline) giving the bounding box
2804 and baseline position of the visible part of the line containing
2805 the character at INDEX."""
2806 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002807 def dump(self, index1, index2=None, command=None, **kw):
2808 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002809
Guido van Rossum256705b2002-04-23 13:29:43 +00002810 The type of contents returned in filtered based on the keyword
2811 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2812 given and true, then the corresponding items are returned. The result
2813 is a list of triples of the form (key, value, index). If none of the
2814 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002815
Guido van Rossum256705b2002-04-23 13:29:43 +00002816 If the 'command' argument is given, it is called once for each element
2817 of the list of triples, with the values of each triple serving as the
2818 arguments to the function. In this case the list is not returned."""
2819 args = []
2820 func_name = None
2821 result = None
2822 if not command:
2823 # Never call the dump command without the -command flag, since the
2824 # output could involve Tcl quoting and would be a pain to parse
2825 # right. Instead just set the command to build a list of triples
2826 # as if we had done the parsing.
2827 result = []
2828 def append_triple(key, value, index, result=result):
2829 result.append((key, value, index))
2830 command = append_triple
2831 try:
2832 if not isinstance(command, str):
2833 func_name = command = self._register(command)
2834 args += ["-command", command]
2835 for key in kw:
2836 if kw[key]: args.append("-" + key)
2837 args.append(index1)
2838 if index2:
2839 args.append(index2)
2840 self.tk.call(self._w, "dump", *args)
2841 return result
2842 finally:
2843 if func_name:
2844 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002845
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002846 ## new in tk8.4
2847 def edit(self, *args):
2848 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002849
2850 This method controls the undo mechanism and
2851 the modified flag. The exact behavior of the
2852 command depends on the option argument that
2853 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002854 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002855
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002856 edit_modified, edit_redo, edit_reset, edit_separator
2857 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002858
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002859 """
2860 return self._getints(
2861 self.tk.call((self._w, 'edit') + args)) or ()
2862
2863 def edit_modified(self, arg=None):
2864 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002865
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002866 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002867 flag of the widget. The insert, delete, edit undo and
2868 edit redo commands or the user can set or clear the
2869 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002870 modified flag of the widget to arg.
2871 """
2872 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002873
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002874 def edit_redo(self):
2875 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002876
2877 When the undo option is true, reapplies the last
2878 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002879 then. Generates an error when the redo stack is empty.
2880 Does nothing when the undo option is false.
2881 """
2882 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002883
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002884 def edit_reset(self):
2885 """Clears the undo and redo stacks
2886 """
2887 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002888
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002889 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002890 """Inserts a separator (boundary) on the undo stack.
2891
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002892 Does nothing when the undo option is false
2893 """
2894 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002895
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002896 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002897 """Undoes the last edit action
2898
2899 If the undo option is true. An edit action is defined
2900 as all the insert and delete commands that are recorded
2901 on the undo stack in between two separators. Generates
2902 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002903 when the undo option is false
2904 """
2905 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002906
Fredrik Lundh06d28152000-08-09 18:03:12 +00002907 def get(self, index1, index2=None):
2908 """Return the text from INDEX1 to INDEX2 (not included)."""
2909 return self.tk.call(self._w, 'get', index1, index2)
2910 # (Image commands are new in 8.0)
2911 def image_cget(self, index, option):
2912 """Return the value of OPTION of an embedded image at INDEX."""
2913 if option[:1] != "-":
2914 option = "-" + option
2915 if option[-1:] == "_":
2916 option = option[:-1]
2917 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002918 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002919 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002920 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002921 def image_create(self, index, cnf={}, **kw):
2922 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002923 return self.tk.call(
2924 self._w, "image", "create", index,
2925 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002926 def image_names(self):
2927 """Return all names of embedded images in this widget."""
2928 return self.tk.call(self._w, "image", "names")
2929 def index(self, index):
2930 """Return the index in the form line.char for INDEX."""
2931 return self.tk.call(self._w, 'index', index)
2932 def insert(self, index, chars, *args):
2933 """Insert CHARS before the characters at INDEX. An additional
2934 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2935 self.tk.call((self._w, 'insert', index, chars) + args)
2936 def mark_gravity(self, markName, direction=None):
2937 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2938 Return the current value if None is given for DIRECTION."""
2939 return self.tk.call(
2940 (self._w, 'mark', 'gravity', markName, direction))
2941 def mark_names(self):
2942 """Return all mark names."""
2943 return self.tk.splitlist(self.tk.call(
2944 self._w, 'mark', 'names'))
2945 def mark_set(self, markName, index):
2946 """Set mark MARKNAME before the character at INDEX."""
2947 self.tk.call(self._w, 'mark', 'set', markName, index)
2948 def mark_unset(self, *markNames):
2949 """Delete all marks in MARKNAMES."""
2950 self.tk.call((self._w, 'mark', 'unset') + markNames)
2951 def mark_next(self, index):
2952 """Return the name of the next mark after INDEX."""
2953 return self.tk.call(self._w, 'mark', 'next', index) or None
2954 def mark_previous(self, index):
2955 """Return the name of the previous mark before INDEX."""
2956 return self.tk.call(self._w, 'mark', 'previous', index) or None
2957 def scan_mark(self, x, y):
2958 """Remember the current X, Y coordinates."""
2959 self.tk.call(self._w, 'scan', 'mark', x, y)
2960 def scan_dragto(self, x, y):
2961 """Adjust the view of the text to 10 times the
2962 difference between X and Y and the coordinates given in
2963 scan_mark."""
2964 self.tk.call(self._w, 'scan', 'dragto', x, y)
2965 def search(self, pattern, index, stopindex=None,
2966 forwards=None, backwards=None, exact=None,
2967 regexp=None, nocase=None, count=None):
2968 """Search PATTERN beginning from INDEX until STOPINDEX.
2969 Return the index of the first character of a match or an empty string."""
2970 args = [self._w, 'search']
2971 if forwards: args.append('-forwards')
2972 if backwards: args.append('-backwards')
2973 if exact: args.append('-exact')
2974 if regexp: args.append('-regexp')
2975 if nocase: args.append('-nocase')
2976 if count: args.append('-count'); args.append(count)
2977 if pattern[0] == '-': args.append('--')
2978 args.append(pattern)
2979 args.append(index)
2980 if stopindex: args.append(stopindex)
2981 return self.tk.call(tuple(args))
2982 def see(self, index):
2983 """Scroll such that the character at INDEX is visible."""
2984 self.tk.call(self._w, 'see', index)
2985 def tag_add(self, tagName, index1, *args):
2986 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
2987 Additional pairs of indices may follow in ARGS."""
2988 self.tk.call(
2989 (self._w, 'tag', 'add', tagName, index1) + args)
2990 def tag_unbind(self, tagName, sequence, funcid=None):
2991 """Unbind for all characters with TAGNAME for event SEQUENCE the
2992 function identified with FUNCID."""
2993 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
2994 if funcid:
2995 self.deletecommand(funcid)
2996 def tag_bind(self, tagName, sequence, func, add=None):
2997 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002998
Fredrik Lundh06d28152000-08-09 18:03:12 +00002999 An additional boolean parameter ADD specifies whether FUNC will be
3000 called additionally to the other bound function or whether it will
3001 replace the previous function. See bind for the return value."""
3002 return self._bind((self._w, 'tag', 'bind', tagName),
3003 sequence, func, add)
3004 def tag_cget(self, tagName, option):
3005 """Return the value of OPTION for tag TAGNAME."""
3006 if option[:1] != '-':
3007 option = '-' + option
3008 if option[-1:] == '_':
3009 option = option[:-1]
3010 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003011 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003012 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003013 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003014 tag_config = tag_configure
3015 def tag_delete(self, *tagNames):
3016 """Delete all tags in TAGNAMES."""
3017 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3018 def tag_lower(self, tagName, belowThis=None):
3019 """Change the priority of tag TAGNAME such that it is lower
3020 than the priority of BELOWTHIS."""
3021 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3022 def tag_names(self, index=None):
3023 """Return a list of all tag names."""
3024 return self.tk.splitlist(
3025 self.tk.call(self._w, 'tag', 'names', index))
3026 def tag_nextrange(self, tagName, index1, index2=None):
3027 """Return a list of start and end index for the first sequence of
3028 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3029 The text is searched forward from INDEX1."""
3030 return self.tk.splitlist(self.tk.call(
3031 self._w, 'tag', 'nextrange', tagName, index1, index2))
3032 def tag_prevrange(self, tagName, index1, index2=None):
3033 """Return a list of start and end index for the first sequence of
3034 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3035 The text is searched backwards from INDEX1."""
3036 return self.tk.splitlist(self.tk.call(
3037 self._w, 'tag', 'prevrange', tagName, index1, index2))
3038 def tag_raise(self, tagName, aboveThis=None):
3039 """Change the priority of tag TAGNAME such that it is higher
3040 than the priority of ABOVETHIS."""
3041 self.tk.call(
3042 self._w, 'tag', 'raise', tagName, aboveThis)
3043 def tag_ranges(self, tagName):
3044 """Return a list of ranges of text which have tag TAGNAME."""
3045 return self.tk.splitlist(self.tk.call(
3046 self._w, 'tag', 'ranges', tagName))
3047 def tag_remove(self, tagName, index1, index2=None):
3048 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3049 self.tk.call(
3050 self._w, 'tag', 'remove', tagName, index1, index2)
3051 def window_cget(self, index, option):
3052 """Return the value of OPTION of an embedded window at INDEX."""
3053 if option[:1] != '-':
3054 option = '-' + option
3055 if option[-1:] == '_':
3056 option = option[:-1]
3057 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003058 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003059 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003060 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003061 window_config = window_configure
3062 def window_create(self, index, cnf={}, **kw):
3063 """Create a window at INDEX."""
3064 self.tk.call(
3065 (self._w, 'window', 'create', index)
3066 + self._options(cnf, kw))
3067 def window_names(self):
3068 """Return all names of embedded windows in this widget."""
3069 return self.tk.splitlist(
3070 self.tk.call(self._w, 'window', 'names'))
3071 def xview(self, *what):
3072 """Query and change horizontal position of the view."""
3073 if not what:
3074 return self._getdoubles(self.tk.call(self._w, 'xview'))
3075 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003076 def xview_moveto(self, fraction):
3077 """Adjusts the view in the window so that FRACTION of the
3078 total width of the canvas is off-screen to the left."""
3079 self.tk.call(self._w, 'xview', 'moveto', fraction)
3080 def xview_scroll(self, number, what):
3081 """Shift the x-view according to NUMBER which is measured
3082 in "units" or "pages" (WHAT)."""
3083 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003084 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003085 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003086 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003087 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003088 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003089 def yview_moveto(self, fraction):
3090 """Adjusts the view in the window so that FRACTION of the
3091 total height of the canvas is off-screen to the top."""
3092 self.tk.call(self._w, 'yview', 'moveto', fraction)
3093 def yview_scroll(self, number, what):
3094 """Shift the y-view according to NUMBER which is measured
3095 in "units" or "pages" (WHAT)."""
3096 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003097 def yview_pickplace(self, *what):
3098 """Obsolete function, use see."""
3099 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003100
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003101
Guido van Rossum28574b51996-10-21 15:16:51 +00003102class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003103 """Internal class. It wraps the command in the widget OptionMenu."""
3104 def __init__(self, var, value, callback=None):
3105 self.__value = value
3106 self.__var = var
3107 self.__callback = callback
3108 def __call__(self, *args):
3109 self.__var.set(self.__value)
3110 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003111 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003112
3113class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003114 """OptionMenu which allows the user to select a value from a menu."""
3115 def __init__(self, master, variable, value, *values, **kwargs):
3116 """Construct an optionmenu widget with the parent MASTER, with
3117 the resource textvariable set to VARIABLE, the initially selected
3118 value VALUE, the other menu values VALUES and an additional
3119 keyword argument command."""
3120 kw = {"borderwidth": 2, "textvariable": variable,
3121 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3122 "highlightthickness": 2}
3123 Widget.__init__(self, master, "menubutton", kw)
3124 self.widgetName = 'tk_optionMenu'
3125 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3126 self.menuname = menu._w
3127 # 'command' is the only supported keyword
3128 callback = kwargs.get('command')
3129 if kwargs.has_key('command'):
3130 del kwargs['command']
3131 if kwargs:
3132 raise TclError, 'unknown option -'+kwargs.keys()[0]
3133 menu.add_command(label=value,
3134 command=_setit(variable, value, callback))
3135 for v in values:
3136 menu.add_command(label=v,
3137 command=_setit(variable, v, callback))
3138 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003139
Fredrik Lundh06d28152000-08-09 18:03:12 +00003140 def __getitem__(self, name):
3141 if name == 'menu':
3142 return self.__menu
3143 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003144
Fredrik Lundh06d28152000-08-09 18:03:12 +00003145 def destroy(self):
3146 """Destroy this widget and the associated menu."""
3147 Menubutton.destroy(self)
3148 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003149
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003150class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003151 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003152 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003153 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3154 self.name = None
3155 if not master:
3156 master = _default_root
3157 if not master:
3158 raise RuntimeError, 'Too early to create image'
3159 self.tk = master.tk
3160 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003161 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003162 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003163 # The following is needed for systems where id(x)
3164 # can return a negative number, such as Linux/m68k:
3165 if name[0] == '-': name = '_' + name[1:]
3166 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3167 elif kw: cnf = kw
3168 options = ()
3169 for k, v in cnf.items():
3170 if callable(v):
3171 v = self._register(v)
3172 options = options + ('-'+k, v)
3173 self.tk.call(('image', 'create', imgtype, name,) + options)
3174 self.name = name
3175 def __str__(self): return self.name
3176 def __del__(self):
3177 if self.name:
3178 try:
3179 self.tk.call('image', 'delete', self.name)
3180 except TclError:
3181 # May happen if the root was destroyed
3182 pass
3183 def __setitem__(self, key, value):
3184 self.tk.call(self.name, 'configure', '-'+key, value)
3185 def __getitem__(self, key):
3186 return self.tk.call(self.name, 'configure', '-'+key)
3187 def configure(self, **kw):
3188 """Configure the image."""
3189 res = ()
3190 for k, v in _cnfmerge(kw).items():
3191 if v is not None:
3192 if k[-1] == '_': k = k[:-1]
3193 if callable(v):
3194 v = self._register(v)
3195 res = res + ('-'+k, v)
3196 self.tk.call((self.name, 'config') + res)
3197 config = configure
3198 def height(self):
3199 """Return the height of the image."""
3200 return getint(
3201 self.tk.call('image', 'height', self.name))
3202 def type(self):
3203 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3204 return self.tk.call('image', 'type', self.name)
3205 def width(self):
3206 """Return the width of the image."""
3207 return getint(
3208 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003209
3210class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003211 """Widget which can display colored images in GIF, PPM/PGM format."""
3212 def __init__(self, name=None, cnf={}, master=None, **kw):
3213 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003214
Fredrik Lundh06d28152000-08-09 18:03:12 +00003215 Valid resource names: data, format, file, gamma, height, palette,
3216 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003217 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003218 def blank(self):
3219 """Display a transparent image."""
3220 self.tk.call(self.name, 'blank')
3221 def cget(self, option):
3222 """Return the value of OPTION."""
3223 return self.tk.call(self.name, 'cget', '-' + option)
3224 # XXX config
3225 def __getitem__(self, key):
3226 return self.tk.call(self.name, 'cget', '-' + key)
3227 # XXX copy -from, -to, ...?
3228 def copy(self):
3229 """Return a new PhotoImage with the same image as this widget."""
3230 destImage = PhotoImage()
3231 self.tk.call(destImage, 'copy', self.name)
3232 return destImage
3233 def zoom(self,x,y=''):
3234 """Return a new PhotoImage with the same image as this widget
3235 but zoom it with X and Y."""
3236 destImage = PhotoImage()
3237 if y=='': y=x
3238 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3239 return destImage
3240 def subsample(self,x,y=''):
3241 """Return a new PhotoImage based on the same image as this widget
3242 but use only every Xth or Yth pixel."""
3243 destImage = PhotoImage()
3244 if y=='': y=x
3245 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3246 return destImage
3247 def get(self, x, y):
3248 """Return the color (red, green, blue) of the pixel at X,Y."""
3249 return self.tk.call(self.name, 'get', x, y)
3250 def put(self, data, to=None):
3251 """Put row formated colors to image starting from
3252 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3253 args = (self.name, 'put', data)
3254 if to:
3255 if to[0] == '-to':
3256 to = to[1:]
3257 args = args + ('-to',) + tuple(to)
3258 self.tk.call(args)
3259 # XXX read
3260 def write(self, filename, format=None, from_coords=None):
3261 """Write image to file FILENAME in FORMAT starting from
3262 position FROM_COORDS."""
3263 args = (self.name, 'write', filename)
3264 if format:
3265 args = args + ('-format', format)
3266 if from_coords:
3267 args = args + ('-from',) + tuple(from_coords)
3268 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003269
3270class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003271 """Widget which can display a bitmap."""
3272 def __init__(self, name=None, cnf={}, master=None, **kw):
3273 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003274
Fredrik Lundh06d28152000-08-09 18:03:12 +00003275 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003276 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003277
3278def image_names(): return _default_root.tk.call('image', 'names')
3279def image_types(): return _default_root.tk.call('image', 'types')
3280
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003281
3282class Spinbox(Widget):
3283 """spinbox widget."""
3284 def __init__(self, master=None, cnf={}, **kw):
3285 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003286
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003287 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003288
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003289 activebackground, background, borderwidth,
3290 cursor, exportselection, font, foreground,
3291 highlightbackground, highlightcolor,
3292 highlightthickness, insertbackground,
3293 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003294 insertontime, insertwidth, justify, relief,
3295 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003296 selectbackground, selectborderwidth
3297 selectforeground, takefocus, textvariable
3298 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003299
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003300 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003301
3302 buttonbackground, buttoncursor,
3303 buttondownrelief, buttonuprelief,
3304 command, disabledbackground,
3305 disabledforeground, format, from,
3306 invalidcommand, increment,
3307 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003308 validate, validatecommand values,
3309 width, wrap,
3310 """
3311 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003312
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003313 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003314 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3315 rectangle which encloses the character given by index.
3316
3317 The first two elements of the list give the x and y
3318 coordinates of the upper-left corner of the screen
3319 area covered by the character (in pixels relative
3320 to the widget) and the last two elements give the
3321 width and height of the character, in pixels. The
3322 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003323 visible area of the window.
3324 """
3325 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003326
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003327 def delete(self, first, last=None):
3328 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003329
3330 First is the index of the first character to delete,
3331 and last is the index of the character just after
3332 the last one to delete. If last isn't specified it
3333 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003334 deleted. This command returns an empty string.
3335 """
3336 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003337
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003338 def get(self):
3339 """Returns the spinbox's string"""
3340 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003341
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003342 def icursor(self, index):
3343 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003344
3345 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003346 the character given by index. Returns an empty string
3347 """
3348 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003349
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003350 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003351 """Returns the name of the widget at position x, y
3352
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003353 Return value is one of: none, buttondown, buttonup, entry
3354 """
3355 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003356
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003357 def index(self, index):
3358 """Returns the numerical index corresponding to index
3359 """
3360 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003361
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003362 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003363 """Insert string s at index
3364
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003365 Returns an empty string.
3366 """
3367 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003368
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003369 def invoke(self, element):
3370 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003371
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003372 The element could be buttondown or buttonup
3373 triggering the action associated with it.
3374 """
3375 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003376
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003377 def scan(self, *args):
3378 """Internal function."""
3379 return self._getints(
3380 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003381
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003382 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003383 """Records x and the current view in the spinbox window;
3384
3385 used in conjunction with later scan dragto commands.
3386 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003387 press in the widget. It returns an empty string.
3388 """
3389 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003390
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003391 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003392 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003393 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003394
3395 It then adjusts the view left or right by 10 times the
3396 difference in x-coordinates. This command is typically
3397 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003398 produce the effect of dragging the spinbox at high speed
3399 through the window. The return value is an empty string.
3400 """
3401 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003402
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003403 def selection(self, *args):
3404 """Internal function."""
3405 return self._getints(
3406 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003407
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003408 def selection_adjust(self, index):
3409 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003410 given by index,
3411
3412 Then adjust that end of the selection to be at index
3413 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003414 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003415 select to commands. If the selection isn't currently in
3416 the spinbox, then a new selection is created to include
3417 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003418 anchor point, inclusive. Returns an empty string.
3419 """
3420 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003421
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003422 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003423 """Clear the selection
3424
3425 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003426 command has no effect. Returns an empty string.
3427 """
3428 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003429
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003430 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003431 """Sets or gets the currently selected element.
3432
3433 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003434 displayed depressed
3435 """
3436 return self.selection("element", element)
3437
3438###########################################################################
3439
3440class LabelFrame(Widget):
3441 """labelframe widget."""
3442 def __init__(self, master=None, cnf={}, **kw):
3443 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003444
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003445 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003446
3447 borderwidth, cursor, font, foreground,
3448 highlightbackground, highlightcolor,
3449 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003450 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003451
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003452 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003453
3454 background, class, colormap, container,
3455 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003456 visual, width
3457 """
3458 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003459
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003460########################################################################
3461
3462class PanedWindow(Widget):
3463 """panedwindow widget."""
3464 def __init__(self, master=None, cnf={}, **kw):
3465 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003466
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003467 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003468
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003469 background, borderwidth, cursor, height,
3470 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003471
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003472 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003473
3474 handlepad, handlesize, opaqueresize,
3475 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003476 sashwidth, showhandle,
3477 """
3478 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3479
3480 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003481 """Add a child widget to the panedwindow in a new pane.
3482
3483 The child argument is the name of the child widget
3484 followed by pairs of arguments that specify how to
3485 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003486 accepted by the configure subcommand.
3487 """
3488 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003489
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003490 def remove(self, child):
3491 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003492
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003493 All geometry management options for child will be forgotten.
3494 """
3495 self.tk.call(self._w, 'forget', child)
3496 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003497
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003498 def identify(self, x, y):
3499 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003500
3501 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003502 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003503 handle, and a word indicating whether it is over a sash
3504 or a handle, such as {0 sash} or {2 handle}. If the point
3505 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003506 an empty list.
3507 """
3508 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003509
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003510 def proxy(self, *args):
3511 """Internal function."""
3512 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003513 self.tk.call((self._w, 'proxy') + args)) or ()
3514
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003515 def proxy_coord(self):
3516 """Return the x and y pair of the most recent proxy location
3517 """
3518 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003519
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003520 def proxy_forget(self):
3521 """Remove the proxy from the display.
3522 """
3523 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003524
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003525 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003526 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003527 """
3528 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003529
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003530 def sash(self, *args):
3531 """Internal function."""
3532 return self._getints(
3533 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003534
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003535 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003536 """Return the current x and y pair for the sash given by index.
3537
3538 Index must be an integer between 0 and 1 less than the
3539 number of panes in the panedwindow. The coordinates given are
3540 those of the top left corner of the region containing the sash.
3541 pathName sash dragto index x y This command computes the
3542 difference between the given coordinates and the coordinates
3543 given to the last sash coord command for the given sash. It then
3544 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003545 empty string.
3546 """
3547 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003548
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003549 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003550 """Records x and y for the sash given by index;
3551
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003552 Used in conjunction with later dragto commands to move the sash.
3553 """
3554 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003555
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003556 def sash_place(self, index, x, y):
3557 """Place the sash given by index at the given coordinates
3558 """
3559 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003560
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003561 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003562 """Query a management option for window.
3563
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003564 Option may be any value allowed by the paneconfigure subcommand
3565 """
3566 return self.tk.call(
3567 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003568
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003569 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003570 """Query or modify the management options for window.
3571
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003572 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003573 of the available options for pathName. If option is
3574 specified with no value, then the command returns a list
3575 describing the one named option (this list will be identical
3576 to the corresponding sublist of the value returned if no
3577 option is specified). If one or more option-value pairs are
3578 specified, then the command modifies the given widget
3579 option(s) to have the given value(s); in this case the
3580 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003581 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003582
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003583 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003584 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003585 should be the name of a window already managed by pathName.
3586 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003587 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003588 should be the name of a window already managed by pathName.
3589 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003590 Specify a height for the window. The height will be the
3591 outer dimension of the window including its border, if
3592 any. If size is an empty string, or if -height is not
3593 specified, then the height requested internally by the
3594 window will be used initially; the height may later be
3595 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003596 Size may be any value accepted by Tk_GetPixels.
3597 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003598 Specifies that the size of the window cannot be made
3599 less than n. This constraint only affects the size of
3600 the widget in the paned dimension -- the x dimension
3601 for horizontal panedwindows, the y dimension for
3602 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003603 Tk_GetPixels.
3604 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003605 Specifies a non-negative value indicating how much
3606 extra space to leave on each side of the window in
3607 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003608 accepted by Tk_GetPixels.
3609 pady n
3610 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003611 extra space to leave on each side of the window in
3612 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003613 accepted by Tk_GetPixels.
3614 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003615 If a window's pane is larger than the requested
3616 dimensions of the window, this option may be used
3617 to position (or stretch) the window within its pane.
3618 Style is a string that contains zero or more of the
3619 characters n, s, e or w. The string can optionally
3620 contains spaces or commas, but they are ignored. Each
3621 letter refers to a side (north, south, east, or west)
3622 that the window will "stick" to. If both n and s
3623 (or e and w) are specified, the window will be
3624 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003625 its cavity.
3626 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003627 Specify a width for the window. The width will be
3628 the outer dimension of the window including its
3629 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003630 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003631 internally by the window will be used initially; the
3632 width may later be adjusted by the movement of sashes
3633 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003634 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003635
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003636 """
3637 if cnf is None and not kw:
3638 cnf = {}
3639 for x in self.tk.split(
3640 self.tk.call(self._w,
3641 'paneconfigure', tagOrId)):
3642 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3643 return cnf
3644 if type(cnf) == StringType and not kw:
3645 x = self.tk.split(self.tk.call(
3646 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3647 return (x[0][1:],) + x[1:]
3648 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3649 self._options(cnf, kw))
3650 paneconfig = paneconfigure
3651
3652 def panes(self):
3653 """Returns an ordered list of the child panes."""
3654 return self.tk.call(self._w, 'panes')
3655
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003656######################################################################
3657# Extensions:
3658
3659class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003660 def __init__(self, master=None, cnf={}, **kw):
3661 Widget.__init__(self, master, 'studbutton', cnf, kw)
3662 self.bind('<Any-Enter>', self.tkButtonEnter)
3663 self.bind('<Any-Leave>', self.tkButtonLeave)
3664 self.bind('<1>', self.tkButtonDown)
3665 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003666
3667class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003668 def __init__(self, master=None, cnf={}, **kw):
3669 Widget.__init__(self, master, 'tributton', cnf, kw)
3670 self.bind('<Any-Enter>', self.tkButtonEnter)
3671 self.bind('<Any-Leave>', self.tkButtonLeave)
3672 self.bind('<1>', self.tkButtonDown)
3673 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3674 self['fg'] = self['bg']
3675 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003676
Guido van Rossumc417ef81996-08-21 23:38:59 +00003677######################################################################
3678# Test:
3679
3680def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003681 root = Tk()
3682 text = "This is Tcl/Tk version %s" % TclVersion
3683 if TclVersion >= 8.1:
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003684 try:
3685 text = text + unicode("\nThis should be a cedilla: \347",
3686 "iso-8859-1")
3687 except NameError:
3688 pass # no unicode support
Fredrik Lundh06d28152000-08-09 18:03:12 +00003689 label = Label(root, text=text)
3690 label.pack()
3691 test = Button(root, text="Click me!",
3692 command=lambda root=root: root.test.configure(
3693 text="[%s]" % root.test['text']))
3694 test.pack()
3695 root.test = test
3696 quit = Button(root, text="QUIT", command=root.destroy)
3697 quit.pack()
3698 # The following three commands are needed so the window pops
3699 # up on top on Windows...
3700 root.iconify()
3701 root.update()
3702 root.deiconify()
3703 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003704
3705if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003706 _test()