blob: 144be0a1a8876731b87ebfd0318d69bf212d3b05 [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 Rossuma5773dd1995-09-07 19:22:00 +000041from Tkconstants import *
Guido van Rossumf0c891a1998-04-29 21:43:36 +000042try:
Fredrik Lundh06d28152000-08-09 18:03:12 +000043 import MacOS; _MacOS = MacOS; del MacOS
Guido van Rossumf0c891a1998-04-29 21:43:36 +000044except ImportError:
Fredrik Lundh06d28152000-08-09 18:03:12 +000045 _MacOS = None
Guido van Rossum18468821994-06-20 07:49:28 +000046
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000047wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000048
Eric S. Raymondfc170b12001-02-09 11:51:27 +000049TkVersion = float(_tkinter.TK_VERSION)
50TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000051
Guido van Rossumd6615ab1997-08-05 02:35:01 +000052READABLE = _tkinter.READABLE
53WRITABLE = _tkinter.WRITABLE
54EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000055
56# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
57try: _tkinter.createfilehandler
58except AttributeError: _tkinter.createfilehandler = None
59try: _tkinter.deletefilehandler
60except AttributeError: _tkinter.deletefilehandler = None
Fredrik Lundh06d28152000-08-09 18:03:12 +000061
62
Guido van Rossum13257902007-06-07 23:15:56 +000063def _flatten(seq):
Fredrik Lundh06d28152000-08-09 18:03:12 +000064 """Internal function."""
65 res = ()
Guido van Rossum13257902007-06-07 23:15:56 +000066 for item in seq:
67 if isinstance(item, (tuple, list)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000068 res = res + _flatten(item)
69 elif item is not None:
70 res = res + (item,)
71 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000072
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000073try: _flatten = _tkinter._flatten
74except AttributeError: pass
75
Guido van Rossum2dcf5291994-07-06 09:23:20 +000076def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000077 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +000078 if isinstance(cnfs, dict):
Fredrik Lundh06d28152000-08-09 18:03:12 +000079 return cnfs
Guido van Rossum13257902007-06-07 23:15:56 +000080 elif isinstance(cnfs, (type(None), str)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000081 return cnfs
82 else:
83 cnf = {}
84 for c in _flatten(cnfs):
85 try:
86 cnf.update(c)
Guido van Rossumb940e112007-01-10 16:19:56 +000087 except (AttributeError, TypeError) as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000088 print("_cnfmerge: fallback due to:", msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +000089 for k, v in c.items():
90 cnf[k] = v
91 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000092
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000093try: _cnfmerge = _tkinter._cnfmerge
94except AttributeError: pass
95
Guido van Rossum2dcf5291994-07-06 09:23:20 +000096class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000097 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000098
Fredrik Lundh06d28152000-08-09 18:03:12 +000099 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000100
Fredrik Lundh06d28152000-08-09 18:03:12 +0000101 KeyPress, KeyRelease - for keyboard events
102 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
103 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
104 Colormap, Gravity, Reparent, Property, Destroy, Activate,
105 Deactivate - for window events.
106
107 If a callback function for one of these events is registered
108 using bind, bind_all, bind_class, or tag_bind, the callback is
109 called with an Event as first argument. It will have the
110 following attributes (in braces are the event types for which
111 the attribute is valid):
112
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000113 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000114 num - mouse button pressed (ButtonPress, ButtonRelease)
115 focus - whether the window has the focus (Enter, Leave)
116 height - height of the exposed window (Configure, Expose)
117 width - width of the exposed window (Configure, Expose)
118 keycode - keycode of the pressed key (KeyPress, KeyRelease)
119 state - state of the event as a number (ButtonPress, ButtonRelease,
120 Enter, KeyPress, KeyRelease,
121 Leave, Motion)
122 state - state as a string (Visibility)
123 time - when the event occurred
124 x - x-position of the mouse
125 y - y-position of the mouse
126 x_root - x-position of the mouse on the screen
127 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
128 y_root - y-position of the mouse on the screen
129 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
130 char - pressed character (KeyPress, KeyRelease)
131 send_event - see X/Windows documentation
Walter Dörwald966c2642005-11-09 17:12:43 +0000132 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000133 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
134 type - type of the event as a number
135 widget - widget in which the event occurred
136 delta - delta of wheel movement (MouseWheel)
137 """
138 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000139
Guido van Rossumc4570481998-03-20 20:45:49 +0000140_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000141_default_root = None
142
Guido van Rossumc4570481998-03-20 20:45:49 +0000143def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000144 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000145
Fredrik Lundh06d28152000-08-09 18:03:12 +0000146 Call this function to inhibit that the first instance of
147 Tk is used for windows without an explicit parent window.
148 """
149 global _support_default_root
150 _support_default_root = 0
151 global _default_root
152 _default_root = None
153 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000154
Guido van Rossum45853db1994-06-20 12:19:19 +0000155def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000156 """Internal function."""
157 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000158
Guido van Rossum97aeca11994-07-07 13:12:12 +0000159def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000160 """Internal function. Calling it will throw the exception SystemExit."""
161 raise SystemExit, code
Guido van Rossum97aeca11994-07-07 13:12:12 +0000162
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000163_varnum = 0
164class Variable:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000165 """Class to define value holders for e.g. buttons.
166
167 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
168 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000169 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000170 def __init__(self, master=None, value=None, name=None):
171 """Construct a variable
172
173 MASTER can be given as master widget.
174 VALUE is an optional value (defaults to "")
175 NAME is an optional Tcl name (defaults to PY_VARnum).
176
177 If NAME matches an existing variable and VALUE is omitted
178 then the existing value is retained.
Fredrik Lundh06d28152000-08-09 18:03:12 +0000179 """
180 global _varnum
181 if not master:
182 master = _default_root
183 self._master = master
184 self._tk = master.tk
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185 if name:
186 self._name = name
187 else:
188 self._name = 'PY_VAR' + repr(_varnum)
189 _varnum += 1
190 if value != None:
191 self.set(value)
192 elif not self._tk.call("info", "exists", self._name):
193 self.set(self._default)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000194 def __del__(self):
195 """Unset the variable in Tcl."""
196 self._tk.globalunsetvar(self._name)
197 def __str__(self):
198 """Return the name of the variable in Tcl."""
199 return self._name
200 def set(self, value):
201 """Set the variable to VALUE."""
202 return self._tk.globalsetvar(self._name, value)
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000203 def get(self):
204 """Return value of variable."""
205 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000206 def trace_variable(self, mode, callback):
207 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000208
Fredrik Lundh06d28152000-08-09 18:03:12 +0000209 MODE is one of "r", "w", "u" for read, write, undefine.
210 CALLBACK must be a function which is called when
211 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000212
Fredrik Lundh06d28152000-08-09 18:03:12 +0000213 Return the name of the callback.
214 """
215 cbname = self._master._register(callback)
216 self._tk.call("trace", "variable", self._name, mode, cbname)
217 return cbname
218 trace = trace_variable
219 def trace_vdelete(self, mode, cbname):
220 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000221
Fredrik Lundh06d28152000-08-09 18:03:12 +0000222 MODE is one of "r", "w", "u" for read, write, undefine.
223 CBNAME is the name of the callback returned from trace_variable or trace.
224 """
225 self._tk.call("trace", "vdelete", self._name, mode, cbname)
226 self._master.deletecommand(cbname)
227 def trace_vinfo(self):
228 """Return all trace callback information."""
229 return map(self._tk.split, self._tk.splitlist(
230 self._tk.call("trace", "vinfo", self._name)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000231 def __eq__(self, other):
232 """Comparison for equality (==).
233
234 Note: if the Variable's master matters to behavior
235 also compare self._master == other._master
236 """
237 return self.__class__.__name__ == other.__class__.__name__ \
238 and self._name == other._name
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000239
240class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000241 """Value holder for strings variables."""
242 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000243 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000244 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000245
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000246 MASTER can be given as master widget.
247 VALUE is an optional value (defaults to "")
248 NAME is an optional Tcl name (defaults to PY_VARnum).
249
250 If NAME matches an existing variable and VALUE is omitted
251 then the existing value is retained.
252 """
253 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000254
Fredrik Lundh06d28152000-08-09 18:03:12 +0000255 def get(self):
256 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000257 value = self._tk.globalgetvar(self._name)
258 if isinstance(value, basestring):
259 return value
260 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000261
262class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000263 """Value holder for integer variables."""
264 _default = 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000265 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000266 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000267
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000268 MASTER can be given as master widget.
269 VALUE is an optional value (defaults to 0)
270 NAME is an optional Tcl name (defaults to PY_VARnum).
271
272 If NAME matches an existing variable and VALUE is omitted
273 then the existing value is retained.
274 """
275 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000276
Martin v. Löwis70c3dda2003-01-22 09:17:38 +0000277 def set(self, value):
278 """Set the variable to value, converting booleans to integers."""
279 if isinstance(value, bool):
280 value = int(value)
281 return Variable.set(self, value)
282
Fredrik Lundh06d28152000-08-09 18:03:12 +0000283 def get(self):
284 """Return the value of the variable as an integer."""
285 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000286
287class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000288 """Value holder for float variables."""
289 _default = 0.0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000290 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000291 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000292
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000293 MASTER can be given as master widget.
294 VALUE is an optional value (defaults to 0.0)
295 NAME is an optional Tcl name (defaults to PY_VARnum).
296
297 If NAME matches an existing variable and VALUE is omitted
298 then the existing value is retained.
299 """
300 Variable.__init__(self, master, value, name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000301
302 def get(self):
303 """Return the value of the variable as a float."""
304 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000305
306class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000307 """Value holder for boolean variables."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000308 _default = False
309 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000310 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000311
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000312 MASTER can be given as master widget.
313 VALUE is an optional value (defaults to False)
314 NAME is an optional Tcl name (defaults to PY_VARnum).
315
316 If NAME matches an existing variable and VALUE is omitted
317 then the existing value is retained.
318 """
319 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000320
Fredrik Lundh06d28152000-08-09 18:03:12 +0000321 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000322 """Return the value of the variable as a bool."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000323 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000324
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000325def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000326 """Run the main loop of Tcl."""
327 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000328
Guido van Rossum0132f691998-04-30 17:50:36 +0000329getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000330
Guido van Rossum0132f691998-04-30 17:50:36 +0000331getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000332
333def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000334 """Convert true and false to integer values 1 and 0."""
335 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000336
Guido van Rossum368e06b1997-11-07 20:38:49 +0000337# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000338class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000339 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000340
Fredrik Lundh06d28152000-08-09 18:03:12 +0000341 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000342
Fredrik Lundh06d28152000-08-09 18:03:12 +0000343 # XXX font command?
344 _tclCommands = None
345 def destroy(self):
346 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000347
Fredrik Lundh06d28152000-08-09 18:03:12 +0000348 Delete all Tcl commands created for
349 this widget in the Tcl interpreter."""
350 if self._tclCommands is not None:
351 for name in self._tclCommands:
352 #print '- Tkinter: deleted command', name
353 self.tk.deletecommand(name)
354 self._tclCommands = None
355 def deletecommand(self, name):
356 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000357
Fredrik Lundh06d28152000-08-09 18:03:12 +0000358 Delete the Tcl command provided in NAME."""
359 #print '- Tkinter: deleted command', name
360 self.tk.deletecommand(name)
361 try:
362 self._tclCommands.remove(name)
363 except ValueError:
364 pass
365 def tk_strictMotif(self, boolean=None):
366 """Set Tcl internal variable, whether the look and feel
367 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000368
Fredrik Lundh06d28152000-08-09 18:03:12 +0000369 A parameter of 1 means adhere to Motif (e.g. no color
370 change if mouse passes over slider).
371 Returns the set value."""
372 return self.tk.getboolean(self.tk.call(
373 'set', 'tk_strictMotif', boolean))
374 def tk_bisque(self):
375 """Change the color scheme to light brown as used in Tk 3.6 and before."""
376 self.tk.call('tk_bisque')
377 def tk_setPalette(self, *args, **kw):
378 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000379
Fredrik Lundh06d28152000-08-09 18:03:12 +0000380 A single color as argument will cause that all colors of Tk
381 widget elements are derived from this.
382 Alternatively several keyword parameters and its associated
383 colors can be given. The following keywords are valid:
384 activeBackground, foreground, selectColor,
385 activeForeground, highlightBackground, selectBackground,
386 background, highlightColor, selectForeground,
387 disabledForeground, insertBackground, troughColor."""
388 self.tk.call(('tk_setPalette',)
389 + _flatten(args) + _flatten(kw.items()))
390 def tk_menuBar(self, *args):
391 """Do not use. Needed in Tk 3.6 and earlier."""
392 pass # obsolete since Tk 4.0
393 def wait_variable(self, name='PY_VAR'):
394 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000395
Fredrik Lundh06d28152000-08-09 18:03:12 +0000396 A parameter of type IntVar, StringVar, DoubleVar or
397 BooleanVar must be given."""
398 self.tk.call('tkwait', 'variable', name)
399 waitvar = wait_variable # XXX b/w compat
400 def wait_window(self, window=None):
401 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000402
Fredrik Lundh06d28152000-08-09 18:03:12 +0000403 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000404 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000405 window = self
406 self.tk.call('tkwait', 'window', window._w)
407 def wait_visibility(self, window=None):
408 """Wait until the visibility of a WIDGET changes
409 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000410
Fredrik Lundh06d28152000-08-09 18:03:12 +0000411 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000412 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000413 window = self
414 self.tk.call('tkwait', 'visibility', window._w)
415 def setvar(self, name='PY_VAR', value='1'):
416 """Set Tcl variable NAME to VALUE."""
417 self.tk.setvar(name, value)
418 def getvar(self, name='PY_VAR'):
419 """Return value of Tcl variable NAME."""
420 return self.tk.getvar(name)
421 getint = int
422 getdouble = float
423 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000424 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000425 return self.tk.getboolean(s)
426 def focus_set(self):
427 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000428
Fredrik Lundh06d28152000-08-09 18:03:12 +0000429 If the application currently does not have the focus
430 this widget will get the focus if the application gets
431 the focus through the window manager."""
432 self.tk.call('focus', self._w)
433 focus = focus_set # XXX b/w compat?
434 def focus_force(self):
435 """Direct input focus to this widget even if the
436 application does not have the focus. Use with
437 caution!"""
438 self.tk.call('focus', '-force', self._w)
439 def focus_get(self):
440 """Return the widget which has currently the focus in the
441 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000442
Fredrik Lundh06d28152000-08-09 18:03:12 +0000443 Use focus_displayof to allow working with several
444 displays. Return None if application does not have
445 the focus."""
446 name = self.tk.call('focus')
447 if name == 'none' or not name: return None
448 return self._nametowidget(name)
449 def focus_displayof(self):
450 """Return the widget which has currently the focus on the
451 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000452
Fredrik Lundh06d28152000-08-09 18:03:12 +0000453 Return None if the application does not have the focus."""
454 name = self.tk.call('focus', '-displayof', self._w)
455 if name == 'none' or not name: return None
456 return self._nametowidget(name)
457 def focus_lastfor(self):
458 """Return the widget which would have the focus if top level
459 for this widget gets the focus from the window manager."""
460 name = self.tk.call('focus', '-lastfor', self._w)
461 if name == 'none' or not name: return None
462 return self._nametowidget(name)
463 def tk_focusFollowsMouse(self):
464 """The widget under mouse will get automatically focus. Can not
465 be disabled easily."""
466 self.tk.call('tk_focusFollowsMouse')
467 def tk_focusNext(self):
468 """Return the next widget in the focus order which follows
469 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000470
Fredrik Lundh06d28152000-08-09 18:03:12 +0000471 The focus order first goes to the next child, then to
472 the children of the child recursively and then to the
473 next sibling which is higher in the stacking order. A
474 widget is omitted if it has the takefocus resource set
475 to 0."""
476 name = self.tk.call('tk_focusNext', self._w)
477 if not name: return None
478 return self._nametowidget(name)
479 def tk_focusPrev(self):
480 """Return previous widget in the focus order. See tk_focusNext for details."""
481 name = self.tk.call('tk_focusPrev', self._w)
482 if not name: return None
483 return self._nametowidget(name)
484 def after(self, ms, func=None, *args):
485 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000486
Fredrik Lundh06d28152000-08-09 18:03:12 +0000487 MS specifies the time in milliseconds. FUNC gives the
488 function which shall be called. Additional parameters
489 are given as parameters to the function call. Return
490 identifier to cancel scheduling with after_cancel."""
491 if not func:
492 # I'd rather use time.sleep(ms*0.001)
493 self.tk.call('after', ms)
494 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000495 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000496 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000497 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000498 finally:
499 try:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000501 except TclError:
502 pass
503 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000504 return self.tk.call('after', ms, name)
505 def after_idle(self, func, *args):
506 """Call FUNC once if the Tcl main loop has no event to
507 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000508
Fredrik Lundh06d28152000-08-09 18:03:12 +0000509 Return an identifier to cancel the scheduling with
510 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000511 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000512 def after_cancel(self, id):
513 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000514
Fredrik Lundh06d28152000-08-09 18:03:12 +0000515 Identifier returned by after or after_idle must be
516 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000517 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000518 data = self.tk.call('after', 'info', id)
519 # In Tk 8.3, splitlist returns: (script, type)
520 # In Tk 8.4, splitlist may return (script, type) or (script,)
521 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000522 self.deletecommand(script)
523 except TclError:
524 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000525 self.tk.call('after', 'cancel', id)
526 def bell(self, displayof=0):
527 """Ring a display's bell."""
528 self.tk.call(('bell',) + self._displayof(displayof))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000529
Fredrik Lundh06d28152000-08-09 18:03:12 +0000530 # Clipboard handling:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531 def clipboard_get(self, **kw):
532 """Retrieve data from the clipboard on window's display.
533
534 The window keyword defaults to the root window of the Tkinter
535 application.
536
537 The type keyword specifies the form in which the data is
538 to be returned and should be an atom name such as STRING
539 or FILE_NAME. Type defaults to STRING.
540
541 This command is equivalent to:
542
543 selection_get(CLIPBOARD)
544 """
545 return self.tk.call(('clipboard', 'get') + self._options(kw))
546
Fredrik Lundh06d28152000-08-09 18:03:12 +0000547 def clipboard_clear(self, **kw):
548 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000549
Fredrik Lundh06d28152000-08-09 18:03:12 +0000550 A widget specified for the optional displayof keyword
551 argument specifies the target display."""
Guido van Rossume014a132006-08-19 16:53:45 +0000552 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000553 self.tk.call(('clipboard', 'clear') + self._options(kw))
554 def clipboard_append(self, string, **kw):
555 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000556
Fredrik Lundh06d28152000-08-09 18:03:12 +0000557 A widget specified at the optional displayof keyword
558 argument specifies the target display. The clipboard
559 can be retrieved with selection_get."""
Guido van Rossume014a132006-08-19 16:53:45 +0000560 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000561 self.tk.call(('clipboard', 'append') + self._options(kw)
562 + ('--', string))
563 # XXX grab current w/o window argument
564 def grab_current(self):
565 """Return widget which has currently the grab in this application
566 or None."""
567 name = self.tk.call('grab', 'current', self._w)
568 if not name: return None
569 return self._nametowidget(name)
570 def grab_release(self):
571 """Release grab for this widget if currently set."""
572 self.tk.call('grab', 'release', self._w)
573 def grab_set(self):
574 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000575
Fredrik Lundh06d28152000-08-09 18:03:12 +0000576 A grab directs all events to this and descendant
577 widgets in the application."""
578 self.tk.call('grab', 'set', self._w)
579 def grab_set_global(self):
580 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000581
Fredrik Lundh06d28152000-08-09 18:03:12 +0000582 A global grab directs all events to this and
583 descendant widgets on the display. Use with caution -
584 other applications do not get events anymore."""
585 self.tk.call('grab', 'set', '-global', self._w)
586 def grab_status(self):
587 """Return None, "local" or "global" if this widget has
588 no, a local or a global grab."""
589 status = self.tk.call('grab', 'status', self._w)
590 if status == 'none': status = None
591 return status
592 def lower(self, belowThis=None):
593 """Lower this widget in the stacking order."""
594 self.tk.call('lower', self._w, belowThis)
595 def option_add(self, pattern, value, priority = None):
596 """Set a VALUE (second parameter) for an option
597 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000598
Fredrik Lundh06d28152000-08-09 18:03:12 +0000599 An optional third parameter gives the numeric priority
600 (defaults to 80)."""
601 self.tk.call('option', 'add', pattern, value, priority)
602 def option_clear(self):
603 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000604
Fredrik Lundh06d28152000-08-09 18:03:12 +0000605 It will be reloaded if option_add is called."""
606 self.tk.call('option', 'clear')
607 def option_get(self, name, className):
608 """Return the value for an option NAME for this widget
609 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000610
Fredrik Lundh06d28152000-08-09 18:03:12 +0000611 Values with higher priority override lower values."""
612 return self.tk.call('option', 'get', self._w, name, className)
613 def option_readfile(self, fileName, priority = None):
614 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000615
Fredrik Lundh06d28152000-08-09 18:03:12 +0000616 An optional second parameter gives the numeric
617 priority."""
618 self.tk.call('option', 'readfile', fileName, priority)
619 def selection_clear(self, **kw):
620 """Clear the current X selection."""
Guido van Rossume014a132006-08-19 16:53:45 +0000621 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000622 self.tk.call(('selection', 'clear') + self._options(kw))
623 def selection_get(self, **kw):
624 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000625
Fredrik Lundh06d28152000-08-09 18:03:12 +0000626 A keyword parameter selection specifies the name of
627 the selection and defaults to PRIMARY. A keyword
628 parameter displayof specifies a widget on the display
629 to use."""
Guido van Rossume014a132006-08-19 16:53:45 +0000630 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000631 return self.tk.call(('selection', 'get') + self._options(kw))
632 def selection_handle(self, command, **kw):
633 """Specify a function COMMAND to call if the X
634 selection owned by this widget is queried by another
635 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000636
Fredrik Lundh06d28152000-08-09 18:03:12 +0000637 This function must return the contents of the
638 selection. The function will be called with the
639 arguments OFFSET and LENGTH which allows the chunking
640 of very long selections. The following keyword
641 parameters can be provided:
642 selection - name of the selection (default PRIMARY),
643 type - type of the selection (e.g. STRING, FILE_NAME)."""
644 name = self._register(command)
645 self.tk.call(('selection', 'handle') + self._options(kw)
646 + (self._w, name))
647 def selection_own(self, **kw):
648 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000649
Fredrik Lundh06d28152000-08-09 18:03:12 +0000650 A keyword parameter selection specifies the name of
651 the selection (default PRIMARY)."""
652 self.tk.call(('selection', 'own') +
653 self._options(kw) + (self._w,))
654 def selection_own_get(self, **kw):
655 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000656
Fredrik Lundh06d28152000-08-09 18:03:12 +0000657 The following keyword parameter can
658 be provided:
659 selection - name of the selection (default PRIMARY),
660 type - type of the selection (e.g. STRING, FILE_NAME)."""
Guido van Rossume014a132006-08-19 16:53:45 +0000661 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000662 name = self.tk.call(('selection', 'own') + self._options(kw))
663 if not name: return None
664 return self._nametowidget(name)
665 def send(self, interp, cmd, *args):
666 """Send Tcl command CMD to different interpreter INTERP to be executed."""
667 return self.tk.call(('send', interp, cmd) + args)
668 def lower(self, belowThis=None):
669 """Lower this widget in the stacking order."""
670 self.tk.call('lower', self._w, belowThis)
671 def tkraise(self, aboveThis=None):
672 """Raise this widget in the stacking order."""
673 self.tk.call('raise', self._w, aboveThis)
674 lift = tkraise
675 def colormodel(self, value=None):
676 """Useless. Not implemented in Tk."""
677 return self.tk.call('tk', 'colormodel', self._w, value)
678 def winfo_atom(self, name, displayof=0):
679 """Return integer which represents atom NAME."""
680 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
681 return getint(self.tk.call(args))
682 def winfo_atomname(self, id, displayof=0):
683 """Return name of atom with identifier ID."""
684 args = ('winfo', 'atomname') \
685 + self._displayof(displayof) + (id,)
686 return self.tk.call(args)
687 def winfo_cells(self):
688 """Return number of cells in the colormap for this widget."""
689 return getint(
690 self.tk.call('winfo', 'cells', self._w))
691 def winfo_children(self):
692 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000693 result = []
694 for child in self.tk.splitlist(
695 self.tk.call('winfo', 'children', self._w)):
696 try:
697 # Tcl sometimes returns extra windows, e.g. for
698 # menus; those need to be skipped
699 result.append(self._nametowidget(child))
700 except KeyError:
701 pass
702 return result
703
Fredrik Lundh06d28152000-08-09 18:03:12 +0000704 def winfo_class(self):
705 """Return window class name of this widget."""
706 return self.tk.call('winfo', 'class', self._w)
707 def winfo_colormapfull(self):
708 """Return true if at the last color request the colormap was full."""
709 return self.tk.getboolean(
710 self.tk.call('winfo', 'colormapfull', self._w))
711 def winfo_containing(self, rootX, rootY, displayof=0):
712 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
713 args = ('winfo', 'containing') \
714 + self._displayof(displayof) + (rootX, rootY)
715 name = self.tk.call(args)
716 if not name: return None
717 return self._nametowidget(name)
718 def winfo_depth(self):
719 """Return the number of bits per pixel."""
720 return getint(self.tk.call('winfo', 'depth', self._w))
721 def winfo_exists(self):
722 """Return true if this widget exists."""
723 return getint(
724 self.tk.call('winfo', 'exists', self._w))
725 def winfo_fpixels(self, number):
726 """Return the number of pixels for the given distance NUMBER
727 (e.g. "3c") as float."""
728 return getdouble(self.tk.call(
729 'winfo', 'fpixels', self._w, number))
730 def winfo_geometry(self):
731 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
732 return self.tk.call('winfo', 'geometry', self._w)
733 def winfo_height(self):
734 """Return height of this widget."""
735 return getint(
736 self.tk.call('winfo', 'height', self._w))
737 def winfo_id(self):
738 """Return identifier ID for this widget."""
739 return self.tk.getint(
740 self.tk.call('winfo', 'id', self._w))
741 def winfo_interps(self, displayof=0):
742 """Return the name of all Tcl interpreters for this display."""
743 args = ('winfo', 'interps') + self._displayof(displayof)
744 return self.tk.splitlist(self.tk.call(args))
745 def winfo_ismapped(self):
746 """Return true if this widget is mapped."""
747 return getint(
748 self.tk.call('winfo', 'ismapped', self._w))
749 def winfo_manager(self):
750 """Return the window mananger name for this widget."""
751 return self.tk.call('winfo', 'manager', self._w)
752 def winfo_name(self):
753 """Return the name of this widget."""
754 return self.tk.call('winfo', 'name', self._w)
755 def winfo_parent(self):
756 """Return the name of the parent of this widget."""
757 return self.tk.call('winfo', 'parent', self._w)
758 def winfo_pathname(self, id, displayof=0):
759 """Return the pathname of the widget given by ID."""
760 args = ('winfo', 'pathname') \
761 + self._displayof(displayof) + (id,)
762 return self.tk.call(args)
763 def winfo_pixels(self, number):
764 """Rounded integer value of winfo_fpixels."""
765 return getint(
766 self.tk.call('winfo', 'pixels', self._w, number))
767 def winfo_pointerx(self):
768 """Return the x coordinate of the pointer on the root window."""
769 return getint(
770 self.tk.call('winfo', 'pointerx', self._w))
771 def winfo_pointerxy(self):
772 """Return a tuple of x and y coordinates of the pointer on the root window."""
773 return self._getints(
774 self.tk.call('winfo', 'pointerxy', self._w))
775 def winfo_pointery(self):
776 """Return the y coordinate of the pointer on the root window."""
777 return getint(
778 self.tk.call('winfo', 'pointery', self._w))
779 def winfo_reqheight(self):
780 """Return requested height of this widget."""
781 return getint(
782 self.tk.call('winfo', 'reqheight', self._w))
783 def winfo_reqwidth(self):
784 """Return requested width of this widget."""
785 return getint(
786 self.tk.call('winfo', 'reqwidth', self._w))
787 def winfo_rgb(self, color):
788 """Return tuple of decimal values for red, green, blue for
789 COLOR in this widget."""
790 return self._getints(
791 self.tk.call('winfo', 'rgb', self._w, color))
792 def winfo_rootx(self):
793 """Return x coordinate of upper left corner of this widget on the
794 root window."""
795 return getint(
796 self.tk.call('winfo', 'rootx', self._w))
797 def winfo_rooty(self):
798 """Return y coordinate of upper left corner of this widget on the
799 root window."""
800 return getint(
801 self.tk.call('winfo', 'rooty', self._w))
802 def winfo_screen(self):
803 """Return the screen name of this widget."""
804 return self.tk.call('winfo', 'screen', self._w)
805 def winfo_screencells(self):
806 """Return the number of the cells in the colormap of the screen
807 of this widget."""
808 return getint(
809 self.tk.call('winfo', 'screencells', self._w))
810 def winfo_screendepth(self):
811 """Return the number of bits per pixel of the root window of the
812 screen of this widget."""
813 return getint(
814 self.tk.call('winfo', 'screendepth', self._w))
815 def winfo_screenheight(self):
816 """Return the number of pixels of the height of the screen of this widget
817 in pixel."""
818 return getint(
819 self.tk.call('winfo', 'screenheight', self._w))
820 def winfo_screenmmheight(self):
821 """Return the number of pixels of the height of the screen of
822 this widget in mm."""
823 return getint(
824 self.tk.call('winfo', 'screenmmheight', self._w))
825 def winfo_screenmmwidth(self):
826 """Return the number of pixels of the width of the screen of
827 this widget in mm."""
828 return getint(
829 self.tk.call('winfo', 'screenmmwidth', self._w))
830 def winfo_screenvisual(self):
831 """Return one of the strings directcolor, grayscale, pseudocolor,
832 staticcolor, staticgray, or truecolor for the default
833 colormodel of this screen."""
834 return self.tk.call('winfo', 'screenvisual', self._w)
835 def winfo_screenwidth(self):
836 """Return the number of pixels of the width of the screen of
837 this widget in pixel."""
838 return getint(
839 self.tk.call('winfo', 'screenwidth', self._w))
840 def winfo_server(self):
841 """Return information of the X-Server of the screen of this widget in
842 the form "XmajorRminor vendor vendorVersion"."""
843 return self.tk.call('winfo', 'server', self._w)
844 def winfo_toplevel(self):
845 """Return the toplevel widget of this widget."""
846 return self._nametowidget(self.tk.call(
847 'winfo', 'toplevel', self._w))
848 def winfo_viewable(self):
849 """Return true if the widget and all its higher ancestors are mapped."""
850 return getint(
851 self.tk.call('winfo', 'viewable', self._w))
852 def winfo_visual(self):
853 """Return one of the strings directcolor, grayscale, pseudocolor,
854 staticcolor, staticgray, or truecolor for the
855 colormodel of this widget."""
856 return self.tk.call('winfo', 'visual', self._w)
857 def winfo_visualid(self):
858 """Return the X identifier for the visual for this widget."""
859 return self.tk.call('winfo', 'visualid', self._w)
860 def winfo_visualsavailable(self, includeids=0):
861 """Return a list of all visuals available for the screen
862 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000863
Fredrik Lundh06d28152000-08-09 18:03:12 +0000864 Each item in the list consists of a visual name (see winfo_visual), a
865 depth and if INCLUDEIDS=1 is given also the X identifier."""
866 data = self.tk.split(
867 self.tk.call('winfo', 'visualsavailable', self._w,
868 includeids and 'includeids' or None))
Guido van Rossum13257902007-06-07 23:15:56 +0000869 if isinstance(data, str):
Fredrik Lundh24037f72000-08-09 19:26:47 +0000870 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000871 return map(self.__winfo_parseitem, data)
872 def __winfo_parseitem(self, t):
873 """Internal function."""
874 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
875 def __winfo_getint(self, x):
876 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000877 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000878 def winfo_vrootheight(self):
879 """Return the height of the virtual root window associated with this
880 widget in pixels. If there is no virtual root window return the
881 height of the screen."""
882 return getint(
883 self.tk.call('winfo', 'vrootheight', self._w))
884 def winfo_vrootwidth(self):
885 """Return the width of the virtual root window associated with this
886 widget in pixel. If there is no virtual root window return the
887 width of the screen."""
888 return getint(
889 self.tk.call('winfo', 'vrootwidth', self._w))
890 def winfo_vrootx(self):
891 """Return the x offset of the virtual root relative to the root
892 window of the screen of this widget."""
893 return getint(
894 self.tk.call('winfo', 'vrootx', self._w))
895 def winfo_vrooty(self):
896 """Return the y offset of the virtual root relative to the root
897 window of the screen of this widget."""
898 return getint(
899 self.tk.call('winfo', 'vrooty', self._w))
900 def winfo_width(self):
901 """Return the width of this widget."""
902 return getint(
903 self.tk.call('winfo', 'width', self._w))
904 def winfo_x(self):
905 """Return the x coordinate of the upper left corner of this widget
906 in the parent."""
907 return getint(
908 self.tk.call('winfo', 'x', self._w))
909 def winfo_y(self):
910 """Return the y coordinate of the upper left corner of this widget
911 in the parent."""
912 return getint(
913 self.tk.call('winfo', 'y', self._w))
914 def update(self):
915 """Enter event loop until all pending events have been processed by Tcl."""
916 self.tk.call('update')
917 def update_idletasks(self):
918 """Enter event loop until all idle callbacks have been called. This
919 will update the display of windows but not process events caused by
920 the user."""
921 self.tk.call('update', 'idletasks')
922 def bindtags(self, tagList=None):
923 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000924
Fredrik Lundh06d28152000-08-09 18:03:12 +0000925 With no argument return the list of all bindtags associated with
926 this widget. With a list of strings as argument the bindtags are
927 set to this list. The bindtags determine in which order events are
928 processed (see bind)."""
929 if tagList is None:
930 return self.tk.splitlist(
931 self.tk.call('bindtags', self._w))
932 else:
933 self.tk.call('bindtags', self._w, tagList)
934 def _bind(self, what, sequence, func, add, needcleanup=1):
935 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +0000936 if isinstance(func, str):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000937 self.tk.call(what + (sequence, func))
938 elif func:
939 funcid = self._register(func, self._substitute,
940 needcleanup)
941 cmd = ('%sif {"[%s %s]" == "break"} break\n'
942 %
943 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000944 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000945 self.tk.call(what + (sequence, cmd))
946 return funcid
947 elif sequence:
948 return self.tk.call(what + (sequence,))
949 else:
950 return self.tk.splitlist(self.tk.call(what))
951 def bind(self, sequence=None, func=None, add=None):
952 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000953
Fredrik Lundh06d28152000-08-09 18:03:12 +0000954 SEQUENCE is a string of concatenated event
955 patterns. An event pattern is of the form
956 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
957 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
958 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
959 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
960 Mod1, M1. TYPE is one of Activate, Enter, Map,
961 ButtonPress, Button, Expose, Motion, ButtonRelease
962 FocusIn, MouseWheel, Circulate, FocusOut, Property,
963 Colormap, Gravity Reparent, Configure, KeyPress, Key,
964 Unmap, Deactivate, KeyRelease Visibility, Destroy,
965 Leave and DETAIL is the button number for ButtonPress,
966 ButtonRelease and DETAIL is the Keysym for KeyPress and
967 KeyRelease. Examples are
968 <Control-Button-1> for pressing Control and mouse button 1 or
969 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
970 An event pattern can also be a virtual event of the form
971 <<AString>> where AString can be arbitrary. This
972 event can be generated by event_generate.
973 If events are concatenated they must appear shortly
974 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000975
Fredrik Lundh06d28152000-08-09 18:03:12 +0000976 FUNC will be called if the event sequence occurs with an
977 instance of Event as argument. If the return value of FUNC is
978 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000979
Fredrik Lundh06d28152000-08-09 18:03:12 +0000980 An additional boolean parameter ADD specifies whether FUNC will
981 be called additionally to the other bound function or whether
982 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000983
Fredrik Lundh06d28152000-08-09 18:03:12 +0000984 Bind will return an identifier to allow deletion of the bound function with
985 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000986
Fredrik Lundh06d28152000-08-09 18:03:12 +0000987 If FUNC or SEQUENCE is omitted the bound function or list
988 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000989
Fredrik Lundh06d28152000-08-09 18:03:12 +0000990 return self._bind(('bind', self._w), sequence, func, add)
991 def unbind(self, sequence, funcid=None):
992 """Unbind for this widget for event SEQUENCE the
993 function identified with FUNCID."""
994 self.tk.call('bind', self._w, sequence, '')
995 if funcid:
996 self.deletecommand(funcid)
997 def bind_all(self, sequence=None, func=None, add=None):
998 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
999 An additional boolean parameter ADD specifies whether FUNC will
1000 be called additionally to the other bound function or whether
1001 it will replace the previous function. See bind for the return value."""
1002 return self._bind(('bind', 'all'), sequence, func, add, 0)
1003 def unbind_all(self, sequence):
1004 """Unbind for all widgets for event SEQUENCE all functions."""
1005 self.tk.call('bind', 'all' , sequence, '')
1006 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001007
Fredrik Lundh06d28152000-08-09 18:03:12 +00001008 """Bind to widgets with bindtag CLASSNAME at event
1009 SEQUENCE a call of function FUNC. An additional
1010 boolean parameter ADD specifies whether FUNC will be
1011 called additionally to the other bound function or
1012 whether it will replace the previous function. See bind for
1013 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001014
Fredrik Lundh06d28152000-08-09 18:03:12 +00001015 return self._bind(('bind', className), sequence, func, add, 0)
1016 def unbind_class(self, className, sequence):
1017 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1018 all functions."""
1019 self.tk.call('bind', className , sequence, '')
1020 def mainloop(self, n=0):
1021 """Call the mainloop of Tk."""
1022 self.tk.mainloop(n)
1023 def quit(self):
1024 """Quit the Tcl interpreter. All widgets will be destroyed."""
1025 self.tk.quit()
1026 def _getints(self, string):
1027 """Internal function."""
1028 if string:
1029 return tuple(map(getint, self.tk.splitlist(string)))
1030 def _getdoubles(self, string):
1031 """Internal function."""
1032 if string:
1033 return tuple(map(getdouble, self.tk.splitlist(string)))
1034 def _getboolean(self, string):
1035 """Internal function."""
1036 if string:
1037 return self.tk.getboolean(string)
1038 def _displayof(self, displayof):
1039 """Internal function."""
1040 if displayof:
1041 return ('-displayof', displayof)
1042 if displayof is None:
1043 return ('-displayof', self._w)
1044 return ()
1045 def _options(self, cnf, kw = None):
1046 """Internal function."""
1047 if kw:
1048 cnf = _cnfmerge((cnf, kw))
1049 else:
1050 cnf = _cnfmerge(cnf)
1051 res = ()
1052 for k, v in cnf.items():
1053 if v is not None:
1054 if k[-1] == '_': k = k[:-1]
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001055 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001056 v = self._register(v)
1057 res = res + ('-'+k, v)
1058 return res
1059 def nametowidget(self, name):
1060 """Return the Tkinter instance of a widget identified by
1061 its Tcl name NAME."""
1062 w = self
1063 if name[0] == '.':
1064 w = w._root()
1065 name = name[1:]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001066 while name:
Eric S. Raymondfc170b12001-02-09 11:51:27 +00001067 i = name.find('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001068 if i >= 0:
1069 name, tail = name[:i], name[i+1:]
1070 else:
1071 tail = ''
1072 w = w.children[name]
1073 name = tail
1074 return w
1075 _nametowidget = nametowidget
1076 def _register(self, func, subst=None, needcleanup=1):
1077 """Return a newly created Tcl function. If this
1078 function is called, the Python function FUNC will
1079 be executed. An optional function SUBST can
1080 be given which will be executed before FUNC."""
1081 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001082 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001083 try:
1084 func = func.im_func
1085 except AttributeError:
1086 pass
1087 try:
1088 name = name + func.__name__
1089 except AttributeError:
1090 pass
1091 self.tk.createcommand(name, f)
1092 if needcleanup:
1093 if self._tclCommands is None:
1094 self._tclCommands = []
1095 self._tclCommands.append(name)
1096 #print '+ Tkinter created command', name
1097 return name
1098 register = _register
1099 def _root(self):
1100 """Internal function."""
1101 w = self
1102 while w.master: w = w.master
1103 return w
1104 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1105 '%s', '%t', '%w', '%x', '%y',
1106 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001107 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001108 def _substitute(self, *args):
1109 """Internal function."""
1110 if len(args) != len(self._subst_format): return args
1111 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001112
Fredrik Lundh06d28152000-08-09 18:03:12 +00001113 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001114 def getint_event(s):
1115 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1116 try:
1117 return int(s)
1118 except ValueError:
1119 return s
1120
Fredrik Lundh06d28152000-08-09 18:03:12 +00001121 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1122 # Missing: (a, c, d, m, o, v, B, R)
1123 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001124 # serial field: valid vor all events
1125 # number of button: ButtonPress and ButtonRelease events only
1126 # height field: Configure, ConfigureRequest, Create,
1127 # ResizeRequest, and Expose events only
1128 # keycode field: KeyPress and KeyRelease events only
1129 # time field: "valid for events that contain a time field"
1130 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1131 # and Expose events only
1132 # x field: "valid for events that contain a x field"
1133 # y field: "valid for events that contain a y field"
1134 # keysym as decimal: KeyPress and KeyRelease events only
1135 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1136 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001137 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001138 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001139 try: e.focus = getboolean(f)
1140 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001141 e.height = getint_event(h)
1142 e.keycode = getint_event(k)
1143 e.state = getint_event(s)
1144 e.time = getint_event(t)
1145 e.width = getint_event(w)
1146 e.x = getint_event(x)
1147 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001148 e.char = A
1149 try: e.send_event = getboolean(E)
1150 except TclError: pass
1151 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001152 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001153 e.type = T
1154 try:
1155 e.widget = self._nametowidget(W)
1156 except KeyError:
1157 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001158 e.x_root = getint_event(X)
1159 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001160 try:
1161 e.delta = getint(D)
1162 except ValueError:
1163 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001164 return (e,)
1165 def _report_exception(self):
1166 """Internal function."""
1167 import sys
Neal Norwitzac3625f2006-03-17 05:49:33 +00001168 exc, val, tb = sys.exc_info()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001169 root = self._root()
1170 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001171 def _configure(self, cmd, cnf, kw):
1172 """Internal function."""
1173 if kw:
1174 cnf = _cnfmerge((cnf, kw))
1175 elif cnf:
1176 cnf = _cnfmerge(cnf)
1177 if cnf is None:
1178 cnf = {}
1179 for x in self.tk.split(
1180 self.tk.call(_flatten((self._w, cmd)))):
1181 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1182 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00001183 if isinstance(cnf, str):
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001184 x = self.tk.split(
1185 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1186 return (x[0][1:],) + x[1:]
1187 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001188 # These used to be defined in Widget:
1189 def configure(self, cnf=None, **kw):
1190 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001191
Fredrik Lundh06d28152000-08-09 18:03:12 +00001192 The values for resources are specified as keyword
1193 arguments. To get an overview about
1194 the allowed keyword arguments call the method keys.
1195 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001196 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001197 config = configure
1198 def cget(self, key):
1199 """Return the resource value for a KEY given as string."""
1200 return self.tk.call(self._w, 'cget', '-' + key)
1201 __getitem__ = cget
1202 def __setitem__(self, key, value):
1203 self.configure({key: value})
1204 def keys(self):
1205 """Return a list of all resource names of this widget."""
1206 return map(lambda x: x[0][1:],
1207 self.tk.split(self.tk.call(self._w, 'configure')))
1208 def __str__(self):
1209 """Return the window path name of this widget."""
1210 return self._w
1211 # Pack methods that apply to the master
1212 _noarg_ = ['_noarg_']
1213 def pack_propagate(self, flag=_noarg_):
1214 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001215
Fredrik Lundh06d28152000-08-09 18:03:12 +00001216 A boolean argument specifies whether the geometry information
1217 of the slaves will determine the size of this widget. If no argument
1218 is given the current setting will be returned.
1219 """
1220 if flag is Misc._noarg_:
1221 return self._getboolean(self.tk.call(
1222 'pack', 'propagate', self._w))
1223 else:
1224 self.tk.call('pack', 'propagate', self._w, flag)
1225 propagate = pack_propagate
1226 def pack_slaves(self):
1227 """Return a list of all slaves of this widget
1228 in its packing order."""
1229 return map(self._nametowidget,
1230 self.tk.splitlist(
1231 self.tk.call('pack', 'slaves', self._w)))
1232 slaves = pack_slaves
1233 # Place method that applies to the master
1234 def place_slaves(self):
1235 """Return a list of all slaves of this widget
1236 in its packing order."""
1237 return map(self._nametowidget,
1238 self.tk.splitlist(
1239 self.tk.call(
1240 'place', 'slaves', self._w)))
1241 # Grid methods that apply to the master
1242 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1243 """Return a tuple of integer coordinates for the bounding
1244 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001245
Fredrik Lundh06d28152000-08-09 18:03:12 +00001246 If COLUMN, ROW is given the bounding box applies from
1247 the cell with row and column 0 to the specified
1248 cell. If COL2 and ROW2 are given the bounding box
1249 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001250
Fredrik Lundh06d28152000-08-09 18:03:12 +00001251 The returned integers specify the offset of the upper left
1252 corner in the master widget and the width and height.
1253 """
1254 args = ('grid', 'bbox', self._w)
1255 if column is not None and row is not None:
1256 args = args + (column, row)
1257 if col2 is not None and row2 is not None:
1258 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001259 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001260
Fredrik Lundh06d28152000-08-09 18:03:12 +00001261 bbox = grid_bbox
1262 def _grid_configure(self, command, index, cnf, kw):
1263 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001264 if isinstance(cnf, str) and not kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001265 if cnf[-1:] == '_':
1266 cnf = cnf[:-1]
1267 if cnf[:1] != '-':
1268 cnf = '-'+cnf
1269 options = (cnf,)
1270 else:
1271 options = self._options(cnf, kw)
1272 if not options:
1273 res = self.tk.call('grid',
1274 command, self._w, index)
1275 words = self.tk.splitlist(res)
1276 dict = {}
1277 for i in range(0, len(words), 2):
1278 key = words[i][1:]
1279 value = words[i+1]
1280 if not value:
1281 value = None
1282 elif '.' in value:
1283 value = getdouble(value)
1284 else:
1285 value = getint(value)
1286 dict[key] = value
1287 return dict
1288 res = self.tk.call(
1289 ('grid', command, self._w, index)
1290 + options)
1291 if len(options) == 1:
1292 if not res: return None
1293 # In Tk 7.5, -width can be a float
1294 if '.' in res: return getdouble(res)
1295 return getint(res)
1296 def grid_columnconfigure(self, index, cnf={}, **kw):
1297 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001298
Fredrik Lundh06d28152000-08-09 18:03:12 +00001299 Valid resources are minsize (minimum size of the column),
1300 weight (how much does additional space propagate to this column)
1301 and pad (how much space to let additionally)."""
1302 return self._grid_configure('columnconfigure', index, cnf, kw)
1303 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001304 def grid_location(self, x, y):
1305 """Return a tuple of column and row which identify the cell
1306 at which the pixel at position X and Y inside the master
1307 widget is located."""
1308 return self._getints(
1309 self.tk.call(
1310 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001311 def grid_propagate(self, flag=_noarg_):
1312 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001313
Fredrik Lundh06d28152000-08-09 18:03:12 +00001314 A boolean argument specifies whether the geometry information
1315 of the slaves will determine the size of this widget. If no argument
1316 is given, the current setting will be returned.
1317 """
1318 if flag is Misc._noarg_:
1319 return self._getboolean(self.tk.call(
1320 'grid', 'propagate', self._w))
1321 else:
1322 self.tk.call('grid', 'propagate', self._w, flag)
1323 def grid_rowconfigure(self, index, cnf={}, **kw):
1324 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001325
Fredrik Lundh06d28152000-08-09 18:03:12 +00001326 Valid resources are minsize (minimum size of the row),
1327 weight (how much does additional space propagate to this row)
1328 and pad (how much space to let additionally)."""
1329 return self._grid_configure('rowconfigure', index, cnf, kw)
1330 rowconfigure = grid_rowconfigure
1331 def grid_size(self):
1332 """Return a tuple of the number of column and rows in the grid."""
1333 return self._getints(
1334 self.tk.call('grid', 'size', self._w)) or None
1335 size = grid_size
1336 def grid_slaves(self, row=None, column=None):
1337 """Return a list of all slaves of this widget
1338 in its packing order."""
1339 args = ()
1340 if row is not None:
1341 args = args + ('-row', row)
1342 if column is not None:
1343 args = args + ('-column', column)
1344 return map(self._nametowidget,
1345 self.tk.splitlist(self.tk.call(
1346 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001347
Fredrik Lundh06d28152000-08-09 18:03:12 +00001348 # Support for the "event" command, new in Tk 4.2.
1349 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001350
Fredrik Lundh06d28152000-08-09 18:03:12 +00001351 def event_add(self, virtual, *sequences):
1352 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1353 to an event SEQUENCE such that the virtual event is triggered
1354 whenever SEQUENCE occurs."""
1355 args = ('event', 'add', virtual) + sequences
1356 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001357
Fredrik Lundh06d28152000-08-09 18:03:12 +00001358 def event_delete(self, virtual, *sequences):
1359 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1360 args = ('event', 'delete', virtual) + sequences
1361 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001362
Fredrik Lundh06d28152000-08-09 18:03:12 +00001363 def event_generate(self, sequence, **kw):
1364 """Generate an event SEQUENCE. Additional
1365 keyword arguments specify parameter of the event
1366 (e.g. x, y, rootx, rooty)."""
1367 args = ('event', 'generate', self._w, sequence)
1368 for k, v in kw.items():
1369 args = args + ('-%s' % k, str(v))
1370 self.tk.call(args)
1371
1372 def event_info(self, virtual=None):
1373 """Return a list of all virtual events or the information
1374 about the SEQUENCE bound to the virtual event VIRTUAL."""
1375 return self.tk.splitlist(
1376 self.tk.call('event', 'info', virtual))
1377
1378 # Image related commands
1379
1380 def image_names(self):
1381 """Return a list of all existing image names."""
1382 return self.tk.call('image', 'names')
1383
1384 def image_types(self):
1385 """Return a list of all available image types (e.g. phote bitmap)."""
1386 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001387
Guido van Rossum80f8be81997-12-02 19:51:39 +00001388
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001389class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001390 """Internal class. Stores function to call when some user
1391 defined Tcl function is called e.g. after an event occurred."""
1392 def __init__(self, func, subst, widget):
1393 """Store FUNC, SUBST and WIDGET as members."""
1394 self.func = func
1395 self.subst = subst
1396 self.widget = widget
1397 def __call__(self, *args):
1398 """Apply first function SUBST to arguments, than FUNC."""
1399 try:
1400 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001401 args = self.subst(*args)
1402 return self.func(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001403 except SystemExit as msg:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001404 raise SystemExit, msg
1405 except:
1406 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001407
Guido van Rossume365a591998-05-01 19:48:20 +00001408
Guido van Rossum18468821994-06-20 07:49:28 +00001409class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001410 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001411
Fredrik Lundh06d28152000-08-09 18:03:12 +00001412 def wm_aspect(self,
1413 minNumer=None, minDenom=None,
1414 maxNumer=None, maxDenom=None):
1415 """Instruct the window manager to set the aspect ratio (width/height)
1416 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1417 of the actual values if no argument is given."""
1418 return self._getints(
1419 self.tk.call('wm', 'aspect', self._w,
1420 minNumer, minDenom,
1421 maxNumer, maxDenom))
1422 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001423
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001424 def wm_attributes(self, *args):
1425 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001426
1427 The first form returns a list of the platform specific flags and
1428 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001429 option. The third form sets one or more of the values. The values
1430 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001431
1432 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001433 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001434 to toolwindow (as defined in the MSDN). -topmost gets or sets
1435 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001436 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001437
1438 On Macintosh, XXXXX
1439
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001440 On Unix, there are currently no special attribute values.
1441 """
1442 args = ('wm', 'attributes', self._w) + args
1443 return self.tk.call(args)
1444 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001445
Fredrik Lundh06d28152000-08-09 18:03:12 +00001446 def wm_client(self, name=None):
1447 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1448 current value."""
1449 return self.tk.call('wm', 'client', self._w, name)
1450 client = wm_client
1451 def wm_colormapwindows(self, *wlist):
1452 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1453 of this widget. This list contains windows whose colormaps differ from their
1454 parents. Return current list of widgets if WLIST is empty."""
1455 if len(wlist) > 1:
1456 wlist = (wlist,) # Tk needs a list of windows here
1457 args = ('wm', 'colormapwindows', self._w) + wlist
1458 return map(self._nametowidget, self.tk.call(args))
1459 colormapwindows = wm_colormapwindows
1460 def wm_command(self, value=None):
1461 """Store VALUE in WM_COMMAND property. It is the command
1462 which shall be used to invoke the application. Return current
1463 command if VALUE is None."""
1464 return self.tk.call('wm', 'command', self._w, value)
1465 command = wm_command
1466 def wm_deiconify(self):
1467 """Deiconify this widget. If it was never mapped it will not be mapped.
1468 On Windows it will raise this widget and give it the focus."""
1469 return self.tk.call('wm', 'deiconify', self._w)
1470 deiconify = wm_deiconify
1471 def wm_focusmodel(self, model=None):
1472 """Set focus model to MODEL. "active" means that this widget will claim
1473 the focus itself, "passive" means that the window manager shall give
1474 the focus. Return current focus model if MODEL is None."""
1475 return self.tk.call('wm', 'focusmodel', self._w, model)
1476 focusmodel = wm_focusmodel
1477 def wm_frame(self):
1478 """Return identifier for decorative frame of this widget if present."""
1479 return self.tk.call('wm', 'frame', self._w)
1480 frame = wm_frame
1481 def wm_geometry(self, newGeometry=None):
1482 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1483 current value if None is given."""
1484 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1485 geometry = wm_geometry
1486 def wm_grid(self,
1487 baseWidth=None, baseHeight=None,
1488 widthInc=None, heightInc=None):
1489 """Instruct the window manager that this widget shall only be
1490 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1491 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1492 number of grid units requested in Tk_GeometryRequest."""
1493 return self._getints(self.tk.call(
1494 'wm', 'grid', self._w,
1495 baseWidth, baseHeight, widthInc, heightInc))
1496 grid = wm_grid
1497 def wm_group(self, pathName=None):
1498 """Set the group leader widgets for related widgets to PATHNAME. Return
1499 the group leader of this widget if None is given."""
1500 return self.tk.call('wm', 'group', self._w, pathName)
1501 group = wm_group
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001502 def wm_iconbitmap(self, bitmap=None, default=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001503 """Set bitmap for the iconified widget to BITMAP. Return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001504 the bitmap if None is given.
1505
1506 Under Windows, the DEFAULT parameter can be used to set the icon
1507 for the widget and any descendents that don't have an icon set
1508 explicitly. DEFAULT can be the relative path to a .ico file
1509 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1510 documentation for more information."""
1511 if default:
1512 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1513 else:
1514 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001515 iconbitmap = wm_iconbitmap
1516 def wm_iconify(self):
1517 """Display widget as icon."""
1518 return self.tk.call('wm', 'iconify', self._w)
1519 iconify = wm_iconify
1520 def wm_iconmask(self, bitmap=None):
1521 """Set mask for the icon bitmap of this widget. Return the
1522 mask if None is given."""
1523 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1524 iconmask = wm_iconmask
1525 def wm_iconname(self, newName=None):
1526 """Set the name of the icon for this widget. Return the name if
1527 None is given."""
1528 return self.tk.call('wm', 'iconname', self._w, newName)
1529 iconname = wm_iconname
1530 def wm_iconposition(self, x=None, y=None):
1531 """Set the position of the icon of this widget to X and Y. Return
1532 a tuple of the current values of X and X if None is given."""
1533 return self._getints(self.tk.call(
1534 'wm', 'iconposition', self._w, x, y))
1535 iconposition = wm_iconposition
1536 def wm_iconwindow(self, pathName=None):
1537 """Set widget PATHNAME to be displayed instead of icon. Return the current
1538 value if None is given."""
1539 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1540 iconwindow = wm_iconwindow
1541 def wm_maxsize(self, width=None, height=None):
1542 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1543 the values are given in grid units. Return the current values if None
1544 is given."""
1545 return self._getints(self.tk.call(
1546 'wm', 'maxsize', self._w, width, height))
1547 maxsize = wm_maxsize
1548 def wm_minsize(self, width=None, height=None):
1549 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1550 the values are given in grid units. Return the current values if None
1551 is given."""
1552 return self._getints(self.tk.call(
1553 'wm', 'minsize', self._w, width, height))
1554 minsize = wm_minsize
1555 def wm_overrideredirect(self, boolean=None):
1556 """Instruct the window manager to ignore this widget
1557 if BOOLEAN is given with 1. Return the current value if None
1558 is given."""
1559 return self._getboolean(self.tk.call(
1560 'wm', 'overrideredirect', self._w, boolean))
1561 overrideredirect = wm_overrideredirect
1562 def wm_positionfrom(self, who=None):
1563 """Instruct the window manager that the position of this widget shall
1564 be defined by the user if WHO is "user", and by its own policy if WHO is
1565 "program"."""
1566 return self.tk.call('wm', 'positionfrom', self._w, who)
1567 positionfrom = wm_positionfrom
1568 def wm_protocol(self, name=None, func=None):
1569 """Bind function FUNC to command NAME for this widget.
1570 Return the function bound to NAME if None is given. NAME could be
1571 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001572 if hasattr(func, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001573 command = self._register(func)
1574 else:
1575 command = func
1576 return self.tk.call(
1577 'wm', 'protocol', self._w, name, command)
1578 protocol = wm_protocol
1579 def wm_resizable(self, width=None, height=None):
1580 """Instruct the window manager whether this width can be resized
1581 in WIDTH or HEIGHT. Both values are boolean values."""
1582 return self.tk.call('wm', 'resizable', self._w, width, height)
1583 resizable = wm_resizable
1584 def wm_sizefrom(self, who=None):
1585 """Instruct the window manager that the size of this widget shall
1586 be defined by the user if WHO is "user", and by its own policy if WHO is
1587 "program"."""
1588 return self.tk.call('wm', 'sizefrom', self._w, who)
1589 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001590 def wm_state(self, newstate=None):
1591 """Query or set the state of this widget as one of normal, icon,
1592 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1593 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001594 state = wm_state
1595 def wm_title(self, string=None):
1596 """Set the title of this widget."""
1597 return self.tk.call('wm', 'title', self._w, string)
1598 title = wm_title
1599 def wm_transient(self, master=None):
1600 """Instruct the window manager that this widget is transient
1601 with regard to widget MASTER."""
1602 return self.tk.call('wm', 'transient', self._w, master)
1603 transient = wm_transient
1604 def wm_withdraw(self):
1605 """Withdraw this widget from the screen such that it is unmapped
1606 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1607 return self.tk.call('wm', 'withdraw', self._w)
1608 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001609
Guido van Rossum18468821994-06-20 07:49:28 +00001610
1611class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001612 """Toplevel widget of Tk which represents mostly the main window
1613 of an appliation. It has an associated Tcl interpreter."""
1614 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001615 def __init__(self, screenName=None, baseName=None, className='Tk',
1616 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001617 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1618 be created. BASENAME will be used for the identification of the profile file (see
1619 readprofile).
1620 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1621 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001622 self.master = None
1623 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001624 self._tkloaded = 0
1625 # to avoid recursions in the getattr code in case of failure, we
1626 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001627 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001628 if baseName is None:
1629 import sys, os
1630 baseName = os.path.basename(sys.argv[0])
1631 baseName, ext = os.path.splitext(baseName)
1632 if ext not in ('.py', '.pyc', '.pyo'):
1633 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001634 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001635 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001636 if useTk:
1637 self._loadtk()
1638 self.readprofile(baseName, className)
1639 def loadtk(self):
1640 if not self._tkloaded:
1641 self.tk.loadtk()
1642 self._loadtk()
1643 def _loadtk(self):
1644 self._tkloaded = 1
1645 global _default_root
Jack Jansenbe92af02001-08-23 13:25:59 +00001646 if _MacOS and hasattr(_MacOS, 'SchedParams'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001647 # Disable event scanning except for Command-Period
1648 _MacOS.SchedParams(1, 0)
1649 # Work around nasty MacTk bug
1650 # XXX Is this one still needed?
1651 self.update()
1652 # Version sanity checks
1653 tk_version = self.tk.getvar('tk_version')
1654 if tk_version != _tkinter.TK_VERSION:
1655 raise RuntimeError, \
1656 "tk.h version (%s) doesn't match libtk.a version (%s)" \
1657 % (_tkinter.TK_VERSION, tk_version)
Martin v. Löwis54895972003-05-24 11:37:15 +00001658 # Under unknown circumstances, tcl_version gets coerced to float
1659 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001660 if tcl_version != _tkinter.TCL_VERSION:
1661 raise RuntimeError, \
1662 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1663 % (_tkinter.TCL_VERSION, tcl_version)
1664 if TkVersion < 4.0:
1665 raise RuntimeError, \
1666 "Tk 4.0 or higher is required; found Tk %s" \
1667 % str(TkVersion)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001668 # Create and register the tkerror and exit commands
1669 # We need to inline parts of _register here, _ register
1670 # would register differently-named commands.
1671 if self._tclCommands is None:
1672 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001673 self.tk.createcommand('tkerror', _tkerror)
1674 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001675 self._tclCommands.append('tkerror')
1676 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001677 if _support_default_root and not _default_root:
1678 _default_root = self
1679 self.protocol("WM_DELETE_WINDOW", self.destroy)
1680 def destroy(self):
1681 """Destroy this and all descendants widgets. This will
1682 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001683 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001684 self.tk.call('destroy', self._w)
1685 Misc.destroy(self)
1686 global _default_root
1687 if _support_default_root and _default_root is self:
1688 _default_root = None
1689 def readprofile(self, baseName, className):
1690 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001691 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1692 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001693 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001694 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001695 else: home = os.curdir
1696 class_tcl = os.path.join(home, '.%s.tcl' % className)
1697 class_py = os.path.join(home, '.%s.py' % className)
1698 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1699 base_py = os.path.join(home, '.%s.py' % baseName)
1700 dir = {'self': self}
Georg Brandl7cae87c2006-09-06 06:51:57 +00001701 exec('from Tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001702 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001703 self.tk.call('source', class_tcl)
1704 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001705 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001706 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001707 self.tk.call('source', base_tcl)
1708 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001709 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001710 def report_callback_exception(self, exc, val, tb):
1711 """Internal function. It reports exception on sys.stderr."""
1712 import traceback, sys
1713 sys.stderr.write("Exception in Tkinter callback\n")
1714 sys.last_type = exc
1715 sys.last_value = val
1716 sys.last_traceback = tb
1717 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001718 def __getattr__(self, attr):
1719 "Delegate attribute access to the interpreter object"
1720 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001721
Guido van Rossum368e06b1997-11-07 20:38:49 +00001722# Ideally, the classes Pack, Place and Grid disappear, the
1723# pack/place/grid methods are defined on the Widget class, and
1724# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1725# ...), with pack(), place() and grid() being short for
1726# pack_configure(), place_configure() and grid_columnconfigure(), and
1727# forget() being short for pack_forget(). As a practical matter, I'm
1728# afraid that there is too much code out there that may be using the
1729# Pack, Place or Grid class, so I leave them intact -- but only as
1730# backwards compatibility features. Also note that those methods that
1731# take a master as argument (e.g. pack_propagate) have been moved to
1732# the Misc class (which now incorporates all methods common between
1733# toplevel and interior widgets). Again, for compatibility, these are
1734# copied into the Pack, Place or Grid class.
1735
David Aschere2b4b322004-02-18 05:59:53 +00001736
1737def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1738 return Tk(screenName, baseName, className, useTk)
1739
Guido van Rossum18468821994-06-20 07:49:28 +00001740class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001741 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001742
Fredrik Lundh06d28152000-08-09 18:03:12 +00001743 Base class to use the methods pack_* in every widget."""
1744 def pack_configure(self, cnf={}, **kw):
1745 """Pack a widget in the parent widget. Use as options:
1746 after=widget - pack it after you have packed widget
1747 anchor=NSEW (or subset) - position widget according to
1748 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001749 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001750 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001751 fill=NONE or X or Y or BOTH - fill widget if widget grows
1752 in=master - use master to contain this widget
1753 ipadx=amount - add internal padding in x direction
1754 ipady=amount - add internal padding in y direction
1755 padx=amount - add padding in x direction
1756 pady=amount - add padding in y direction
1757 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1758 """
1759 self.tk.call(
1760 ('pack', 'configure', self._w)
1761 + self._options(cnf, kw))
1762 pack = configure = config = pack_configure
1763 def pack_forget(self):
1764 """Unmap this widget and do not use it for the packing order."""
1765 self.tk.call('pack', 'forget', self._w)
1766 forget = pack_forget
1767 def pack_info(self):
1768 """Return information about the packing options
1769 for this widget."""
1770 words = self.tk.splitlist(
1771 self.tk.call('pack', 'info', self._w))
1772 dict = {}
1773 for i in range(0, len(words), 2):
1774 key = words[i][1:]
1775 value = words[i+1]
1776 if value[:1] == '.':
1777 value = self._nametowidget(value)
1778 dict[key] = value
1779 return dict
1780 info = pack_info
1781 propagate = pack_propagate = Misc.pack_propagate
1782 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001783
1784class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001785 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001786
Fredrik Lundh06d28152000-08-09 18:03:12 +00001787 Base class to use the methods place_* in every widget."""
1788 def place_configure(self, cnf={}, **kw):
1789 """Place a widget in the parent widget. Use as options:
1790 in=master - master relative to which the widget is placed.
1791 x=amount - locate anchor of this widget at position x of master
1792 y=amount - locate anchor of this widget at position y of master
1793 relx=amount - locate anchor of this widget between 0.0 and 1.0
1794 relative to width of master (1.0 is right edge)
1795 rely=amount - locate anchor of this widget between 0.0 and 1.0
1796 relative to height of master (1.0 is bottom edge)
1797 anchor=NSEW (or subset) - position anchor according to given direction
1798 width=amount - width of this widget in pixel
1799 height=amount - height of this widget in pixel
1800 relwidth=amount - width of this widget between 0.0 and 1.0
1801 relative to width of master (1.0 is the same width
1802 as the master)
1803 relheight=amount - height of this widget between 0.0 and 1.0
1804 relative to height of master (1.0 is the same
1805 height as the master)
1806 bordermode="inside" or "outside" - whether to take border width of master widget
1807 into account
1808 """
1809 for k in ['in_']:
Guido van Rossume014a132006-08-19 16:53:45 +00001810 if k in kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001811 kw[k[:-1]] = kw[k]
1812 del kw[k]
1813 self.tk.call(
1814 ('place', 'configure', self._w)
1815 + self._options(cnf, kw))
1816 place = configure = config = place_configure
1817 def place_forget(self):
1818 """Unmap this widget."""
1819 self.tk.call('place', 'forget', self._w)
1820 forget = place_forget
1821 def place_info(self):
1822 """Return information about the placing options
1823 for this widget."""
1824 words = self.tk.splitlist(
1825 self.tk.call('place', 'info', self._w))
1826 dict = {}
1827 for i in range(0, len(words), 2):
1828 key = words[i][1:]
1829 value = words[i+1]
1830 if value[:1] == '.':
1831 value = self._nametowidget(value)
1832 dict[key] = value
1833 return dict
1834 info = place_info
1835 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001836
Guido van Rossum37dcab11996-05-16 16:00:19 +00001837class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001838 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001839
Fredrik Lundh06d28152000-08-09 18:03:12 +00001840 Base class to use the methods grid_* in every widget."""
1841 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1842 def grid_configure(self, cnf={}, **kw):
1843 """Position a widget in the parent widget in a grid. Use as options:
1844 column=number - use cell identified with given column (starting with 0)
1845 columnspan=number - this widget will span several columns
1846 in=master - use master to contain this widget
1847 ipadx=amount - add internal padding in x direction
1848 ipady=amount - add internal padding in y direction
1849 padx=amount - add padding in x direction
1850 pady=amount - add padding in y direction
1851 row=number - use cell identified with given row (starting with 0)
1852 rowspan=number - this widget will span several rows
1853 sticky=NSEW - if cell is larger on which sides will this
1854 widget stick to the cell boundary
1855 """
1856 self.tk.call(
1857 ('grid', 'configure', self._w)
1858 + self._options(cnf, kw))
1859 grid = configure = config = grid_configure
1860 bbox = grid_bbox = Misc.grid_bbox
1861 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1862 def grid_forget(self):
1863 """Unmap this widget."""
1864 self.tk.call('grid', 'forget', self._w)
1865 forget = grid_forget
1866 def grid_remove(self):
1867 """Unmap this widget but remember the grid options."""
1868 self.tk.call('grid', 'remove', self._w)
1869 def grid_info(self):
1870 """Return information about the options
1871 for positioning this widget in a grid."""
1872 words = self.tk.splitlist(
1873 self.tk.call('grid', 'info', self._w))
1874 dict = {}
1875 for i in range(0, len(words), 2):
1876 key = words[i][1:]
1877 value = words[i+1]
1878 if value[:1] == '.':
1879 value = self._nametowidget(value)
1880 dict[key] = value
1881 return dict
1882 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001883 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001884 propagate = grid_propagate = Misc.grid_propagate
1885 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1886 size = grid_size = Misc.grid_size
1887 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001888
Guido van Rossum368e06b1997-11-07 20:38:49 +00001889class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001890 """Internal class."""
1891 def _setup(self, master, cnf):
1892 """Internal function. Sets up information about children."""
1893 if _support_default_root:
1894 global _default_root
1895 if not master:
1896 if not _default_root:
1897 _default_root = Tk()
1898 master = _default_root
1899 self.master = master
1900 self.tk = master.tk
1901 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00001902 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001903 name = cnf['name']
1904 del cnf['name']
1905 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001906 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001907 self._name = name
1908 if master._w=='.':
1909 self._w = '.' + name
1910 else:
1911 self._w = master._w + '.' + name
1912 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00001913 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001914 self.master.children[self._name].destroy()
1915 self.master.children[self._name] = self
1916 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1917 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1918 and appropriate options."""
1919 if kw:
1920 cnf = _cnfmerge((cnf, kw))
1921 self.widgetName = widgetName
1922 BaseWidget._setup(self, master, cnf)
1923 classes = []
1924 for k in cnf.keys():
Guido van Rossum13257902007-06-07 23:15:56 +00001925 if isinstance(k, type):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001926 classes.append((k, cnf[k]))
1927 del cnf[k]
1928 self.tk.call(
1929 (widgetName, self._w) + extra + self._options(cnf))
1930 for k, v in classes:
1931 k.configure(self, v)
1932 def destroy(self):
1933 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00001934 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001935 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00001936 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001937 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001938 Misc.destroy(self)
1939 def _do(self, name, args=()):
1940 # XXX Obsolete -- better use self.tk.call directly!
1941 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001942
Guido van Rossum368e06b1997-11-07 20:38:49 +00001943class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001944 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001945
Fredrik Lundh06d28152000-08-09 18:03:12 +00001946 Base class for a widget which can be positioned with the geometry managers
1947 Pack, Place or Grid."""
1948 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001949
1950class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001951 """Toplevel widget, e.g. for dialogs."""
1952 def __init__(self, master=None, cnf={}, **kw):
1953 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001954
Fredrik Lundh06d28152000-08-09 18:03:12 +00001955 Valid resource names: background, bd, bg, borderwidth, class,
1956 colormap, container, cursor, height, highlightbackground,
1957 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1958 use, visual, width."""
1959 if kw:
1960 cnf = _cnfmerge((cnf, kw))
1961 extra = ()
1962 for wmkey in ['screen', 'class_', 'class', 'visual',
1963 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00001964 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001965 val = cnf[wmkey]
1966 # TBD: a hack needed because some keys
1967 # are not valid as keyword arguments
1968 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1969 else: opt = '-'+wmkey
1970 extra = extra + (opt, val)
1971 del cnf[wmkey]
1972 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1973 root = self._root()
1974 self.iconname(root.iconname())
1975 self.title(root.title())
1976 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001977
1978class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001979 """Button widget."""
1980 def __init__(self, master=None, cnf={}, **kw):
1981 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001982
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001983 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001984
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001985 activebackground, activeforeground, anchor,
1986 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001987 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001988 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001989 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001990 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001991 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001992 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001993
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001994 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001995
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001996 command, compound, default, height,
1997 overrelief, state, width
1998 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001999 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002000
Fredrik Lundh06d28152000-08-09 18:03:12 +00002001 def tkButtonEnter(self, *dummy):
2002 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002003
Fredrik Lundh06d28152000-08-09 18:03:12 +00002004 def tkButtonLeave(self, *dummy):
2005 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002006
Fredrik Lundh06d28152000-08-09 18:03:12 +00002007 def tkButtonDown(self, *dummy):
2008 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002009
Fredrik Lundh06d28152000-08-09 18:03:12 +00002010 def tkButtonUp(self, *dummy):
2011 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002012
Fredrik Lundh06d28152000-08-09 18:03:12 +00002013 def tkButtonInvoke(self, *dummy):
2014 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002015
Fredrik Lundh06d28152000-08-09 18:03:12 +00002016 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002017 """Flash the button.
2018
2019 This is accomplished by redisplaying
2020 the button several times, alternating between active and
2021 normal colors. At the end of the flash the button is left
2022 in the same normal/active state as when the command was
2023 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002024 disabled.
2025 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002026 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002027
Fredrik Lundh06d28152000-08-09 18:03:12 +00002028 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002029 """Invoke the command associated with the button.
2030
2031 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002032 or an empty string if there is no command associated with
2033 the button. This command is ignored if the button's state
2034 is disabled.
2035 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002036 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002037
2038# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002039# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00002040def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002041 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00002042def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002043 s = 'insert'
2044 for a in args:
2045 if a: s = s + (' ' + a)
2046 return s
Guido van Rossum18468821994-06-20 07:49:28 +00002047def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002048 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00002049def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002050 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00002051def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002052 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002053 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002054 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002055 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002056
2057class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002058 """Canvas widget to display graphical elements like lines or text."""
2059 def __init__(self, master=None, cnf={}, **kw):
2060 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002061
Fredrik Lundh06d28152000-08-09 18:03:12 +00002062 Valid resource names: background, bd, bg, borderwidth, closeenough,
2063 confine, cursor, height, highlightbackground, highlightcolor,
2064 highlightthickness, insertbackground, insertborderwidth,
2065 insertofftime, insertontime, insertwidth, offset, relief,
2066 scrollregion, selectbackground, selectborderwidth, selectforeground,
2067 state, takefocus, width, xscrollcommand, xscrollincrement,
2068 yscrollcommand, yscrollincrement."""
2069 Widget.__init__(self, master, 'canvas', cnf, kw)
2070 def addtag(self, *args):
2071 """Internal function."""
2072 self.tk.call((self._w, 'addtag') + args)
2073 def addtag_above(self, newtag, tagOrId):
2074 """Add tag NEWTAG to all items above TAGORID."""
2075 self.addtag(newtag, 'above', tagOrId)
2076 def addtag_all(self, newtag):
2077 """Add tag NEWTAG to all items."""
2078 self.addtag(newtag, 'all')
2079 def addtag_below(self, newtag, tagOrId):
2080 """Add tag NEWTAG to all items below TAGORID."""
2081 self.addtag(newtag, 'below', tagOrId)
2082 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2083 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2084 If several match take the top-most.
2085 All items closer than HALO are considered overlapping (all are
2086 closests). If START is specified the next below this tag is taken."""
2087 self.addtag(newtag, 'closest', x, y, halo, start)
2088 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2089 """Add tag NEWTAG to all items in the rectangle defined
2090 by X1,Y1,X2,Y2."""
2091 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2092 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2093 """Add tag NEWTAG to all items which overlap the rectangle
2094 defined by X1,Y1,X2,Y2."""
2095 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2096 def addtag_withtag(self, newtag, tagOrId):
2097 """Add tag NEWTAG to all items with TAGORID."""
2098 self.addtag(newtag, 'withtag', tagOrId)
2099 def bbox(self, *args):
2100 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2101 which encloses all items with tags specified as arguments."""
2102 return self._getints(
2103 self.tk.call((self._w, 'bbox') + args)) or None
2104 def tag_unbind(self, tagOrId, sequence, funcid=None):
2105 """Unbind for all items with TAGORID for event SEQUENCE the
2106 function identified with FUNCID."""
2107 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2108 if funcid:
2109 self.deletecommand(funcid)
2110 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2111 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002112
Fredrik Lundh06d28152000-08-09 18:03:12 +00002113 An additional boolean parameter ADD specifies whether FUNC will be
2114 called additionally to the other bound function or whether it will
2115 replace the previous function. See bind for the return value."""
2116 return self._bind((self._w, 'bind', tagOrId),
2117 sequence, func, add)
2118 def canvasx(self, screenx, gridspacing=None):
2119 """Return the canvas x coordinate of pixel position SCREENX rounded
2120 to nearest multiple of GRIDSPACING units."""
2121 return getdouble(self.tk.call(
2122 self._w, 'canvasx', screenx, gridspacing))
2123 def canvasy(self, screeny, gridspacing=None):
2124 """Return the canvas y coordinate of pixel position SCREENY rounded
2125 to nearest multiple of GRIDSPACING units."""
2126 return getdouble(self.tk.call(
2127 self._w, 'canvasy', screeny, gridspacing))
2128 def coords(self, *args):
2129 """Return a list of coordinates for the item given in ARGS."""
2130 # XXX Should use _flatten on args
2131 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002132 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002133 self.tk.call((self._w, 'coords') + args)))
2134 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2135 """Internal function."""
2136 args = _flatten(args)
2137 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002138 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002139 args = args[:-1]
2140 else:
2141 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002142 return getint(self.tk.call(
2143 self._w, 'create', itemType,
2144 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002145 def create_arc(self, *args, **kw):
2146 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2147 return self._create('arc', args, kw)
2148 def create_bitmap(self, *args, **kw):
2149 """Create bitmap with coordinates x1,y1."""
2150 return self._create('bitmap', args, kw)
2151 def create_image(self, *args, **kw):
2152 """Create image item with coordinates x1,y1."""
2153 return self._create('image', args, kw)
2154 def create_line(self, *args, **kw):
2155 """Create line with coordinates x1,y1,...,xn,yn."""
2156 return self._create('line', args, kw)
2157 def create_oval(self, *args, **kw):
2158 """Create oval with coordinates x1,y1,x2,y2."""
2159 return self._create('oval', args, kw)
2160 def create_polygon(self, *args, **kw):
2161 """Create polygon with coordinates x1,y1,...,xn,yn."""
2162 return self._create('polygon', args, kw)
2163 def create_rectangle(self, *args, **kw):
2164 """Create rectangle with coordinates x1,y1,x2,y2."""
2165 return self._create('rectangle', args, kw)
2166 def create_text(self, *args, **kw):
2167 """Create text with coordinates x1,y1."""
2168 return self._create('text', args, kw)
2169 def create_window(self, *args, **kw):
2170 """Create window with coordinates x1,y1,x2,y2."""
2171 return self._create('window', args, kw)
2172 def dchars(self, *args):
2173 """Delete characters of text items identified by tag or id in ARGS (possibly
2174 several times) from FIRST to LAST character (including)."""
2175 self.tk.call((self._w, 'dchars') + args)
2176 def delete(self, *args):
2177 """Delete items identified by all tag or ids contained in ARGS."""
2178 self.tk.call((self._w, 'delete') + args)
2179 def dtag(self, *args):
2180 """Delete tag or id given as last arguments in ARGS from items
2181 identified by first argument in ARGS."""
2182 self.tk.call((self._w, 'dtag') + args)
2183 def find(self, *args):
2184 """Internal function."""
2185 return self._getints(
2186 self.tk.call((self._w, 'find') + args)) or ()
2187 def find_above(self, tagOrId):
2188 """Return items above TAGORID."""
2189 return self.find('above', tagOrId)
2190 def find_all(self):
2191 """Return all items."""
2192 return self.find('all')
2193 def find_below(self, tagOrId):
2194 """Return all items below TAGORID."""
2195 return self.find('below', tagOrId)
2196 def find_closest(self, x, y, halo=None, start=None):
2197 """Return item which is closest to pixel at X, Y.
2198 If several match take the top-most.
2199 All items closer than HALO are considered overlapping (all are
2200 closests). If START is specified the next below this tag is taken."""
2201 return self.find('closest', x, y, halo, start)
2202 def find_enclosed(self, x1, y1, x2, y2):
2203 """Return all items in rectangle defined
2204 by X1,Y1,X2,Y2."""
2205 return self.find('enclosed', x1, y1, x2, y2)
2206 def find_overlapping(self, x1, y1, x2, y2):
2207 """Return all items which overlap the rectangle
2208 defined by X1,Y1,X2,Y2."""
2209 return self.find('overlapping', x1, y1, x2, y2)
2210 def find_withtag(self, tagOrId):
2211 """Return all items with TAGORID."""
2212 return self.find('withtag', tagOrId)
2213 def focus(self, *args):
2214 """Set focus to the first item specified in ARGS."""
2215 return self.tk.call((self._w, 'focus') + args)
2216 def gettags(self, *args):
2217 """Return tags associated with the first item specified in ARGS."""
2218 return self.tk.splitlist(
2219 self.tk.call((self._w, 'gettags') + args))
2220 def icursor(self, *args):
2221 """Set cursor at position POS in the item identified by TAGORID.
2222 In ARGS TAGORID must be first."""
2223 self.tk.call((self._w, 'icursor') + args)
2224 def index(self, *args):
2225 """Return position of cursor as integer in item specified in ARGS."""
2226 return getint(self.tk.call((self._w, 'index') + args))
2227 def insert(self, *args):
2228 """Insert TEXT in item TAGORID at position POS. ARGS must
2229 be TAGORID POS TEXT."""
2230 self.tk.call((self._w, 'insert') + args)
2231 def itemcget(self, tagOrId, option):
2232 """Return the resource value for an OPTION for item TAGORID."""
2233 return self.tk.call(
2234 (self._w, 'itemcget') + (tagOrId, '-'+option))
2235 def itemconfigure(self, tagOrId, cnf=None, **kw):
2236 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002237
Fredrik Lundh06d28152000-08-09 18:03:12 +00002238 The values for resources are specified as keyword
2239 arguments. To get an overview about
2240 the allowed keyword arguments call the method without arguments.
2241 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002242 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002243 itemconfig = itemconfigure
2244 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2245 # so the preferred name for them is tag_lower, tag_raise
2246 # (similar to tag_bind, and similar to the Text widget);
2247 # unfortunately can't delete the old ones yet (maybe in 1.6)
2248 def tag_lower(self, *args):
2249 """Lower an item TAGORID given in ARGS
2250 (optional below another item)."""
2251 self.tk.call((self._w, 'lower') + args)
2252 lower = tag_lower
2253 def move(self, *args):
2254 """Move an item TAGORID given in ARGS."""
2255 self.tk.call((self._w, 'move') + args)
2256 def postscript(self, cnf={}, **kw):
2257 """Print the contents of the canvas to a postscript
2258 file. Valid options: colormap, colormode, file, fontmap,
2259 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2260 rotate, witdh, x, y."""
2261 return self.tk.call((self._w, 'postscript') +
2262 self._options(cnf, kw))
2263 def tag_raise(self, *args):
2264 """Raise an item TAGORID given in ARGS
2265 (optional above another item)."""
2266 self.tk.call((self._w, 'raise') + args)
2267 lift = tkraise = tag_raise
2268 def scale(self, *args):
2269 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2270 self.tk.call((self._w, 'scale') + args)
2271 def scan_mark(self, x, y):
2272 """Remember the current X, Y coordinates."""
2273 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002274 def scan_dragto(self, x, y, gain=10):
2275 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002276 difference between X and Y and the coordinates given in
2277 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002278 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002279 def select_adjust(self, tagOrId, index):
2280 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2281 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2282 def select_clear(self):
2283 """Clear the selection if it is in this widget."""
2284 self.tk.call(self._w, 'select', 'clear')
2285 def select_from(self, tagOrId, index):
2286 """Set the fixed end of a selection in item TAGORID to INDEX."""
2287 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2288 def select_item(self):
2289 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002290 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002291 def select_to(self, tagOrId, index):
2292 """Set the variable end of a selection in item TAGORID to INDEX."""
2293 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2294 def type(self, tagOrId):
2295 """Return the type of the item TAGORID."""
2296 return self.tk.call(self._w, 'type', tagOrId) or None
2297 def xview(self, *args):
2298 """Query and change horizontal position of the view."""
2299 if not args:
2300 return self._getdoubles(self.tk.call(self._w, 'xview'))
2301 self.tk.call((self._w, 'xview') + args)
2302 def xview_moveto(self, fraction):
2303 """Adjusts the view in the window so that FRACTION of the
2304 total width of the canvas is off-screen to the left."""
2305 self.tk.call(self._w, 'xview', 'moveto', fraction)
2306 def xview_scroll(self, number, what):
2307 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2308 self.tk.call(self._w, 'xview', 'scroll', number, what)
2309 def yview(self, *args):
2310 """Query and change vertical position of the view."""
2311 if not args:
2312 return self._getdoubles(self.tk.call(self._w, 'yview'))
2313 self.tk.call((self._w, 'yview') + args)
2314 def yview_moveto(self, fraction):
2315 """Adjusts the view in the window so that FRACTION of the
2316 total height of the canvas is off-screen to the top."""
2317 self.tk.call(self._w, 'yview', 'moveto', fraction)
2318 def yview_scroll(self, number, what):
2319 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2320 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002321
2322class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002323 """Checkbutton widget which is either in on- or off-state."""
2324 def __init__(self, master=None, cnf={}, **kw):
2325 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002326
Fredrik Lundh06d28152000-08-09 18:03:12 +00002327 Valid resource names: activebackground, activeforeground, anchor,
2328 background, bd, bg, bitmap, borderwidth, command, cursor,
2329 disabledforeground, fg, font, foreground, height,
2330 highlightbackground, highlightcolor, highlightthickness, image,
2331 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2332 selectcolor, selectimage, state, takefocus, text, textvariable,
2333 underline, variable, width, wraplength."""
2334 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2335 def deselect(self):
2336 """Put the button in off-state."""
2337 self.tk.call(self._w, 'deselect')
2338 def flash(self):
2339 """Flash the button."""
2340 self.tk.call(self._w, 'flash')
2341 def invoke(self):
2342 """Toggle the button and invoke a command if given as resource."""
2343 return self.tk.call(self._w, 'invoke')
2344 def select(self):
2345 """Put the button in on-state."""
2346 self.tk.call(self._w, 'select')
2347 def toggle(self):
2348 """Toggle the button."""
2349 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002350
2351class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002352 """Entry widget which allows to display simple text."""
2353 def __init__(self, master=None, cnf={}, **kw):
2354 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002355
Fredrik Lundh06d28152000-08-09 18:03:12 +00002356 Valid resource names: background, bd, bg, borderwidth, cursor,
2357 exportselection, fg, font, foreground, highlightbackground,
2358 highlightcolor, highlightthickness, insertbackground,
2359 insertborderwidth, insertofftime, insertontime, insertwidth,
2360 invalidcommand, invcmd, justify, relief, selectbackground,
2361 selectborderwidth, selectforeground, show, state, takefocus,
2362 textvariable, validate, validatecommand, vcmd, width,
2363 xscrollcommand."""
2364 Widget.__init__(self, master, 'entry', cnf, kw)
2365 def delete(self, first, last=None):
2366 """Delete text from FIRST to LAST (not included)."""
2367 self.tk.call(self._w, 'delete', first, last)
2368 def get(self):
2369 """Return the text."""
2370 return self.tk.call(self._w, 'get')
2371 def icursor(self, index):
2372 """Insert cursor at INDEX."""
2373 self.tk.call(self._w, 'icursor', index)
2374 def index(self, index):
2375 """Return position of cursor."""
2376 return getint(self.tk.call(
2377 self._w, 'index', index))
2378 def insert(self, index, string):
2379 """Insert STRING at INDEX."""
2380 self.tk.call(self._w, 'insert', index, string)
2381 def scan_mark(self, x):
2382 """Remember the current X, Y coordinates."""
2383 self.tk.call(self._w, 'scan', 'mark', x)
2384 def scan_dragto(self, x):
2385 """Adjust the view of the canvas to 10 times the
2386 difference between X and Y and the coordinates given in
2387 scan_mark."""
2388 self.tk.call(self._w, 'scan', 'dragto', x)
2389 def selection_adjust(self, index):
2390 """Adjust the end of the selection near the cursor to INDEX."""
2391 self.tk.call(self._w, 'selection', 'adjust', index)
2392 select_adjust = selection_adjust
2393 def selection_clear(self):
2394 """Clear the selection if it is in this widget."""
2395 self.tk.call(self._w, 'selection', 'clear')
2396 select_clear = selection_clear
2397 def selection_from(self, index):
2398 """Set the fixed end of a selection to INDEX."""
2399 self.tk.call(self._w, 'selection', 'from', index)
2400 select_from = selection_from
2401 def selection_present(self):
2402 """Return whether the widget has the selection."""
2403 return self.tk.getboolean(
2404 self.tk.call(self._w, 'selection', 'present'))
2405 select_present = selection_present
2406 def selection_range(self, start, end):
2407 """Set the selection from START to END (not included)."""
2408 self.tk.call(self._w, 'selection', 'range', start, end)
2409 select_range = selection_range
2410 def selection_to(self, index):
2411 """Set the variable end of a selection to INDEX."""
2412 self.tk.call(self._w, 'selection', 'to', index)
2413 select_to = selection_to
2414 def xview(self, index):
2415 """Query and change horizontal position of the view."""
2416 self.tk.call(self._w, 'xview', index)
2417 def xview_moveto(self, fraction):
2418 """Adjust the view in the window so that FRACTION of the
2419 total width of the entry is off-screen to the left."""
2420 self.tk.call(self._w, 'xview', 'moveto', fraction)
2421 def xview_scroll(self, number, what):
2422 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2423 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002424
2425class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002426 """Frame widget which may contain other widgets and can have a 3D border."""
2427 def __init__(self, master=None, cnf={}, **kw):
2428 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002429
Fredrik Lundh06d28152000-08-09 18:03:12 +00002430 Valid resource names: background, bd, bg, borderwidth, class,
2431 colormap, container, cursor, height, highlightbackground,
2432 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2433 cnf = _cnfmerge((cnf, kw))
2434 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002435 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002436 extra = ('-class', cnf['class_'])
2437 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002438 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002439 extra = ('-class', cnf['class'])
2440 del cnf['class']
2441 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002442
2443class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002444 """Label widget which can display text and bitmaps."""
2445 def __init__(self, master=None, cnf={}, **kw):
2446 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002447
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002448 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002449
2450 activebackground, activeforeground, anchor,
2451 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002452 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002453 highlightbackground, highlightcolor,
2454 highlightthickness, image, justify,
2455 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002456 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002457
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002458 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002459
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002460 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002461
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002462 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002463 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002464
Guido van Rossum18468821994-06-20 07:49:28 +00002465class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002466 """Listbox widget which can display a list of strings."""
2467 def __init__(self, master=None, cnf={}, **kw):
2468 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002469
Fredrik Lundh06d28152000-08-09 18:03:12 +00002470 Valid resource names: background, bd, bg, borderwidth, cursor,
2471 exportselection, fg, font, foreground, height, highlightbackground,
2472 highlightcolor, highlightthickness, relief, selectbackground,
2473 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2474 width, xscrollcommand, yscrollcommand, listvariable."""
2475 Widget.__init__(self, master, 'listbox', cnf, kw)
2476 def activate(self, index):
2477 """Activate item identified by INDEX."""
2478 self.tk.call(self._w, 'activate', index)
2479 def bbox(self, *args):
2480 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2481 which encloses the item identified by index in ARGS."""
2482 return self._getints(
2483 self.tk.call((self._w, 'bbox') + args)) or None
2484 def curselection(self):
2485 """Return list of indices of currently selected item."""
2486 # XXX Ought to apply self._getints()...
2487 return self.tk.splitlist(self.tk.call(
2488 self._w, 'curselection'))
2489 def delete(self, first, last=None):
2490 """Delete items from FIRST to LAST (not included)."""
2491 self.tk.call(self._w, 'delete', first, last)
2492 def get(self, first, last=None):
2493 """Get list of items from FIRST to LAST (not included)."""
2494 if last:
2495 return self.tk.splitlist(self.tk.call(
2496 self._w, 'get', first, last))
2497 else:
2498 return self.tk.call(self._w, 'get', first)
2499 def index(self, index):
2500 """Return index of item identified with INDEX."""
2501 i = self.tk.call(self._w, 'index', index)
2502 if i == 'none': return None
2503 return getint(i)
2504 def insert(self, index, *elements):
2505 """Insert ELEMENTS at INDEX."""
2506 self.tk.call((self._w, 'insert', index) + elements)
2507 def nearest(self, y):
2508 """Get index of item which is nearest to y coordinate Y."""
2509 return getint(self.tk.call(
2510 self._w, 'nearest', y))
2511 def scan_mark(self, x, y):
2512 """Remember the current X, Y coordinates."""
2513 self.tk.call(self._w, 'scan', 'mark', x, y)
2514 def scan_dragto(self, x, y):
2515 """Adjust the view of the listbox to 10 times the
2516 difference between X and Y and the coordinates given in
2517 scan_mark."""
2518 self.tk.call(self._w, 'scan', 'dragto', x, y)
2519 def see(self, index):
2520 """Scroll such that INDEX is visible."""
2521 self.tk.call(self._w, 'see', index)
2522 def selection_anchor(self, index):
2523 """Set the fixed end oft the selection to INDEX."""
2524 self.tk.call(self._w, 'selection', 'anchor', index)
2525 select_anchor = selection_anchor
2526 def selection_clear(self, first, last=None):
2527 """Clear the selection from FIRST to LAST (not included)."""
2528 self.tk.call(self._w,
2529 'selection', 'clear', first, last)
2530 select_clear = selection_clear
2531 def selection_includes(self, index):
2532 """Return 1 if INDEX is part of the selection."""
2533 return self.tk.getboolean(self.tk.call(
2534 self._w, 'selection', 'includes', index))
2535 select_includes = selection_includes
2536 def selection_set(self, first, last=None):
2537 """Set the selection from FIRST to LAST (not included) without
2538 changing the currently selected elements."""
2539 self.tk.call(self._w, 'selection', 'set', first, last)
2540 select_set = selection_set
2541 def size(self):
2542 """Return the number of elements in the listbox."""
2543 return getint(self.tk.call(self._w, 'size'))
2544 def xview(self, *what):
2545 """Query and change horizontal position of the view."""
2546 if not what:
2547 return self._getdoubles(self.tk.call(self._w, 'xview'))
2548 self.tk.call((self._w, 'xview') + what)
2549 def xview_moveto(self, fraction):
2550 """Adjust the view in the window so that FRACTION of the
2551 total width of the entry is off-screen to the left."""
2552 self.tk.call(self._w, 'xview', 'moveto', fraction)
2553 def xview_scroll(self, number, what):
2554 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2555 self.tk.call(self._w, 'xview', 'scroll', number, what)
2556 def yview(self, *what):
2557 """Query and change vertical position of the view."""
2558 if not what:
2559 return self._getdoubles(self.tk.call(self._w, 'yview'))
2560 self.tk.call((self._w, 'yview') + what)
2561 def yview_moveto(self, fraction):
2562 """Adjust the view in the window so that FRACTION of the
2563 total width of the entry is off-screen to the top."""
2564 self.tk.call(self._w, 'yview', 'moveto', fraction)
2565 def yview_scroll(self, number, what):
2566 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2567 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002568 def itemcget(self, index, option):
2569 """Return the resource value for an ITEM and an OPTION."""
2570 return self.tk.call(
2571 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002572 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002573 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002574
2575 The values for resources are specified as keyword arguments.
2576 To get an overview about the allowed keyword arguments
2577 call the method without arguments.
2578 Valid resource names: background, bg, foreground, fg,
2579 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002580 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002581 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002582
2583class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002584 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2585 def __init__(self, master=None, cnf={}, **kw):
2586 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002587
Fredrik Lundh06d28152000-08-09 18:03:12 +00002588 Valid resource names: activebackground, activeborderwidth,
2589 activeforeground, background, bd, bg, borderwidth, cursor,
2590 disabledforeground, fg, font, foreground, postcommand, relief,
2591 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2592 Widget.__init__(self, master, 'menu', cnf, kw)
2593 def tk_bindForTraversal(self):
2594 pass # obsolete since Tk 4.0
2595 def tk_mbPost(self):
2596 self.tk.call('tk_mbPost', self._w)
2597 def tk_mbUnpost(self):
2598 self.tk.call('tk_mbUnpost')
2599 def tk_traverseToMenu(self, char):
2600 self.tk.call('tk_traverseToMenu', self._w, char)
2601 def tk_traverseWithinMenu(self, char):
2602 self.tk.call('tk_traverseWithinMenu', self._w, char)
2603 def tk_getMenuButtons(self):
2604 return self.tk.call('tk_getMenuButtons', self._w)
2605 def tk_nextMenu(self, count):
2606 self.tk.call('tk_nextMenu', count)
2607 def tk_nextMenuEntry(self, count):
2608 self.tk.call('tk_nextMenuEntry', count)
2609 def tk_invokeMenu(self):
2610 self.tk.call('tk_invokeMenu', self._w)
2611 def tk_firstMenu(self):
2612 self.tk.call('tk_firstMenu', self._w)
2613 def tk_mbButtonDown(self):
2614 self.tk.call('tk_mbButtonDown', self._w)
2615 def tk_popup(self, x, y, entry=""):
2616 """Post the menu at position X,Y with entry ENTRY."""
2617 self.tk.call('tk_popup', self._w, x, y, entry)
2618 def activate(self, index):
2619 """Activate entry at INDEX."""
2620 self.tk.call(self._w, 'activate', index)
2621 def add(self, itemType, cnf={}, **kw):
2622 """Internal function."""
2623 self.tk.call((self._w, 'add', itemType) +
2624 self._options(cnf, kw))
2625 def add_cascade(self, cnf={}, **kw):
2626 """Add hierarchical menu item."""
2627 self.add('cascade', cnf or kw)
2628 def add_checkbutton(self, cnf={}, **kw):
2629 """Add checkbutton menu item."""
2630 self.add('checkbutton', cnf or kw)
2631 def add_command(self, cnf={}, **kw):
2632 """Add command menu item."""
2633 self.add('command', cnf or kw)
2634 def add_radiobutton(self, cnf={}, **kw):
2635 """Addd radio menu item."""
2636 self.add('radiobutton', cnf or kw)
2637 def add_separator(self, cnf={}, **kw):
2638 """Add separator."""
2639 self.add('separator', cnf or kw)
2640 def insert(self, index, itemType, cnf={}, **kw):
2641 """Internal function."""
2642 self.tk.call((self._w, 'insert', index, itemType) +
2643 self._options(cnf, kw))
2644 def insert_cascade(self, index, cnf={}, **kw):
2645 """Add hierarchical menu item at INDEX."""
2646 self.insert(index, 'cascade', cnf or kw)
2647 def insert_checkbutton(self, index, cnf={}, **kw):
2648 """Add checkbutton menu item at INDEX."""
2649 self.insert(index, 'checkbutton', cnf or kw)
2650 def insert_command(self, index, cnf={}, **kw):
2651 """Add command menu item at INDEX."""
2652 self.insert(index, 'command', cnf or kw)
2653 def insert_radiobutton(self, index, cnf={}, **kw):
2654 """Addd radio menu item at INDEX."""
2655 self.insert(index, 'radiobutton', cnf or kw)
2656 def insert_separator(self, index, cnf={}, **kw):
2657 """Add separator at INDEX."""
2658 self.insert(index, 'separator', cnf or kw)
2659 def delete(self, index1, index2=None):
2660 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2661 self.tk.call(self._w, 'delete', index1, index2)
2662 def entrycget(self, index, option):
2663 """Return the resource value of an menu item for OPTION at INDEX."""
2664 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2665 def entryconfigure(self, index, cnf=None, **kw):
2666 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002667 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002668 entryconfig = entryconfigure
2669 def index(self, index):
2670 """Return the index of a menu item identified by INDEX."""
2671 i = self.tk.call(self._w, 'index', index)
2672 if i == 'none': return None
2673 return getint(i)
2674 def invoke(self, index):
2675 """Invoke a menu item identified by INDEX and execute
2676 the associated command."""
2677 return self.tk.call(self._w, 'invoke', index)
2678 def post(self, x, y):
2679 """Display a menu at position X,Y."""
2680 self.tk.call(self._w, 'post', x, y)
2681 def type(self, index):
2682 """Return the type of the menu item at INDEX."""
2683 return self.tk.call(self._w, 'type', index)
2684 def unpost(self):
2685 """Unmap a menu."""
2686 self.tk.call(self._w, 'unpost')
2687 def yposition(self, index):
2688 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2689 return getint(self.tk.call(
2690 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002691
2692class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002693 """Menubutton widget, obsolete since Tk8.0."""
2694 def __init__(self, master=None, cnf={}, **kw):
2695 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002696
2697class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002698 """Message widget to display multiline text. Obsolete since Label does it too."""
2699 def __init__(self, master=None, cnf={}, **kw):
2700 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002701
2702class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002703 """Radiobutton widget which shows only one of several buttons in on-state."""
2704 def __init__(self, master=None, cnf={}, **kw):
2705 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002706
Fredrik Lundh06d28152000-08-09 18:03:12 +00002707 Valid resource names: activebackground, activeforeground, anchor,
2708 background, bd, bg, bitmap, borderwidth, command, cursor,
2709 disabledforeground, fg, font, foreground, height,
2710 highlightbackground, highlightcolor, highlightthickness, image,
2711 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2712 state, takefocus, text, textvariable, underline, value, variable,
2713 width, wraplength."""
2714 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2715 def deselect(self):
2716 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002717
Fredrik Lundh06d28152000-08-09 18:03:12 +00002718 self.tk.call(self._w, 'deselect')
2719 def flash(self):
2720 """Flash the button."""
2721 self.tk.call(self._w, 'flash')
2722 def invoke(self):
2723 """Toggle the button and invoke a command if given as resource."""
2724 return self.tk.call(self._w, 'invoke')
2725 def select(self):
2726 """Put the button in on-state."""
2727 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002728
2729class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002730 """Scale widget which can display a numerical scale."""
2731 def __init__(self, master=None, cnf={}, **kw):
2732 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002733
Fredrik Lundh06d28152000-08-09 18:03:12 +00002734 Valid resource names: activebackground, background, bigincrement, bd,
2735 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2736 highlightbackground, highlightcolor, highlightthickness, label,
2737 length, orient, relief, repeatdelay, repeatinterval, resolution,
2738 showvalue, sliderlength, sliderrelief, state, takefocus,
2739 tickinterval, to, troughcolor, variable, width."""
2740 Widget.__init__(self, master, 'scale', cnf, kw)
2741 def get(self):
2742 """Get the current value as integer or float."""
2743 value = self.tk.call(self._w, 'get')
2744 try:
2745 return getint(value)
2746 except ValueError:
2747 return getdouble(value)
2748 def set(self, value):
2749 """Set the value to VALUE."""
2750 self.tk.call(self._w, 'set', value)
2751 def coords(self, value=None):
2752 """Return a tuple (X,Y) of the point along the centerline of the
2753 trough that corresponds to VALUE or the current value if None is
2754 given."""
2755
2756 return self._getints(self.tk.call(self._w, 'coords', value))
2757 def identify(self, x, y):
2758 """Return where the point X,Y lies. Valid return values are "slider",
2759 "though1" and "though2"."""
2760 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002761
2762class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002763 """Scrollbar widget which displays a slider at a certain position."""
2764 def __init__(self, master=None, cnf={}, **kw):
2765 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002766
Fredrik Lundh06d28152000-08-09 18:03:12 +00002767 Valid resource names: activebackground, activerelief,
2768 background, bd, bg, borderwidth, command, cursor,
2769 elementborderwidth, highlightbackground,
2770 highlightcolor, highlightthickness, jump, orient,
2771 relief, repeatdelay, repeatinterval, takefocus,
2772 troughcolor, width."""
2773 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2774 def activate(self, index):
2775 """Display the element at INDEX with activebackground and activerelief.
2776 INDEX can be "arrow1","slider" or "arrow2"."""
2777 self.tk.call(self._w, 'activate', index)
2778 def delta(self, deltax, deltay):
2779 """Return the fractional change of the scrollbar setting if it
2780 would be moved by DELTAX or DELTAY pixels."""
2781 return getdouble(
2782 self.tk.call(self._w, 'delta', deltax, deltay))
2783 def fraction(self, x, y):
2784 """Return the fractional value which corresponds to a slider
2785 position of X,Y."""
2786 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2787 def identify(self, x, y):
2788 """Return the element under position X,Y as one of
2789 "arrow1","slider","arrow2" or ""."""
2790 return self.tk.call(self._w, 'identify', x, y)
2791 def get(self):
2792 """Return the current fractional values (upper and lower end)
2793 of the slider position."""
2794 return self._getdoubles(self.tk.call(self._w, 'get'))
2795 def set(self, *args):
2796 """Set the fractional values of the slider position (upper and
2797 lower ends as value between 0 and 1)."""
2798 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002799
2800
2801
Guido van Rossum18468821994-06-20 07:49:28 +00002802class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002803 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002804 def __init__(self, master=None, cnf={}, **kw):
2805 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002806
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002807 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002808
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002809 background, borderwidth, cursor,
2810 exportselection, font, foreground,
2811 highlightbackground, highlightcolor,
2812 highlightthickness, insertbackground,
2813 insertborderwidth, insertofftime,
2814 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002815 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002816 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002817 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002818 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002819
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002820 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002821
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002822 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002823 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002824 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002825
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002826 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002827 Widget.__init__(self, master, 'text', cnf, kw)
2828 def bbox(self, *args):
2829 """Return a tuple of (x,y,width,height) which gives the bounding
2830 box of the visible part of the character at the index in ARGS."""
2831 return self._getints(
2832 self.tk.call((self._w, 'bbox') + args)) or None
2833 def tk_textSelectTo(self, index):
2834 self.tk.call('tk_textSelectTo', self._w, index)
2835 def tk_textBackspace(self):
2836 self.tk.call('tk_textBackspace', self._w)
2837 def tk_textIndexCloser(self, a, b, c):
2838 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2839 def tk_textResetAnchor(self, index):
2840 self.tk.call('tk_textResetAnchor', self._w, index)
2841 def compare(self, index1, op, index2):
2842 """Return whether between index INDEX1 and index INDEX2 the
2843 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2844 return self.tk.getboolean(self.tk.call(
2845 self._w, 'compare', index1, op, index2))
2846 def debug(self, boolean=None):
2847 """Turn on the internal consistency checks of the B-Tree inside the text
2848 widget according to BOOLEAN."""
2849 return self.tk.getboolean(self.tk.call(
2850 self._w, 'debug', boolean))
2851 def delete(self, index1, index2=None):
2852 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2853 self.tk.call(self._w, 'delete', index1, index2)
2854 def dlineinfo(self, index):
2855 """Return tuple (x,y,width,height,baseline) giving the bounding box
2856 and baseline position of the visible part of the line containing
2857 the character at INDEX."""
2858 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002859 def dump(self, index1, index2=None, command=None, **kw):
2860 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002861
Guido van Rossum256705b2002-04-23 13:29:43 +00002862 The type of contents returned in filtered based on the keyword
2863 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2864 given and true, then the corresponding items are returned. The result
2865 is a list of triples of the form (key, value, index). If none of the
2866 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002867
Guido van Rossum256705b2002-04-23 13:29:43 +00002868 If the 'command' argument is given, it is called once for each element
2869 of the list of triples, with the values of each triple serving as the
2870 arguments to the function. In this case the list is not returned."""
2871 args = []
2872 func_name = None
2873 result = None
2874 if not command:
2875 # Never call the dump command without the -command flag, since the
2876 # output could involve Tcl quoting and would be a pain to parse
2877 # right. Instead just set the command to build a list of triples
2878 # as if we had done the parsing.
2879 result = []
2880 def append_triple(key, value, index, result=result):
2881 result.append((key, value, index))
2882 command = append_triple
2883 try:
2884 if not isinstance(command, str):
2885 func_name = command = self._register(command)
2886 args += ["-command", command]
2887 for key in kw:
2888 if kw[key]: args.append("-" + key)
2889 args.append(index1)
2890 if index2:
2891 args.append(index2)
2892 self.tk.call(self._w, "dump", *args)
2893 return result
2894 finally:
2895 if func_name:
2896 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002897
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002898 ## new in tk8.4
2899 def edit(self, *args):
2900 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002901
2902 This method controls the undo mechanism and
2903 the modified flag. The exact behavior of the
2904 command depends on the option argument that
2905 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002906 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002907
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002908 edit_modified, edit_redo, edit_reset, edit_separator
2909 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002910
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002911 """
2912 return self._getints(
2913 self.tk.call((self._w, 'edit') + args)) or ()
2914
2915 def edit_modified(self, arg=None):
2916 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002917
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002918 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002919 flag of the widget. The insert, delete, edit undo and
2920 edit redo commands or the user can set or clear the
2921 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002922 modified flag of the widget to arg.
2923 """
2924 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002925
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002926 def edit_redo(self):
2927 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002928
2929 When the undo option is true, reapplies the last
2930 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002931 then. Generates an error when the redo stack is empty.
2932 Does nothing when the undo option is false.
2933 """
2934 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002935
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002936 def edit_reset(self):
2937 """Clears the undo and redo stacks
2938 """
2939 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002940
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002941 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002942 """Inserts a separator (boundary) on the undo stack.
2943
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002944 Does nothing when the undo option is false
2945 """
2946 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002947
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002948 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002949 """Undoes the last edit action
2950
2951 If the undo option is true. An edit action is defined
2952 as all the insert and delete commands that are recorded
2953 on the undo stack in between two separators. Generates
2954 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002955 when the undo option is false
2956 """
2957 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002958
Fredrik Lundh06d28152000-08-09 18:03:12 +00002959 def get(self, index1, index2=None):
2960 """Return the text from INDEX1 to INDEX2 (not included)."""
2961 return self.tk.call(self._w, 'get', index1, index2)
2962 # (Image commands are new in 8.0)
2963 def image_cget(self, index, option):
2964 """Return the value of OPTION of an embedded image at INDEX."""
2965 if option[:1] != "-":
2966 option = "-" + option
2967 if option[-1:] == "_":
2968 option = option[:-1]
2969 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002970 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002971 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002972 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002973 def image_create(self, index, cnf={}, **kw):
2974 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002975 return self.tk.call(
2976 self._w, "image", "create", index,
2977 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002978 def image_names(self):
2979 """Return all names of embedded images in this widget."""
2980 return self.tk.call(self._w, "image", "names")
2981 def index(self, index):
2982 """Return the index in the form line.char for INDEX."""
2983 return self.tk.call(self._w, 'index', index)
2984 def insert(self, index, chars, *args):
2985 """Insert CHARS before the characters at INDEX. An additional
2986 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2987 self.tk.call((self._w, 'insert', index, chars) + args)
2988 def mark_gravity(self, markName, direction=None):
2989 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2990 Return the current value if None is given for DIRECTION."""
2991 return self.tk.call(
2992 (self._w, 'mark', 'gravity', markName, direction))
2993 def mark_names(self):
2994 """Return all mark names."""
2995 return self.tk.splitlist(self.tk.call(
2996 self._w, 'mark', 'names'))
2997 def mark_set(self, markName, index):
2998 """Set mark MARKNAME before the character at INDEX."""
2999 self.tk.call(self._w, 'mark', 'set', markName, index)
3000 def mark_unset(self, *markNames):
3001 """Delete all marks in MARKNAMES."""
3002 self.tk.call((self._w, 'mark', 'unset') + markNames)
3003 def mark_next(self, index):
3004 """Return the name of the next mark after INDEX."""
3005 return self.tk.call(self._w, 'mark', 'next', index) or None
3006 def mark_previous(self, index):
3007 """Return the name of the previous mark before INDEX."""
3008 return self.tk.call(self._w, 'mark', 'previous', index) or None
3009 def scan_mark(self, x, y):
3010 """Remember the current X, Y coordinates."""
3011 self.tk.call(self._w, 'scan', 'mark', x, y)
3012 def scan_dragto(self, x, y):
3013 """Adjust the view of the text to 10 times the
3014 difference between X and Y and the coordinates given in
3015 scan_mark."""
3016 self.tk.call(self._w, 'scan', 'dragto', x, y)
3017 def search(self, pattern, index, stopindex=None,
3018 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003019 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003020 """Search PATTERN beginning from INDEX until STOPINDEX.
3021 Return the index of the first character of a match or an empty string."""
3022 args = [self._w, 'search']
3023 if forwards: args.append('-forwards')
3024 if backwards: args.append('-backwards')
3025 if exact: args.append('-exact')
3026 if regexp: args.append('-regexp')
3027 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003028 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003029 if count: args.append('-count'); args.append(count)
3030 if pattern[0] == '-': args.append('--')
3031 args.append(pattern)
3032 args.append(index)
3033 if stopindex: args.append(stopindex)
3034 return self.tk.call(tuple(args))
3035 def see(self, index):
3036 """Scroll such that the character at INDEX is visible."""
3037 self.tk.call(self._w, 'see', index)
3038 def tag_add(self, tagName, index1, *args):
3039 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3040 Additional pairs of indices may follow in ARGS."""
3041 self.tk.call(
3042 (self._w, 'tag', 'add', tagName, index1) + args)
3043 def tag_unbind(self, tagName, sequence, funcid=None):
3044 """Unbind for all characters with TAGNAME for event SEQUENCE the
3045 function identified with FUNCID."""
3046 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3047 if funcid:
3048 self.deletecommand(funcid)
3049 def tag_bind(self, tagName, sequence, func, add=None):
3050 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003051
Fredrik Lundh06d28152000-08-09 18:03:12 +00003052 An additional boolean parameter ADD specifies whether FUNC will be
3053 called additionally to the other bound function or whether it will
3054 replace the previous function. See bind for the return value."""
3055 return self._bind((self._w, 'tag', 'bind', tagName),
3056 sequence, func, add)
3057 def tag_cget(self, tagName, option):
3058 """Return the value of OPTION for tag TAGNAME."""
3059 if option[:1] != '-':
3060 option = '-' + option
3061 if option[-1:] == '_':
3062 option = option[:-1]
3063 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003064 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003065 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003066 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003067 tag_config = tag_configure
3068 def tag_delete(self, *tagNames):
3069 """Delete all tags in TAGNAMES."""
3070 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3071 def tag_lower(self, tagName, belowThis=None):
3072 """Change the priority of tag TAGNAME such that it is lower
3073 than the priority of BELOWTHIS."""
3074 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3075 def tag_names(self, index=None):
3076 """Return a list of all tag names."""
3077 return self.tk.splitlist(
3078 self.tk.call(self._w, 'tag', 'names', index))
3079 def tag_nextrange(self, tagName, index1, index2=None):
3080 """Return a list of start and end index for the first sequence of
3081 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3082 The text is searched forward from INDEX1."""
3083 return self.tk.splitlist(self.tk.call(
3084 self._w, 'tag', 'nextrange', tagName, index1, index2))
3085 def tag_prevrange(self, tagName, index1, index2=None):
3086 """Return a list of start and end index for the first sequence of
3087 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3088 The text is searched backwards from INDEX1."""
3089 return self.tk.splitlist(self.tk.call(
3090 self._w, 'tag', 'prevrange', tagName, index1, index2))
3091 def tag_raise(self, tagName, aboveThis=None):
3092 """Change the priority of tag TAGNAME such that it is higher
3093 than the priority of ABOVETHIS."""
3094 self.tk.call(
3095 self._w, 'tag', 'raise', tagName, aboveThis)
3096 def tag_ranges(self, tagName):
3097 """Return a list of ranges of text which have tag TAGNAME."""
3098 return self.tk.splitlist(self.tk.call(
3099 self._w, 'tag', 'ranges', tagName))
3100 def tag_remove(self, tagName, index1, index2=None):
3101 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3102 self.tk.call(
3103 self._w, 'tag', 'remove', tagName, index1, index2)
3104 def window_cget(self, index, option):
3105 """Return the value of OPTION of an embedded window at INDEX."""
3106 if option[:1] != '-':
3107 option = '-' + option
3108 if option[-1:] == '_':
3109 option = option[:-1]
3110 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003111 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003112 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003113 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003114 window_config = window_configure
3115 def window_create(self, index, cnf={}, **kw):
3116 """Create a window at INDEX."""
3117 self.tk.call(
3118 (self._w, 'window', 'create', index)
3119 + self._options(cnf, kw))
3120 def window_names(self):
3121 """Return all names of embedded windows in this widget."""
3122 return self.tk.splitlist(
3123 self.tk.call(self._w, 'window', 'names'))
3124 def xview(self, *what):
3125 """Query and change horizontal position of the view."""
3126 if not what:
3127 return self._getdoubles(self.tk.call(self._w, 'xview'))
3128 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003129 def xview_moveto(self, fraction):
3130 """Adjusts the view in the window so that FRACTION of the
3131 total width of the canvas is off-screen to the left."""
3132 self.tk.call(self._w, 'xview', 'moveto', fraction)
3133 def xview_scroll(self, number, what):
3134 """Shift the x-view according to NUMBER which is measured
3135 in "units" or "pages" (WHAT)."""
3136 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003137 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003138 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003139 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003140 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003141 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003142 def yview_moveto(self, fraction):
3143 """Adjusts the view in the window so that FRACTION of the
3144 total height of the canvas is off-screen to the top."""
3145 self.tk.call(self._w, 'yview', 'moveto', fraction)
3146 def yview_scroll(self, number, what):
3147 """Shift the y-view according to NUMBER which is measured
3148 in "units" or "pages" (WHAT)."""
3149 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003150 def yview_pickplace(self, *what):
3151 """Obsolete function, use see."""
3152 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003153
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003154
Guido van Rossum28574b51996-10-21 15:16:51 +00003155class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003156 """Internal class. It wraps the command in the widget OptionMenu."""
3157 def __init__(self, var, value, callback=None):
3158 self.__value = value
3159 self.__var = var
3160 self.__callback = callback
3161 def __call__(self, *args):
3162 self.__var.set(self.__value)
3163 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003164 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003165
3166class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003167 """OptionMenu which allows the user to select a value from a menu."""
3168 def __init__(self, master, variable, value, *values, **kwargs):
3169 """Construct an optionmenu widget with the parent MASTER, with
3170 the resource textvariable set to VARIABLE, the initially selected
3171 value VALUE, the other menu values VALUES and an additional
3172 keyword argument command."""
3173 kw = {"borderwidth": 2, "textvariable": variable,
3174 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3175 "highlightthickness": 2}
3176 Widget.__init__(self, master, "menubutton", kw)
3177 self.widgetName = 'tk_optionMenu'
3178 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3179 self.menuname = menu._w
3180 # 'command' is the only supported keyword
3181 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003182 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003183 del kwargs['command']
3184 if kwargs:
3185 raise TclError, 'unknown option -'+kwargs.keys()[0]
3186 menu.add_command(label=value,
3187 command=_setit(variable, value, callback))
3188 for v in values:
3189 menu.add_command(label=v,
3190 command=_setit(variable, v, callback))
3191 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003192
Fredrik Lundh06d28152000-08-09 18:03:12 +00003193 def __getitem__(self, name):
3194 if name == 'menu':
3195 return self.__menu
3196 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003197
Fredrik Lundh06d28152000-08-09 18:03:12 +00003198 def destroy(self):
3199 """Destroy this widget and the associated menu."""
3200 Menubutton.destroy(self)
3201 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003202
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003203class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003204 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003205 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003206 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3207 self.name = None
3208 if not master:
3209 master = _default_root
3210 if not master:
3211 raise RuntimeError, 'Too early to create image'
3212 self.tk = master.tk
3213 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003214 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003215 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003216 # The following is needed for systems where id(x)
3217 # can return a negative number, such as Linux/m68k:
3218 if name[0] == '-': name = '_' + name[1:]
3219 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3220 elif kw: cnf = kw
3221 options = ()
3222 for k, v in cnf.items():
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003223 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003224 v = self._register(v)
3225 options = options + ('-'+k, v)
3226 self.tk.call(('image', 'create', imgtype, name,) + options)
3227 self.name = name
3228 def __str__(self): return self.name
3229 def __del__(self):
3230 if self.name:
3231 try:
3232 self.tk.call('image', 'delete', self.name)
3233 except TclError:
3234 # May happen if the root was destroyed
3235 pass
3236 def __setitem__(self, key, value):
3237 self.tk.call(self.name, 'configure', '-'+key, value)
3238 def __getitem__(self, key):
3239 return self.tk.call(self.name, 'configure', '-'+key)
3240 def configure(self, **kw):
3241 """Configure the image."""
3242 res = ()
3243 for k, v in _cnfmerge(kw).items():
3244 if v is not None:
3245 if k[-1] == '_': k = k[:-1]
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003246 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003247 v = self._register(v)
3248 res = res + ('-'+k, v)
3249 self.tk.call((self.name, 'config') + res)
3250 config = configure
3251 def height(self):
3252 """Return the height of the image."""
3253 return getint(
3254 self.tk.call('image', 'height', self.name))
3255 def type(self):
3256 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3257 return self.tk.call('image', 'type', self.name)
3258 def width(self):
3259 """Return the width of the image."""
3260 return getint(
3261 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003262
3263class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003264 """Widget which can display colored images in GIF, PPM/PGM format."""
3265 def __init__(self, name=None, cnf={}, master=None, **kw):
3266 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003267
Fredrik Lundh06d28152000-08-09 18:03:12 +00003268 Valid resource names: data, format, file, gamma, height, palette,
3269 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003270 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003271 def blank(self):
3272 """Display a transparent image."""
3273 self.tk.call(self.name, 'blank')
3274 def cget(self, option):
3275 """Return the value of OPTION."""
3276 return self.tk.call(self.name, 'cget', '-' + option)
3277 # XXX config
3278 def __getitem__(self, key):
3279 return self.tk.call(self.name, 'cget', '-' + key)
3280 # XXX copy -from, -to, ...?
3281 def copy(self):
3282 """Return a new PhotoImage with the same image as this widget."""
3283 destImage = PhotoImage()
3284 self.tk.call(destImage, 'copy', self.name)
3285 return destImage
3286 def zoom(self,x,y=''):
3287 """Return a new PhotoImage with the same image as this widget
3288 but zoom it with X and Y."""
3289 destImage = PhotoImage()
3290 if y=='': y=x
3291 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3292 return destImage
3293 def subsample(self,x,y=''):
3294 """Return a new PhotoImage based on the same image as this widget
3295 but use only every Xth or Yth pixel."""
3296 destImage = PhotoImage()
3297 if y=='': y=x
3298 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3299 return destImage
3300 def get(self, x, y):
3301 """Return the color (red, green, blue) of the pixel at X,Y."""
3302 return self.tk.call(self.name, 'get', x, y)
3303 def put(self, data, to=None):
3304 """Put row formated colors to image starting from
3305 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3306 args = (self.name, 'put', data)
3307 if to:
3308 if to[0] == '-to':
3309 to = to[1:]
3310 args = args + ('-to',) + tuple(to)
3311 self.tk.call(args)
3312 # XXX read
3313 def write(self, filename, format=None, from_coords=None):
3314 """Write image to file FILENAME in FORMAT starting from
3315 position FROM_COORDS."""
3316 args = (self.name, 'write', filename)
3317 if format:
3318 args = args + ('-format', format)
3319 if from_coords:
3320 args = args + ('-from',) + tuple(from_coords)
3321 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003322
3323class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003324 """Widget which can display a bitmap."""
3325 def __init__(self, name=None, cnf={}, master=None, **kw):
3326 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003327
Fredrik Lundh06d28152000-08-09 18:03:12 +00003328 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003329 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003330
3331def image_names(): return _default_root.tk.call('image', 'names')
3332def image_types(): return _default_root.tk.call('image', 'types')
3333
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003334
3335class Spinbox(Widget):
3336 """spinbox widget."""
3337 def __init__(self, master=None, cnf={}, **kw):
3338 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003339
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003340 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003341
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003342 activebackground, background, borderwidth,
3343 cursor, exportselection, font, foreground,
3344 highlightbackground, highlightcolor,
3345 highlightthickness, insertbackground,
3346 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003347 insertontime, insertwidth, justify, relief,
3348 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003349 selectbackground, selectborderwidth
3350 selectforeground, takefocus, textvariable
3351 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003352
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003353 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003354
3355 buttonbackground, buttoncursor,
3356 buttondownrelief, buttonuprelief,
3357 command, disabledbackground,
3358 disabledforeground, format, from,
3359 invalidcommand, increment,
3360 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003361 validate, validatecommand values,
3362 width, wrap,
3363 """
3364 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003365
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003366 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003367 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3368 rectangle which encloses the character given by index.
3369
3370 The first two elements of the list give the x and y
3371 coordinates of the upper-left corner of the screen
3372 area covered by the character (in pixels relative
3373 to the widget) and the last two elements give the
3374 width and height of the character, in pixels. The
3375 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003376 visible area of the window.
3377 """
3378 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003379
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003380 def delete(self, first, last=None):
3381 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003382
3383 First is the index of the first character to delete,
3384 and last is the index of the character just after
3385 the last one to delete. If last isn't specified it
3386 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003387 deleted. This command returns an empty string.
3388 """
3389 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003390
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003391 def get(self):
3392 """Returns the spinbox's string"""
3393 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003394
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003395 def icursor(self, index):
3396 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003397
3398 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003399 the character given by index. Returns an empty string
3400 """
3401 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003402
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003403 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003404 """Returns the name of the widget at position x, y
3405
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003406 Return value is one of: none, buttondown, buttonup, entry
3407 """
3408 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003409
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003410 def index(self, index):
3411 """Returns the numerical index corresponding to index
3412 """
3413 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003414
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003415 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003416 """Insert string s at index
3417
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003418 Returns an empty string.
3419 """
3420 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003421
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003422 def invoke(self, element):
3423 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003424
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003425 The element could be buttondown or buttonup
3426 triggering the action associated with it.
3427 """
3428 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003429
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003430 def scan(self, *args):
3431 """Internal function."""
3432 return self._getints(
3433 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003434
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003435 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003436 """Records x and the current view in the spinbox window;
3437
3438 used in conjunction with later scan dragto commands.
3439 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003440 press in the widget. It returns an empty string.
3441 """
3442 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003443
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003444 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003445 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003446 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003447
3448 It then adjusts the view left or right by 10 times the
3449 difference in x-coordinates. This command is typically
3450 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003451 produce the effect of dragging the spinbox at high speed
3452 through the window. The return value is an empty string.
3453 """
3454 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003455
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003456 def selection(self, *args):
3457 """Internal function."""
3458 return self._getints(
3459 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003460
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003461 def selection_adjust(self, index):
3462 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003463 given by index,
3464
3465 Then adjust that end of the selection to be at index
3466 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003467 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003468 select to commands. If the selection isn't currently in
3469 the spinbox, then a new selection is created to include
3470 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003471 anchor point, inclusive. Returns an empty string.
3472 """
3473 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003474
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003475 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003476 """Clear the selection
3477
3478 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003479 command has no effect. Returns an empty string.
3480 """
3481 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003482
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003483 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003484 """Sets or gets the currently selected element.
3485
3486 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003487 displayed depressed
3488 """
3489 return self.selection("element", element)
3490
3491###########################################################################
3492
3493class LabelFrame(Widget):
3494 """labelframe widget."""
3495 def __init__(self, master=None, cnf={}, **kw):
3496 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003497
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003498 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003499
3500 borderwidth, cursor, font, foreground,
3501 highlightbackground, highlightcolor,
3502 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003503 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003504
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003505 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003506
3507 background, class, colormap, container,
3508 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003509 visual, width
3510 """
3511 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003512
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003513########################################################################
3514
3515class PanedWindow(Widget):
3516 """panedwindow widget."""
3517 def __init__(self, master=None, cnf={}, **kw):
3518 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003519
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003520 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003522 background, borderwidth, cursor, height,
3523 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003524
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003525 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003526
3527 handlepad, handlesize, opaqueresize,
3528 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003529 sashwidth, showhandle,
3530 """
3531 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3532
3533 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003534 """Add a child widget to the panedwindow in a new pane.
3535
3536 The child argument is the name of the child widget
3537 followed by pairs of arguments that specify how to
3538 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003539 accepted by the configure subcommand.
3540 """
3541 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003542
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003543 def remove(self, child):
3544 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003545
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003546 All geometry management options for child will be forgotten.
3547 """
3548 self.tk.call(self._w, 'forget', child)
3549 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003550
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003551 def identify(self, x, y):
3552 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003553
3554 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003555 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003556 handle, and a word indicating whether it is over a sash
3557 or a handle, such as {0 sash} or {2 handle}. If the point
3558 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003559 an empty list.
3560 """
3561 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003562
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003563 def proxy(self, *args):
3564 """Internal function."""
3565 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003566 self.tk.call((self._w, 'proxy') + args)) or ()
3567
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003568 def proxy_coord(self):
3569 """Return the x and y pair of the most recent proxy location
3570 """
3571 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003572
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003573 def proxy_forget(self):
3574 """Remove the proxy from the display.
3575 """
3576 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003577
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003578 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003579 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003580 """
3581 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003582
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003583 def sash(self, *args):
3584 """Internal function."""
3585 return self._getints(
3586 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003587
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003588 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003589 """Return the current x and y pair for the sash given by index.
3590
3591 Index must be an integer between 0 and 1 less than the
3592 number of panes in the panedwindow. The coordinates given are
3593 those of the top left corner of the region containing the sash.
3594 pathName sash dragto index x y This command computes the
3595 difference between the given coordinates and the coordinates
3596 given to the last sash coord command for the given sash. It then
3597 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003598 empty string.
3599 """
3600 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003601
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003602 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003603 """Records x and y for the sash given by index;
3604
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003605 Used in conjunction with later dragto commands to move the sash.
3606 """
3607 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003608
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003609 def sash_place(self, index, x, y):
3610 """Place the sash given by index at the given coordinates
3611 """
3612 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003613
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003614 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003615 """Query a management option for window.
3616
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003617 Option may be any value allowed by the paneconfigure subcommand
3618 """
3619 return self.tk.call(
3620 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003621
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003622 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003623 """Query or modify the management options for window.
3624
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003625 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003626 of the available options for pathName. If option is
3627 specified with no value, then the command returns a list
3628 describing the one named option (this list will be identical
3629 to the corresponding sublist of the value returned if no
3630 option is specified). If one or more option-value pairs are
3631 specified, then the command modifies the given widget
3632 option(s) to have the given value(s); in this case the
3633 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003634 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003635
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003636 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003637 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003638 should be the name of a window already managed by pathName.
3639 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003640 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003641 should be the name of a window already managed by pathName.
3642 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003643 Specify a height for the window. The height will be the
3644 outer dimension of the window including its border, if
3645 any. If size is an empty string, or if -height is not
3646 specified, then the height requested internally by the
3647 window will be used initially; the height may later be
3648 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003649 Size may be any value accepted by Tk_GetPixels.
3650 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003651 Specifies that the size of the window cannot be made
3652 less than n. This constraint only affects the size of
3653 the widget in the paned dimension -- the x dimension
3654 for horizontal panedwindows, the y dimension for
3655 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003656 Tk_GetPixels.
3657 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003658 Specifies a non-negative value indicating how much
3659 extra space to leave on each side of the window in
3660 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003661 accepted by Tk_GetPixels.
3662 pady n
3663 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003664 extra space to leave on each side of the window in
3665 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003666 accepted by Tk_GetPixels.
3667 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003668 If a window's pane is larger than the requested
3669 dimensions of the window, this option may be used
3670 to position (or stretch) the window within its pane.
3671 Style is a string that contains zero or more of the
3672 characters n, s, e or w. The string can optionally
3673 contains spaces or commas, but they are ignored. Each
3674 letter refers to a side (north, south, east, or west)
3675 that the window will "stick" to. If both n and s
3676 (or e and w) are specified, the window will be
3677 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003678 its cavity.
3679 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003680 Specify a width for the window. The width will be
3681 the outer dimension of the window including its
3682 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003683 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003684 internally by the window will be used initially; the
3685 width may later be adjusted by the movement of sashes
3686 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003687 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003688
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003689 """
3690 if cnf is None and not kw:
3691 cnf = {}
3692 for x in self.tk.split(
3693 self.tk.call(self._w,
3694 'paneconfigure', tagOrId)):
3695 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3696 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00003697 if isinstance(cnf, str) and not kw:
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003698 x = self.tk.split(self.tk.call(
3699 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3700 return (x[0][1:],) + x[1:]
3701 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3702 self._options(cnf, kw))
3703 paneconfig = paneconfigure
3704
3705 def panes(self):
3706 """Returns an ordered list of the child panes."""
3707 return self.tk.call(self._w, 'panes')
3708
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003709######################################################################
3710# Extensions:
3711
3712class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003713 def __init__(self, master=None, cnf={}, **kw):
3714 Widget.__init__(self, master, 'studbutton', cnf, kw)
3715 self.bind('<Any-Enter>', self.tkButtonEnter)
3716 self.bind('<Any-Leave>', self.tkButtonLeave)
3717 self.bind('<1>', self.tkButtonDown)
3718 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003719
3720class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003721 def __init__(self, master=None, cnf={}, **kw):
3722 Widget.__init__(self, master, 'tributton', cnf, kw)
3723 self.bind('<Any-Enter>', self.tkButtonEnter)
3724 self.bind('<Any-Leave>', self.tkButtonLeave)
3725 self.bind('<1>', self.tkButtonDown)
3726 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3727 self['fg'] = self['bg']
3728 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003729
Guido van Rossumc417ef81996-08-21 23:38:59 +00003730######################################################################
3731# Test:
3732
3733def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003734 root = Tk()
3735 text = "This is Tcl/Tk version %s" % TclVersion
3736 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003737 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003738 label = Label(root, text=text)
3739 label.pack()
3740 test = Button(root, text="Click me!",
3741 command=lambda root=root: root.test.configure(
3742 text="[%s]" % root.test['text']))
3743 test.pack()
3744 root.test = test
3745 quit = Button(root, text="QUIT", command=root.destroy)
3746 quit.pack()
3747 # The following three commands are needed so the window pops
3748 # up on top on Windows...
3749 root.iconify()
3750 root.update()
3751 root.deiconify()
3752 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003753
3754if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003755 _test()