blob: 33b5ed01743e1996f3c37f795a28909c39b50630 [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."""
Collin Winterce36ad82007-08-30 01:19:48 +0000161 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)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000258 if isinstance(value, str):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000259 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:
Christian Heimesff737952007-11-27 10:40:20 +00001084 func = func.__func__
Fredrik Lundh06d28152000-08-09 18:03:12 +00001085 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:
Collin Winterce36ad82007-08-30 01:19:48 +00001404 raise SystemExit(msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001405 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:
Collin Winterce36ad82007-08-30 01:19:48 +00001655 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
1656 % (_tkinter.TK_VERSION, tk_version))
Martin v. Löwis54895972003-05-24 11:37:15 +00001657 # Under unknown circumstances, tcl_version gets coerced to float
1658 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001659 if tcl_version != _tkinter.TCL_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001660 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1661 % (_tkinter.TCL_VERSION, tcl_version))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001662 if TkVersion < 4.0:
Collin Winterce36ad82007-08-30 01:19:48 +00001663 raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
1664 % str(TkVersion))
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001665 # Create and register the tkerror and exit commands
1666 # We need to inline parts of _register here, _ register
1667 # would register differently-named commands.
1668 if self._tclCommands is None:
1669 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001670 self.tk.createcommand('tkerror', _tkerror)
1671 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001672 self._tclCommands.append('tkerror')
1673 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001674 if _support_default_root and not _default_root:
1675 _default_root = self
1676 self.protocol("WM_DELETE_WINDOW", self.destroy)
1677 def destroy(self):
1678 """Destroy this and all descendants widgets. This will
1679 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001680 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001681 self.tk.call('destroy', self._w)
1682 Misc.destroy(self)
1683 global _default_root
1684 if _support_default_root and _default_root is self:
1685 _default_root = None
1686 def readprofile(self, baseName, className):
1687 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001688 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1689 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001690 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001691 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001692 else: home = os.curdir
1693 class_tcl = os.path.join(home, '.%s.tcl' % className)
1694 class_py = os.path.join(home, '.%s.py' % className)
1695 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1696 base_py = os.path.join(home, '.%s.py' % baseName)
1697 dir = {'self': self}
Georg Brandl7cae87c2006-09-06 06:51:57 +00001698 exec('from Tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001699 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001700 self.tk.call('source', class_tcl)
1701 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001702 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001703 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001704 self.tk.call('source', base_tcl)
1705 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001706 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001707 def report_callback_exception(self, exc, val, tb):
1708 """Internal function. It reports exception on sys.stderr."""
1709 import traceback, sys
1710 sys.stderr.write("Exception in Tkinter callback\n")
1711 sys.last_type = exc
1712 sys.last_value = val
1713 sys.last_traceback = tb
1714 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001715 def __getattr__(self, attr):
1716 "Delegate attribute access to the interpreter object"
1717 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001718
Guido van Rossum368e06b1997-11-07 20:38:49 +00001719# Ideally, the classes Pack, Place and Grid disappear, the
1720# pack/place/grid methods are defined on the Widget class, and
1721# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1722# ...), with pack(), place() and grid() being short for
1723# pack_configure(), place_configure() and grid_columnconfigure(), and
1724# forget() being short for pack_forget(). As a practical matter, I'm
1725# afraid that there is too much code out there that may be using the
1726# Pack, Place or Grid class, so I leave them intact -- but only as
1727# backwards compatibility features. Also note that those methods that
1728# take a master as argument (e.g. pack_propagate) have been moved to
1729# the Misc class (which now incorporates all methods common between
1730# toplevel and interior widgets). Again, for compatibility, these are
1731# copied into the Pack, Place or Grid class.
1732
David Aschere2b4b322004-02-18 05:59:53 +00001733
1734def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1735 return Tk(screenName, baseName, className, useTk)
1736
Guido van Rossum18468821994-06-20 07:49:28 +00001737class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001738 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001739
Fredrik Lundh06d28152000-08-09 18:03:12 +00001740 Base class to use the methods pack_* in every widget."""
1741 def pack_configure(self, cnf={}, **kw):
1742 """Pack a widget in the parent widget. Use as options:
1743 after=widget - pack it after you have packed widget
1744 anchor=NSEW (or subset) - position widget according to
1745 given direction
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001746 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001747 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001748 fill=NONE or X or Y or BOTH - fill widget if widget grows
1749 in=master - use master to contain this widget
1750 ipadx=amount - add internal padding in x direction
1751 ipady=amount - add internal padding in y direction
1752 padx=amount - add padding in x direction
1753 pady=amount - add padding in y direction
1754 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1755 """
1756 self.tk.call(
1757 ('pack', 'configure', self._w)
1758 + self._options(cnf, kw))
1759 pack = configure = config = pack_configure
1760 def pack_forget(self):
1761 """Unmap this widget and do not use it for the packing order."""
1762 self.tk.call('pack', 'forget', self._w)
1763 forget = pack_forget
1764 def pack_info(self):
1765 """Return information about the packing options
1766 for this widget."""
1767 words = self.tk.splitlist(
1768 self.tk.call('pack', 'info', self._w))
1769 dict = {}
1770 for i in range(0, len(words), 2):
1771 key = words[i][1:]
1772 value = words[i+1]
1773 if value[:1] == '.':
1774 value = self._nametowidget(value)
1775 dict[key] = value
1776 return dict
1777 info = pack_info
1778 propagate = pack_propagate = Misc.pack_propagate
1779 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001780
1781class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001782 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001783
Fredrik Lundh06d28152000-08-09 18:03:12 +00001784 Base class to use the methods place_* in every widget."""
1785 def place_configure(self, cnf={}, **kw):
1786 """Place a widget in the parent widget. Use as options:
1787 in=master - master relative to which the widget is placed.
1788 x=amount - locate anchor of this widget at position x of master
1789 y=amount - locate anchor of this widget at position y of master
1790 relx=amount - locate anchor of this widget between 0.0 and 1.0
1791 relative to width of master (1.0 is right edge)
1792 rely=amount - locate anchor of this widget between 0.0 and 1.0
1793 relative to height of master (1.0 is bottom edge)
1794 anchor=NSEW (or subset) - position anchor according to given direction
1795 width=amount - width of this widget in pixel
1796 height=amount - height of this widget in pixel
1797 relwidth=amount - width of this widget between 0.0 and 1.0
1798 relative to width of master (1.0 is the same width
1799 as the master)
1800 relheight=amount - height of this widget between 0.0 and 1.0
1801 relative to height of master (1.0 is the same
1802 height as the master)
1803 bordermode="inside" or "outside" - whether to take border width of master widget
1804 into account
1805 """
1806 for k in ['in_']:
Guido van Rossume014a132006-08-19 16:53:45 +00001807 if k in kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001808 kw[k[:-1]] = kw[k]
1809 del kw[k]
1810 self.tk.call(
1811 ('place', 'configure', self._w)
1812 + self._options(cnf, kw))
1813 place = configure = config = place_configure
1814 def place_forget(self):
1815 """Unmap this widget."""
1816 self.tk.call('place', 'forget', self._w)
1817 forget = place_forget
1818 def place_info(self):
1819 """Return information about the placing options
1820 for this widget."""
1821 words = self.tk.splitlist(
1822 self.tk.call('place', 'info', self._w))
1823 dict = {}
1824 for i in range(0, len(words), 2):
1825 key = words[i][1:]
1826 value = words[i+1]
1827 if value[:1] == '.':
1828 value = self._nametowidget(value)
1829 dict[key] = value
1830 return dict
1831 info = place_info
1832 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001833
Guido van Rossum37dcab11996-05-16 16:00:19 +00001834class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001835 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001836
Fredrik Lundh06d28152000-08-09 18:03:12 +00001837 Base class to use the methods grid_* in every widget."""
1838 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1839 def grid_configure(self, cnf={}, **kw):
1840 """Position a widget in the parent widget in a grid. Use as options:
1841 column=number - use cell identified with given column (starting with 0)
1842 columnspan=number - this widget will span several columns
1843 in=master - use master to contain this widget
1844 ipadx=amount - add internal padding in x direction
1845 ipady=amount - add internal padding in y direction
1846 padx=amount - add padding in x direction
1847 pady=amount - add padding in y direction
1848 row=number - use cell identified with given row (starting with 0)
1849 rowspan=number - this widget will span several rows
1850 sticky=NSEW - if cell is larger on which sides will this
1851 widget stick to the cell boundary
1852 """
1853 self.tk.call(
1854 ('grid', 'configure', self._w)
1855 + self._options(cnf, kw))
1856 grid = configure = config = grid_configure
1857 bbox = grid_bbox = Misc.grid_bbox
1858 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1859 def grid_forget(self):
1860 """Unmap this widget."""
1861 self.tk.call('grid', 'forget', self._w)
1862 forget = grid_forget
1863 def grid_remove(self):
1864 """Unmap this widget but remember the grid options."""
1865 self.tk.call('grid', 'remove', self._w)
1866 def grid_info(self):
1867 """Return information about the options
1868 for positioning this widget in a grid."""
1869 words = self.tk.splitlist(
1870 self.tk.call('grid', 'info', self._w))
1871 dict = {}
1872 for i in range(0, len(words), 2):
1873 key = words[i][1:]
1874 value = words[i+1]
1875 if value[:1] == '.':
1876 value = self._nametowidget(value)
1877 dict[key] = value
1878 return dict
1879 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001880 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001881 propagate = grid_propagate = Misc.grid_propagate
1882 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1883 size = grid_size = Misc.grid_size
1884 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001885
Guido van Rossum368e06b1997-11-07 20:38:49 +00001886class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001887 """Internal class."""
1888 def _setup(self, master, cnf):
1889 """Internal function. Sets up information about children."""
1890 if _support_default_root:
1891 global _default_root
1892 if not master:
1893 if not _default_root:
1894 _default_root = Tk()
1895 master = _default_root
1896 self.master = master
1897 self.tk = master.tk
1898 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00001899 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001900 name = cnf['name']
1901 del cnf['name']
1902 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001903 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001904 self._name = name
1905 if master._w=='.':
1906 self._w = '.' + name
1907 else:
1908 self._w = master._w + '.' + name
1909 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00001910 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001911 self.master.children[self._name].destroy()
1912 self.master.children[self._name] = self
1913 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1914 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1915 and appropriate options."""
1916 if kw:
1917 cnf = _cnfmerge((cnf, kw))
1918 self.widgetName = widgetName
1919 BaseWidget._setup(self, master, cnf)
1920 classes = []
1921 for k in cnf.keys():
Guido van Rossum13257902007-06-07 23:15:56 +00001922 if isinstance(k, type):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001923 classes.append((k, cnf[k]))
1924 del cnf[k]
1925 self.tk.call(
1926 (widgetName, self._w) + extra + self._options(cnf))
1927 for k, v in classes:
1928 k.configure(self, v)
1929 def destroy(self):
1930 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00001931 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001932 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00001933 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001934 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001935 Misc.destroy(self)
1936 def _do(self, name, args=()):
1937 # XXX Obsolete -- better use self.tk.call directly!
1938 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001939
Guido van Rossum368e06b1997-11-07 20:38:49 +00001940class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001941 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001942
Fredrik Lundh06d28152000-08-09 18:03:12 +00001943 Base class for a widget which can be positioned with the geometry managers
1944 Pack, Place or Grid."""
1945 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001946
1947class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001948 """Toplevel widget, e.g. for dialogs."""
1949 def __init__(self, master=None, cnf={}, **kw):
1950 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001951
Fredrik Lundh06d28152000-08-09 18:03:12 +00001952 Valid resource names: background, bd, bg, borderwidth, class,
1953 colormap, container, cursor, height, highlightbackground,
1954 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1955 use, visual, width."""
1956 if kw:
1957 cnf = _cnfmerge((cnf, kw))
1958 extra = ()
1959 for wmkey in ['screen', 'class_', 'class', 'visual',
1960 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00001961 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001962 val = cnf[wmkey]
1963 # TBD: a hack needed because some keys
1964 # are not valid as keyword arguments
1965 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1966 else: opt = '-'+wmkey
1967 extra = extra + (opt, val)
1968 del cnf[wmkey]
1969 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
1970 root = self._root()
1971 self.iconname(root.iconname())
1972 self.title(root.title())
1973 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00001974
1975class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001976 """Button widget."""
1977 def __init__(self, master=None, cnf={}, **kw):
1978 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00001979
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001980 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001981
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001982 activebackground, activeforeground, anchor,
1983 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001984 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001985 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001986 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001987 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00001988 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001989 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00001990
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001991 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00001992
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001993 command, compound, default, height,
1994 overrelief, state, width
1995 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001996 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001997
Fredrik Lundh06d28152000-08-09 18:03:12 +00001998 def tkButtonEnter(self, *dummy):
1999 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002000
Fredrik Lundh06d28152000-08-09 18:03:12 +00002001 def tkButtonLeave(self, *dummy):
2002 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002003
Fredrik Lundh06d28152000-08-09 18:03:12 +00002004 def tkButtonDown(self, *dummy):
2005 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002006
Fredrik Lundh06d28152000-08-09 18:03:12 +00002007 def tkButtonUp(self, *dummy):
2008 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002009
Fredrik Lundh06d28152000-08-09 18:03:12 +00002010 def tkButtonInvoke(self, *dummy):
2011 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002012
Fredrik Lundh06d28152000-08-09 18:03:12 +00002013 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002014 """Flash the button.
2015
2016 This is accomplished by redisplaying
2017 the button several times, alternating between active and
2018 normal colors. At the end of the flash the button is left
2019 in the same normal/active state as when the command was
2020 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002021 disabled.
2022 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002023 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002024
Fredrik Lundh06d28152000-08-09 18:03:12 +00002025 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002026 """Invoke the command associated with the button.
2027
2028 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002029 or an empty string if there is no command associated with
2030 the button. This command is ignored if the button's state
2031 is disabled.
2032 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002033 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002034
2035# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002036# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00002037def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002038 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00002039def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002040 s = 'insert'
2041 for a in args:
2042 if a: s = s + (' ' + a)
2043 return s
Guido van Rossum18468821994-06-20 07:49:28 +00002044def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002045 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00002046def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002047 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00002048def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002049 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002050 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002051 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002052 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002053
2054class Canvas(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002055 """Canvas widget to display graphical elements like lines or text."""
2056 def __init__(self, master=None, cnf={}, **kw):
2057 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002058
Fredrik Lundh06d28152000-08-09 18:03:12 +00002059 Valid resource names: background, bd, bg, borderwidth, closeenough,
2060 confine, cursor, height, highlightbackground, highlightcolor,
2061 highlightthickness, insertbackground, insertborderwidth,
2062 insertofftime, insertontime, insertwidth, offset, relief,
2063 scrollregion, selectbackground, selectborderwidth, selectforeground,
2064 state, takefocus, width, xscrollcommand, xscrollincrement,
2065 yscrollcommand, yscrollincrement."""
2066 Widget.__init__(self, master, 'canvas', cnf, kw)
2067 def addtag(self, *args):
2068 """Internal function."""
2069 self.tk.call((self._w, 'addtag') + args)
2070 def addtag_above(self, newtag, tagOrId):
2071 """Add tag NEWTAG to all items above TAGORID."""
2072 self.addtag(newtag, 'above', tagOrId)
2073 def addtag_all(self, newtag):
2074 """Add tag NEWTAG to all items."""
2075 self.addtag(newtag, 'all')
2076 def addtag_below(self, newtag, tagOrId):
2077 """Add tag NEWTAG to all items below TAGORID."""
2078 self.addtag(newtag, 'below', tagOrId)
2079 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2080 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2081 If several match take the top-most.
2082 All items closer than HALO are considered overlapping (all are
2083 closests). If START is specified the next below this tag is taken."""
2084 self.addtag(newtag, 'closest', x, y, halo, start)
2085 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2086 """Add tag NEWTAG to all items in the rectangle defined
2087 by X1,Y1,X2,Y2."""
2088 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2089 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2090 """Add tag NEWTAG to all items which overlap the rectangle
2091 defined by X1,Y1,X2,Y2."""
2092 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2093 def addtag_withtag(self, newtag, tagOrId):
2094 """Add tag NEWTAG to all items with TAGORID."""
2095 self.addtag(newtag, 'withtag', tagOrId)
2096 def bbox(self, *args):
2097 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2098 which encloses all items with tags specified as arguments."""
2099 return self._getints(
2100 self.tk.call((self._w, 'bbox') + args)) or None
2101 def tag_unbind(self, tagOrId, sequence, funcid=None):
2102 """Unbind for all items with TAGORID for event SEQUENCE the
2103 function identified with FUNCID."""
2104 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2105 if funcid:
2106 self.deletecommand(funcid)
2107 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2108 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002109
Fredrik Lundh06d28152000-08-09 18:03:12 +00002110 An additional boolean parameter ADD specifies whether FUNC will be
2111 called additionally to the other bound function or whether it will
2112 replace the previous function. See bind for the return value."""
2113 return self._bind((self._w, 'bind', tagOrId),
2114 sequence, func, add)
2115 def canvasx(self, screenx, gridspacing=None):
2116 """Return the canvas x coordinate of pixel position SCREENX rounded
2117 to nearest multiple of GRIDSPACING units."""
2118 return getdouble(self.tk.call(
2119 self._w, 'canvasx', screenx, gridspacing))
2120 def canvasy(self, screeny, gridspacing=None):
2121 """Return the canvas y coordinate of pixel position SCREENY rounded
2122 to nearest multiple of GRIDSPACING units."""
2123 return getdouble(self.tk.call(
2124 self._w, 'canvasy', screeny, gridspacing))
2125 def coords(self, *args):
2126 """Return a list of coordinates for the item given in ARGS."""
2127 # XXX Should use _flatten on args
2128 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002129 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002130 self.tk.call((self._w, 'coords') + args)))
2131 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2132 """Internal function."""
2133 args = _flatten(args)
2134 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002135 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002136 args = args[:-1]
2137 else:
2138 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002139 return getint(self.tk.call(
2140 self._w, 'create', itemType,
2141 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002142 def create_arc(self, *args, **kw):
2143 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2144 return self._create('arc', args, kw)
2145 def create_bitmap(self, *args, **kw):
2146 """Create bitmap with coordinates x1,y1."""
2147 return self._create('bitmap', args, kw)
2148 def create_image(self, *args, **kw):
2149 """Create image item with coordinates x1,y1."""
2150 return self._create('image', args, kw)
2151 def create_line(self, *args, **kw):
2152 """Create line with coordinates x1,y1,...,xn,yn."""
2153 return self._create('line', args, kw)
2154 def create_oval(self, *args, **kw):
2155 """Create oval with coordinates x1,y1,x2,y2."""
2156 return self._create('oval', args, kw)
2157 def create_polygon(self, *args, **kw):
2158 """Create polygon with coordinates x1,y1,...,xn,yn."""
2159 return self._create('polygon', args, kw)
2160 def create_rectangle(self, *args, **kw):
2161 """Create rectangle with coordinates x1,y1,x2,y2."""
2162 return self._create('rectangle', args, kw)
2163 def create_text(self, *args, **kw):
2164 """Create text with coordinates x1,y1."""
2165 return self._create('text', args, kw)
2166 def create_window(self, *args, **kw):
2167 """Create window with coordinates x1,y1,x2,y2."""
2168 return self._create('window', args, kw)
2169 def dchars(self, *args):
2170 """Delete characters of text items identified by tag or id in ARGS (possibly
2171 several times) from FIRST to LAST character (including)."""
2172 self.tk.call((self._w, 'dchars') + args)
2173 def delete(self, *args):
2174 """Delete items identified by all tag or ids contained in ARGS."""
2175 self.tk.call((self._w, 'delete') + args)
2176 def dtag(self, *args):
2177 """Delete tag or id given as last arguments in ARGS from items
2178 identified by first argument in ARGS."""
2179 self.tk.call((self._w, 'dtag') + args)
2180 def find(self, *args):
2181 """Internal function."""
2182 return self._getints(
2183 self.tk.call((self._w, 'find') + args)) or ()
2184 def find_above(self, tagOrId):
2185 """Return items above TAGORID."""
2186 return self.find('above', tagOrId)
2187 def find_all(self):
2188 """Return all items."""
2189 return self.find('all')
2190 def find_below(self, tagOrId):
2191 """Return all items below TAGORID."""
2192 return self.find('below', tagOrId)
2193 def find_closest(self, x, y, halo=None, start=None):
2194 """Return item which is closest to pixel at X, Y.
2195 If several match take the top-most.
2196 All items closer than HALO are considered overlapping (all are
2197 closests). If START is specified the next below this tag is taken."""
2198 return self.find('closest', x, y, halo, start)
2199 def find_enclosed(self, x1, y1, x2, y2):
2200 """Return all items in rectangle defined
2201 by X1,Y1,X2,Y2."""
2202 return self.find('enclosed', x1, y1, x2, y2)
2203 def find_overlapping(self, x1, y1, x2, y2):
2204 """Return all items which overlap the rectangle
2205 defined by X1,Y1,X2,Y2."""
2206 return self.find('overlapping', x1, y1, x2, y2)
2207 def find_withtag(self, tagOrId):
2208 """Return all items with TAGORID."""
2209 return self.find('withtag', tagOrId)
2210 def focus(self, *args):
2211 """Set focus to the first item specified in ARGS."""
2212 return self.tk.call((self._w, 'focus') + args)
2213 def gettags(self, *args):
2214 """Return tags associated with the first item specified in ARGS."""
2215 return self.tk.splitlist(
2216 self.tk.call((self._w, 'gettags') + args))
2217 def icursor(self, *args):
2218 """Set cursor at position POS in the item identified by TAGORID.
2219 In ARGS TAGORID must be first."""
2220 self.tk.call((self._w, 'icursor') + args)
2221 def index(self, *args):
2222 """Return position of cursor as integer in item specified in ARGS."""
2223 return getint(self.tk.call((self._w, 'index') + args))
2224 def insert(self, *args):
2225 """Insert TEXT in item TAGORID at position POS. ARGS must
2226 be TAGORID POS TEXT."""
2227 self.tk.call((self._w, 'insert') + args)
2228 def itemcget(self, tagOrId, option):
2229 """Return the resource value for an OPTION for item TAGORID."""
2230 return self.tk.call(
2231 (self._w, 'itemcget') + (tagOrId, '-'+option))
2232 def itemconfigure(self, tagOrId, cnf=None, **kw):
2233 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002234
Fredrik Lundh06d28152000-08-09 18:03:12 +00002235 The values for resources are specified as keyword
2236 arguments. To get an overview about
2237 the allowed keyword arguments call the method without arguments.
2238 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002239 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002240 itemconfig = itemconfigure
2241 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2242 # so the preferred name for them is tag_lower, tag_raise
2243 # (similar to tag_bind, and similar to the Text widget);
2244 # unfortunately can't delete the old ones yet (maybe in 1.6)
2245 def tag_lower(self, *args):
2246 """Lower an item TAGORID given in ARGS
2247 (optional below another item)."""
2248 self.tk.call((self._w, 'lower') + args)
2249 lower = tag_lower
2250 def move(self, *args):
2251 """Move an item TAGORID given in ARGS."""
2252 self.tk.call((self._w, 'move') + args)
2253 def postscript(self, cnf={}, **kw):
2254 """Print the contents of the canvas to a postscript
2255 file. Valid options: colormap, colormode, file, fontmap,
2256 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2257 rotate, witdh, x, y."""
2258 return self.tk.call((self._w, 'postscript') +
2259 self._options(cnf, kw))
2260 def tag_raise(self, *args):
2261 """Raise an item TAGORID given in ARGS
2262 (optional above another item)."""
2263 self.tk.call((self._w, 'raise') + args)
2264 lift = tkraise = tag_raise
2265 def scale(self, *args):
2266 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2267 self.tk.call((self._w, 'scale') + args)
2268 def scan_mark(self, x, y):
2269 """Remember the current X, Y coordinates."""
2270 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002271 def scan_dragto(self, x, y, gain=10):
2272 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002273 difference between X and Y and the coordinates given in
2274 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002275 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002276 def select_adjust(self, tagOrId, index):
2277 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2278 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2279 def select_clear(self):
2280 """Clear the selection if it is in this widget."""
2281 self.tk.call(self._w, 'select', 'clear')
2282 def select_from(self, tagOrId, index):
2283 """Set the fixed end of a selection in item TAGORID to INDEX."""
2284 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2285 def select_item(self):
2286 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002287 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002288 def select_to(self, tagOrId, index):
2289 """Set the variable end of a selection in item TAGORID to INDEX."""
2290 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2291 def type(self, tagOrId):
2292 """Return the type of the item TAGORID."""
2293 return self.tk.call(self._w, 'type', tagOrId) or None
2294 def xview(self, *args):
2295 """Query and change horizontal position of the view."""
2296 if not args:
2297 return self._getdoubles(self.tk.call(self._w, 'xview'))
2298 self.tk.call((self._w, 'xview') + args)
2299 def xview_moveto(self, fraction):
2300 """Adjusts the view in the window so that FRACTION of the
2301 total width of the canvas is off-screen to the left."""
2302 self.tk.call(self._w, 'xview', 'moveto', fraction)
2303 def xview_scroll(self, number, what):
2304 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2305 self.tk.call(self._w, 'xview', 'scroll', number, what)
2306 def yview(self, *args):
2307 """Query and change vertical position of the view."""
2308 if not args:
2309 return self._getdoubles(self.tk.call(self._w, 'yview'))
2310 self.tk.call((self._w, 'yview') + args)
2311 def yview_moveto(self, fraction):
2312 """Adjusts the view in the window so that FRACTION of the
2313 total height of the canvas is off-screen to the top."""
2314 self.tk.call(self._w, 'yview', 'moveto', fraction)
2315 def yview_scroll(self, number, what):
2316 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2317 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002318
2319class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002320 """Checkbutton widget which is either in on- or off-state."""
2321 def __init__(self, master=None, cnf={}, **kw):
2322 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002323
Fredrik Lundh06d28152000-08-09 18:03:12 +00002324 Valid resource names: activebackground, activeforeground, anchor,
2325 background, bd, bg, bitmap, borderwidth, command, cursor,
2326 disabledforeground, fg, font, foreground, height,
2327 highlightbackground, highlightcolor, highlightthickness, image,
2328 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2329 selectcolor, selectimage, state, takefocus, text, textvariable,
2330 underline, variable, width, wraplength."""
2331 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2332 def deselect(self):
2333 """Put the button in off-state."""
2334 self.tk.call(self._w, 'deselect')
2335 def flash(self):
2336 """Flash the button."""
2337 self.tk.call(self._w, 'flash')
2338 def invoke(self):
2339 """Toggle the button and invoke a command if given as resource."""
2340 return self.tk.call(self._w, 'invoke')
2341 def select(self):
2342 """Put the button in on-state."""
2343 self.tk.call(self._w, 'select')
2344 def toggle(self):
2345 """Toggle the button."""
2346 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002347
2348class Entry(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002349 """Entry widget which allows to display simple text."""
2350 def __init__(self, master=None, cnf={}, **kw):
2351 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002352
Fredrik Lundh06d28152000-08-09 18:03:12 +00002353 Valid resource names: background, bd, bg, borderwidth, cursor,
2354 exportselection, fg, font, foreground, highlightbackground,
2355 highlightcolor, highlightthickness, insertbackground,
2356 insertborderwidth, insertofftime, insertontime, insertwidth,
2357 invalidcommand, invcmd, justify, relief, selectbackground,
2358 selectborderwidth, selectforeground, show, state, takefocus,
2359 textvariable, validate, validatecommand, vcmd, width,
2360 xscrollcommand."""
2361 Widget.__init__(self, master, 'entry', cnf, kw)
2362 def delete(self, first, last=None):
2363 """Delete text from FIRST to LAST (not included)."""
2364 self.tk.call(self._w, 'delete', first, last)
2365 def get(self):
2366 """Return the text."""
2367 return self.tk.call(self._w, 'get')
2368 def icursor(self, index):
2369 """Insert cursor at INDEX."""
2370 self.tk.call(self._w, 'icursor', index)
2371 def index(self, index):
2372 """Return position of cursor."""
2373 return getint(self.tk.call(
2374 self._w, 'index', index))
2375 def insert(self, index, string):
2376 """Insert STRING at INDEX."""
2377 self.tk.call(self._w, 'insert', index, string)
2378 def scan_mark(self, x):
2379 """Remember the current X, Y coordinates."""
2380 self.tk.call(self._w, 'scan', 'mark', x)
2381 def scan_dragto(self, x):
2382 """Adjust the view of the canvas to 10 times the
2383 difference between X and Y and the coordinates given in
2384 scan_mark."""
2385 self.tk.call(self._w, 'scan', 'dragto', x)
2386 def selection_adjust(self, index):
2387 """Adjust the end of the selection near the cursor to INDEX."""
2388 self.tk.call(self._w, 'selection', 'adjust', index)
2389 select_adjust = selection_adjust
2390 def selection_clear(self):
2391 """Clear the selection if it is in this widget."""
2392 self.tk.call(self._w, 'selection', 'clear')
2393 select_clear = selection_clear
2394 def selection_from(self, index):
2395 """Set the fixed end of a selection to INDEX."""
2396 self.tk.call(self._w, 'selection', 'from', index)
2397 select_from = selection_from
2398 def selection_present(self):
2399 """Return whether the widget has the selection."""
2400 return self.tk.getboolean(
2401 self.tk.call(self._w, 'selection', 'present'))
2402 select_present = selection_present
2403 def selection_range(self, start, end):
2404 """Set the selection from START to END (not included)."""
2405 self.tk.call(self._w, 'selection', 'range', start, end)
2406 select_range = selection_range
2407 def selection_to(self, index):
2408 """Set the variable end of a selection to INDEX."""
2409 self.tk.call(self._w, 'selection', 'to', index)
2410 select_to = selection_to
2411 def xview(self, index):
2412 """Query and change horizontal position of the view."""
2413 self.tk.call(self._w, 'xview', index)
2414 def xview_moveto(self, fraction):
2415 """Adjust the view in the window so that FRACTION of the
2416 total width of the entry is off-screen to the left."""
2417 self.tk.call(self._w, 'xview', 'moveto', fraction)
2418 def xview_scroll(self, number, what):
2419 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2420 self.tk.call(self._w, 'xview', 'scroll', number, what)
Guido van Rossum18468821994-06-20 07:49:28 +00002421
2422class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002423 """Frame widget which may contain other widgets and can have a 3D border."""
2424 def __init__(self, master=None, cnf={}, **kw):
2425 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002426
Fredrik Lundh06d28152000-08-09 18:03:12 +00002427 Valid resource names: background, bd, bg, borderwidth, class,
2428 colormap, container, cursor, height, highlightbackground,
2429 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2430 cnf = _cnfmerge((cnf, kw))
2431 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002432 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002433 extra = ('-class', cnf['class_'])
2434 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002435 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002436 extra = ('-class', cnf['class'])
2437 del cnf['class']
2438 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002439
2440class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002441 """Label widget which can display text and bitmaps."""
2442 def __init__(self, master=None, cnf={}, **kw):
2443 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002444
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002445 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002446
2447 activebackground, activeforeground, anchor,
2448 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002449 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002450 highlightbackground, highlightcolor,
2451 highlightthickness, image, justify,
2452 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002453 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002454
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002455 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002456
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002457 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002458
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002459 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002460 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002461
Guido van Rossum18468821994-06-20 07:49:28 +00002462class Listbox(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002463 """Listbox widget which can display a list of strings."""
2464 def __init__(self, master=None, cnf={}, **kw):
2465 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002466
Fredrik Lundh06d28152000-08-09 18:03:12 +00002467 Valid resource names: background, bd, bg, borderwidth, cursor,
2468 exportselection, fg, font, foreground, height, highlightbackground,
2469 highlightcolor, highlightthickness, relief, selectbackground,
2470 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2471 width, xscrollcommand, yscrollcommand, listvariable."""
2472 Widget.__init__(self, master, 'listbox', cnf, kw)
2473 def activate(self, index):
2474 """Activate item identified by INDEX."""
2475 self.tk.call(self._w, 'activate', index)
2476 def bbox(self, *args):
2477 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2478 which encloses the item identified by index in ARGS."""
2479 return self._getints(
2480 self.tk.call((self._w, 'bbox') + args)) or None
2481 def curselection(self):
2482 """Return list of indices of currently selected item."""
2483 # XXX Ought to apply self._getints()...
2484 return self.tk.splitlist(self.tk.call(
2485 self._w, 'curselection'))
2486 def delete(self, first, last=None):
2487 """Delete items from FIRST to LAST (not included)."""
2488 self.tk.call(self._w, 'delete', first, last)
2489 def get(self, first, last=None):
2490 """Get list of items from FIRST to LAST (not included)."""
2491 if last:
2492 return self.tk.splitlist(self.tk.call(
2493 self._w, 'get', first, last))
2494 else:
2495 return self.tk.call(self._w, 'get', first)
2496 def index(self, index):
2497 """Return index of item identified with INDEX."""
2498 i = self.tk.call(self._w, 'index', index)
2499 if i == 'none': return None
2500 return getint(i)
2501 def insert(self, index, *elements):
2502 """Insert ELEMENTS at INDEX."""
2503 self.tk.call((self._w, 'insert', index) + elements)
2504 def nearest(self, y):
2505 """Get index of item which is nearest to y coordinate Y."""
2506 return getint(self.tk.call(
2507 self._w, 'nearest', y))
2508 def scan_mark(self, x, y):
2509 """Remember the current X, Y coordinates."""
2510 self.tk.call(self._w, 'scan', 'mark', x, y)
2511 def scan_dragto(self, x, y):
2512 """Adjust the view of the listbox to 10 times the
2513 difference between X and Y and the coordinates given in
2514 scan_mark."""
2515 self.tk.call(self._w, 'scan', 'dragto', x, y)
2516 def see(self, index):
2517 """Scroll such that INDEX is visible."""
2518 self.tk.call(self._w, 'see', index)
2519 def selection_anchor(self, index):
2520 """Set the fixed end oft the selection to INDEX."""
2521 self.tk.call(self._w, 'selection', 'anchor', index)
2522 select_anchor = selection_anchor
2523 def selection_clear(self, first, last=None):
2524 """Clear the selection from FIRST to LAST (not included)."""
2525 self.tk.call(self._w,
2526 'selection', 'clear', first, last)
2527 select_clear = selection_clear
2528 def selection_includes(self, index):
2529 """Return 1 if INDEX is part of the selection."""
2530 return self.tk.getboolean(self.tk.call(
2531 self._w, 'selection', 'includes', index))
2532 select_includes = selection_includes
2533 def selection_set(self, first, last=None):
2534 """Set the selection from FIRST to LAST (not included) without
2535 changing the currently selected elements."""
2536 self.tk.call(self._w, 'selection', 'set', first, last)
2537 select_set = selection_set
2538 def size(self):
2539 """Return the number of elements in the listbox."""
2540 return getint(self.tk.call(self._w, 'size'))
2541 def xview(self, *what):
2542 """Query and change horizontal position of the view."""
2543 if not what:
2544 return self._getdoubles(self.tk.call(self._w, 'xview'))
2545 self.tk.call((self._w, 'xview') + what)
2546 def xview_moveto(self, fraction):
2547 """Adjust the view in the window so that FRACTION of the
2548 total width of the entry is off-screen to the left."""
2549 self.tk.call(self._w, 'xview', 'moveto', fraction)
2550 def xview_scroll(self, number, what):
2551 """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2552 self.tk.call(self._w, 'xview', 'scroll', number, what)
2553 def yview(self, *what):
2554 """Query and change vertical position of the view."""
2555 if not what:
2556 return self._getdoubles(self.tk.call(self._w, 'yview'))
2557 self.tk.call((self._w, 'yview') + what)
2558 def yview_moveto(self, fraction):
2559 """Adjust the view in the window so that FRACTION of the
2560 total width of the entry is off-screen to the top."""
2561 self.tk.call(self._w, 'yview', 'moveto', fraction)
2562 def yview_scroll(self, number, what):
2563 """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
2564 self.tk.call(self._w, 'yview', 'scroll', number, what)
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002565 def itemcget(self, index, option):
2566 """Return the resource value for an ITEM and an OPTION."""
2567 return self.tk.call(
2568 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002569 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002570 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002571
2572 The values for resources are specified as keyword arguments.
2573 To get an overview about the allowed keyword arguments
2574 call the method without arguments.
2575 Valid resource names: background, bg, foreground, fg,
2576 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002577 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002578 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002579
2580class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002581 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2582 def __init__(self, master=None, cnf={}, **kw):
2583 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002584
Fredrik Lundh06d28152000-08-09 18:03:12 +00002585 Valid resource names: activebackground, activeborderwidth,
2586 activeforeground, background, bd, bg, borderwidth, cursor,
2587 disabledforeground, fg, font, foreground, postcommand, relief,
2588 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2589 Widget.__init__(self, master, 'menu', cnf, kw)
2590 def tk_bindForTraversal(self):
2591 pass # obsolete since Tk 4.0
2592 def tk_mbPost(self):
2593 self.tk.call('tk_mbPost', self._w)
2594 def tk_mbUnpost(self):
2595 self.tk.call('tk_mbUnpost')
2596 def tk_traverseToMenu(self, char):
2597 self.tk.call('tk_traverseToMenu', self._w, char)
2598 def tk_traverseWithinMenu(self, char):
2599 self.tk.call('tk_traverseWithinMenu', self._w, char)
2600 def tk_getMenuButtons(self):
2601 return self.tk.call('tk_getMenuButtons', self._w)
2602 def tk_nextMenu(self, count):
2603 self.tk.call('tk_nextMenu', count)
2604 def tk_nextMenuEntry(self, count):
2605 self.tk.call('tk_nextMenuEntry', count)
2606 def tk_invokeMenu(self):
2607 self.tk.call('tk_invokeMenu', self._w)
2608 def tk_firstMenu(self):
2609 self.tk.call('tk_firstMenu', self._w)
2610 def tk_mbButtonDown(self):
2611 self.tk.call('tk_mbButtonDown', self._w)
2612 def tk_popup(self, x, y, entry=""):
2613 """Post the menu at position X,Y with entry ENTRY."""
2614 self.tk.call('tk_popup', self._w, x, y, entry)
2615 def activate(self, index):
2616 """Activate entry at INDEX."""
2617 self.tk.call(self._w, 'activate', index)
2618 def add(self, itemType, cnf={}, **kw):
2619 """Internal function."""
2620 self.tk.call((self._w, 'add', itemType) +
2621 self._options(cnf, kw))
2622 def add_cascade(self, cnf={}, **kw):
2623 """Add hierarchical menu item."""
2624 self.add('cascade', cnf or kw)
2625 def add_checkbutton(self, cnf={}, **kw):
2626 """Add checkbutton menu item."""
2627 self.add('checkbutton', cnf or kw)
2628 def add_command(self, cnf={}, **kw):
2629 """Add command menu item."""
2630 self.add('command', cnf or kw)
2631 def add_radiobutton(self, cnf={}, **kw):
2632 """Addd radio menu item."""
2633 self.add('radiobutton', cnf or kw)
2634 def add_separator(self, cnf={}, **kw):
2635 """Add separator."""
2636 self.add('separator', cnf or kw)
2637 def insert(self, index, itemType, cnf={}, **kw):
2638 """Internal function."""
2639 self.tk.call((self._w, 'insert', index, itemType) +
2640 self._options(cnf, kw))
2641 def insert_cascade(self, index, cnf={}, **kw):
2642 """Add hierarchical menu item at INDEX."""
2643 self.insert(index, 'cascade', cnf or kw)
2644 def insert_checkbutton(self, index, cnf={}, **kw):
2645 """Add checkbutton menu item at INDEX."""
2646 self.insert(index, 'checkbutton', cnf or kw)
2647 def insert_command(self, index, cnf={}, **kw):
2648 """Add command menu item at INDEX."""
2649 self.insert(index, 'command', cnf or kw)
2650 def insert_radiobutton(self, index, cnf={}, **kw):
2651 """Addd radio menu item at INDEX."""
2652 self.insert(index, 'radiobutton', cnf or kw)
2653 def insert_separator(self, index, cnf={}, **kw):
2654 """Add separator at INDEX."""
2655 self.insert(index, 'separator', cnf or kw)
2656 def delete(self, index1, index2=None):
2657 """Delete menu items between INDEX1 and INDEX2 (not included)."""
2658 self.tk.call(self._w, 'delete', index1, index2)
2659 def entrycget(self, index, option):
2660 """Return the resource value of an menu item for OPTION at INDEX."""
2661 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2662 def entryconfigure(self, index, cnf=None, **kw):
2663 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002664 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002665 entryconfig = entryconfigure
2666 def index(self, index):
2667 """Return the index of a menu item identified by INDEX."""
2668 i = self.tk.call(self._w, 'index', index)
2669 if i == 'none': return None
2670 return getint(i)
2671 def invoke(self, index):
2672 """Invoke a menu item identified by INDEX and execute
2673 the associated command."""
2674 return self.tk.call(self._w, 'invoke', index)
2675 def post(self, x, y):
2676 """Display a menu at position X,Y."""
2677 self.tk.call(self._w, 'post', x, y)
2678 def type(self, index):
2679 """Return the type of the menu item at INDEX."""
2680 return self.tk.call(self._w, 'type', index)
2681 def unpost(self):
2682 """Unmap a menu."""
2683 self.tk.call(self._w, 'unpost')
2684 def yposition(self, index):
2685 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2686 return getint(self.tk.call(
2687 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002688
2689class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002690 """Menubutton widget, obsolete since Tk8.0."""
2691 def __init__(self, master=None, cnf={}, **kw):
2692 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002693
2694class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002695 """Message widget to display multiline text. Obsolete since Label does it too."""
2696 def __init__(self, master=None, cnf={}, **kw):
2697 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002698
2699class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002700 """Radiobutton widget which shows only one of several buttons in on-state."""
2701 def __init__(self, master=None, cnf={}, **kw):
2702 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002703
Fredrik Lundh06d28152000-08-09 18:03:12 +00002704 Valid resource names: activebackground, activeforeground, anchor,
2705 background, bd, bg, bitmap, borderwidth, command, cursor,
2706 disabledforeground, fg, font, foreground, height,
2707 highlightbackground, highlightcolor, highlightthickness, image,
2708 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2709 state, takefocus, text, textvariable, underline, value, variable,
2710 width, wraplength."""
2711 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2712 def deselect(self):
2713 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002714
Fredrik Lundh06d28152000-08-09 18:03:12 +00002715 self.tk.call(self._w, 'deselect')
2716 def flash(self):
2717 """Flash the button."""
2718 self.tk.call(self._w, 'flash')
2719 def invoke(self):
2720 """Toggle the button and invoke a command if given as resource."""
2721 return self.tk.call(self._w, 'invoke')
2722 def select(self):
2723 """Put the button in on-state."""
2724 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002725
2726class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002727 """Scale widget which can display a numerical scale."""
2728 def __init__(self, master=None, cnf={}, **kw):
2729 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002730
Fredrik Lundh06d28152000-08-09 18:03:12 +00002731 Valid resource names: activebackground, background, bigincrement, bd,
2732 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2733 highlightbackground, highlightcolor, highlightthickness, label,
2734 length, orient, relief, repeatdelay, repeatinterval, resolution,
2735 showvalue, sliderlength, sliderrelief, state, takefocus,
2736 tickinterval, to, troughcolor, variable, width."""
2737 Widget.__init__(self, master, 'scale', cnf, kw)
2738 def get(self):
2739 """Get the current value as integer or float."""
2740 value = self.tk.call(self._w, 'get')
2741 try:
2742 return getint(value)
2743 except ValueError:
2744 return getdouble(value)
2745 def set(self, value):
2746 """Set the value to VALUE."""
2747 self.tk.call(self._w, 'set', value)
2748 def coords(self, value=None):
2749 """Return a tuple (X,Y) of the point along the centerline of the
2750 trough that corresponds to VALUE or the current value if None is
2751 given."""
2752
2753 return self._getints(self.tk.call(self._w, 'coords', value))
2754 def identify(self, x, y):
2755 """Return where the point X,Y lies. Valid return values are "slider",
2756 "though1" and "though2"."""
2757 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002758
2759class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002760 """Scrollbar widget which displays a slider at a certain position."""
2761 def __init__(self, master=None, cnf={}, **kw):
2762 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002763
Fredrik Lundh06d28152000-08-09 18:03:12 +00002764 Valid resource names: activebackground, activerelief,
2765 background, bd, bg, borderwidth, command, cursor,
2766 elementborderwidth, highlightbackground,
2767 highlightcolor, highlightthickness, jump, orient,
2768 relief, repeatdelay, repeatinterval, takefocus,
2769 troughcolor, width."""
2770 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2771 def activate(self, index):
2772 """Display the element at INDEX with activebackground and activerelief.
2773 INDEX can be "arrow1","slider" or "arrow2"."""
2774 self.tk.call(self._w, 'activate', index)
2775 def delta(self, deltax, deltay):
2776 """Return the fractional change of the scrollbar setting if it
2777 would be moved by DELTAX or DELTAY pixels."""
2778 return getdouble(
2779 self.tk.call(self._w, 'delta', deltax, deltay))
2780 def fraction(self, x, y):
2781 """Return the fractional value which corresponds to a slider
2782 position of X,Y."""
2783 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2784 def identify(self, x, y):
2785 """Return the element under position X,Y as one of
2786 "arrow1","slider","arrow2" or ""."""
2787 return self.tk.call(self._w, 'identify', x, y)
2788 def get(self):
2789 """Return the current fractional values (upper and lower end)
2790 of the slider position."""
2791 return self._getdoubles(self.tk.call(self._w, 'get'))
2792 def set(self, *args):
2793 """Set the fractional values of the slider position (upper and
2794 lower ends as value between 0 and 1)."""
2795 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002796
2797
2798
Guido van Rossum18468821994-06-20 07:49:28 +00002799class Text(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002800 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002801 def __init__(self, master=None, cnf={}, **kw):
2802 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002803
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002804 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002805
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002806 background, borderwidth, cursor,
2807 exportselection, font, foreground,
2808 highlightbackground, highlightcolor,
2809 highlightthickness, insertbackground,
2810 insertborderwidth, insertofftime,
2811 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002812 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002813 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002814 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002815 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002816
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002817 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002818
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002819 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002820 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002821 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002822
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002823 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002824 Widget.__init__(self, master, 'text', cnf, kw)
2825 def bbox(self, *args):
2826 """Return a tuple of (x,y,width,height) which gives the bounding
2827 box of the visible part of the character at the index in ARGS."""
2828 return self._getints(
2829 self.tk.call((self._w, 'bbox') + args)) or None
2830 def tk_textSelectTo(self, index):
2831 self.tk.call('tk_textSelectTo', self._w, index)
2832 def tk_textBackspace(self):
2833 self.tk.call('tk_textBackspace', self._w)
2834 def tk_textIndexCloser(self, a, b, c):
2835 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2836 def tk_textResetAnchor(self, index):
2837 self.tk.call('tk_textResetAnchor', self._w, index)
2838 def compare(self, index1, op, index2):
2839 """Return whether between index INDEX1 and index INDEX2 the
2840 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2841 return self.tk.getboolean(self.tk.call(
2842 self._w, 'compare', index1, op, index2))
2843 def debug(self, boolean=None):
2844 """Turn on the internal consistency checks of the B-Tree inside the text
2845 widget according to BOOLEAN."""
2846 return self.tk.getboolean(self.tk.call(
2847 self._w, 'debug', boolean))
2848 def delete(self, index1, index2=None):
2849 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2850 self.tk.call(self._w, 'delete', index1, index2)
2851 def dlineinfo(self, index):
2852 """Return tuple (x,y,width,height,baseline) giving the bounding box
2853 and baseline position of the visible part of the line containing
2854 the character at INDEX."""
2855 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002856 def dump(self, index1, index2=None, command=None, **kw):
2857 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002858
Guido van Rossum256705b2002-04-23 13:29:43 +00002859 The type of contents returned in filtered based on the keyword
2860 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2861 given and true, then the corresponding items are returned. The result
2862 is a list of triples of the form (key, value, index). If none of the
2863 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002864
Guido van Rossum256705b2002-04-23 13:29:43 +00002865 If the 'command' argument is given, it is called once for each element
2866 of the list of triples, with the values of each triple serving as the
2867 arguments to the function. In this case the list is not returned."""
2868 args = []
2869 func_name = None
2870 result = None
2871 if not command:
2872 # Never call the dump command without the -command flag, since the
2873 # output could involve Tcl quoting and would be a pain to parse
2874 # right. Instead just set the command to build a list of triples
2875 # as if we had done the parsing.
2876 result = []
2877 def append_triple(key, value, index, result=result):
2878 result.append((key, value, index))
2879 command = append_triple
2880 try:
2881 if not isinstance(command, str):
2882 func_name = command = self._register(command)
2883 args += ["-command", command]
2884 for key in kw:
2885 if kw[key]: args.append("-" + key)
2886 args.append(index1)
2887 if index2:
2888 args.append(index2)
2889 self.tk.call(self._w, "dump", *args)
2890 return result
2891 finally:
2892 if func_name:
2893 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002894
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002895 ## new in tk8.4
2896 def edit(self, *args):
2897 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002898
2899 This method controls the undo mechanism and
2900 the modified flag. The exact behavior of the
2901 command depends on the option argument that
2902 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002903 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002904
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002905 edit_modified, edit_redo, edit_reset, edit_separator
2906 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002907
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002908 """
2909 return self._getints(
2910 self.tk.call((self._w, 'edit') + args)) or ()
2911
2912 def edit_modified(self, arg=None):
2913 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002914
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002915 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002916 flag of the widget. The insert, delete, edit undo and
2917 edit redo commands or the user can set or clear the
2918 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002919 modified flag of the widget to arg.
2920 """
2921 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002922
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002923 def edit_redo(self):
2924 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002925
2926 When the undo option is true, reapplies the last
2927 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002928 then. Generates an error when the redo stack is empty.
2929 Does nothing when the undo option is false.
2930 """
2931 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002932
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002933 def edit_reset(self):
2934 """Clears the undo and redo stacks
2935 """
2936 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002937
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002938 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002939 """Inserts a separator (boundary) on the undo stack.
2940
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002941 Does nothing when the undo option is false
2942 """
2943 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002944
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002945 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002946 """Undoes the last edit action
2947
2948 If the undo option is true. An edit action is defined
2949 as all the insert and delete commands that are recorded
2950 on the undo stack in between two separators. Generates
2951 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002952 when the undo option is false
2953 """
2954 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002955
Fredrik Lundh06d28152000-08-09 18:03:12 +00002956 def get(self, index1, index2=None):
2957 """Return the text from INDEX1 to INDEX2 (not included)."""
2958 return self.tk.call(self._w, 'get', index1, index2)
2959 # (Image commands are new in 8.0)
2960 def image_cget(self, index, option):
2961 """Return the value of OPTION of an embedded image at INDEX."""
2962 if option[:1] != "-":
2963 option = "-" + option
2964 if option[-1:] == "_":
2965 option = option[:-1]
2966 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002967 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002968 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002969 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002970 def image_create(self, index, cnf={}, **kw):
2971 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002972 return self.tk.call(
2973 self._w, "image", "create", index,
2974 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002975 def image_names(self):
2976 """Return all names of embedded images in this widget."""
2977 return self.tk.call(self._w, "image", "names")
2978 def index(self, index):
2979 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00002980 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002981 def insert(self, index, chars, *args):
2982 """Insert CHARS before the characters at INDEX. An additional
2983 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2984 self.tk.call((self._w, 'insert', index, chars) + args)
2985 def mark_gravity(self, markName, direction=None):
2986 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2987 Return the current value if None is given for DIRECTION."""
2988 return self.tk.call(
2989 (self._w, 'mark', 'gravity', markName, direction))
2990 def mark_names(self):
2991 """Return all mark names."""
2992 return self.tk.splitlist(self.tk.call(
2993 self._w, 'mark', 'names'))
2994 def mark_set(self, markName, index):
2995 """Set mark MARKNAME before the character at INDEX."""
2996 self.tk.call(self._w, 'mark', 'set', markName, index)
2997 def mark_unset(self, *markNames):
2998 """Delete all marks in MARKNAMES."""
2999 self.tk.call((self._w, 'mark', 'unset') + markNames)
3000 def mark_next(self, index):
3001 """Return the name of the next mark after INDEX."""
3002 return self.tk.call(self._w, 'mark', 'next', index) or None
3003 def mark_previous(self, index):
3004 """Return the name of the previous mark before INDEX."""
3005 return self.tk.call(self._w, 'mark', 'previous', index) or None
3006 def scan_mark(self, x, y):
3007 """Remember the current X, Y coordinates."""
3008 self.tk.call(self._w, 'scan', 'mark', x, y)
3009 def scan_dragto(self, x, y):
3010 """Adjust the view of the text to 10 times the
3011 difference between X and Y and the coordinates given in
3012 scan_mark."""
3013 self.tk.call(self._w, 'scan', 'dragto', x, y)
3014 def search(self, pattern, index, stopindex=None,
3015 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003016 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003017 """Search PATTERN beginning from INDEX until STOPINDEX.
3018 Return the index of the first character of a match or an empty string."""
3019 args = [self._w, 'search']
3020 if forwards: args.append('-forwards')
3021 if backwards: args.append('-backwards')
3022 if exact: args.append('-exact')
3023 if regexp: args.append('-regexp')
3024 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003025 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003026 if count: args.append('-count'); args.append(count)
3027 if pattern[0] == '-': args.append('--')
3028 args.append(pattern)
3029 args.append(index)
3030 if stopindex: args.append(stopindex)
3031 return self.tk.call(tuple(args))
3032 def see(self, index):
3033 """Scroll such that the character at INDEX is visible."""
3034 self.tk.call(self._w, 'see', index)
3035 def tag_add(self, tagName, index1, *args):
3036 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3037 Additional pairs of indices may follow in ARGS."""
3038 self.tk.call(
3039 (self._w, 'tag', 'add', tagName, index1) + args)
3040 def tag_unbind(self, tagName, sequence, funcid=None):
3041 """Unbind for all characters with TAGNAME for event SEQUENCE the
3042 function identified with FUNCID."""
3043 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3044 if funcid:
3045 self.deletecommand(funcid)
3046 def tag_bind(self, tagName, sequence, func, add=None):
3047 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003048
Fredrik Lundh06d28152000-08-09 18:03:12 +00003049 An additional boolean parameter ADD specifies whether FUNC will be
3050 called additionally to the other bound function or whether it will
3051 replace the previous function. See bind for the return value."""
3052 return self._bind((self._w, 'tag', 'bind', tagName),
3053 sequence, func, add)
3054 def tag_cget(self, tagName, option):
3055 """Return the value of OPTION for tag TAGNAME."""
3056 if option[:1] != '-':
3057 option = '-' + option
3058 if option[-1:] == '_':
3059 option = option[:-1]
3060 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003061 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003062 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003063 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003064 tag_config = tag_configure
3065 def tag_delete(self, *tagNames):
3066 """Delete all tags in TAGNAMES."""
3067 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3068 def tag_lower(self, tagName, belowThis=None):
3069 """Change the priority of tag TAGNAME such that it is lower
3070 than the priority of BELOWTHIS."""
3071 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3072 def tag_names(self, index=None):
3073 """Return a list of all tag names."""
3074 return self.tk.splitlist(
3075 self.tk.call(self._w, 'tag', 'names', index))
3076 def tag_nextrange(self, tagName, index1, index2=None):
3077 """Return a list of start and end index for the first sequence of
3078 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3079 The text is searched forward from INDEX1."""
3080 return self.tk.splitlist(self.tk.call(
3081 self._w, 'tag', 'nextrange', tagName, index1, index2))
3082 def tag_prevrange(self, tagName, index1, index2=None):
3083 """Return a list of start and end index for the first sequence of
3084 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3085 The text is searched backwards from INDEX1."""
3086 return self.tk.splitlist(self.tk.call(
3087 self._w, 'tag', 'prevrange', tagName, index1, index2))
3088 def tag_raise(self, tagName, aboveThis=None):
3089 """Change the priority of tag TAGNAME such that it is higher
3090 than the priority of ABOVETHIS."""
3091 self.tk.call(
3092 self._w, 'tag', 'raise', tagName, aboveThis)
3093 def tag_ranges(self, tagName):
3094 """Return a list of ranges of text which have tag TAGNAME."""
3095 return self.tk.splitlist(self.tk.call(
3096 self._w, 'tag', 'ranges', tagName))
3097 def tag_remove(self, tagName, index1, index2=None):
3098 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3099 self.tk.call(
3100 self._w, 'tag', 'remove', tagName, index1, index2)
3101 def window_cget(self, index, option):
3102 """Return the value of OPTION of an embedded window at INDEX."""
3103 if option[:1] != '-':
3104 option = '-' + option
3105 if option[-1:] == '_':
3106 option = option[:-1]
3107 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003108 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003109 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003110 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003111 window_config = window_configure
3112 def window_create(self, index, cnf={}, **kw):
3113 """Create a window at INDEX."""
3114 self.tk.call(
3115 (self._w, 'window', 'create', index)
3116 + self._options(cnf, kw))
3117 def window_names(self):
3118 """Return all names of embedded windows in this widget."""
3119 return self.tk.splitlist(
3120 self.tk.call(self._w, 'window', 'names'))
3121 def xview(self, *what):
3122 """Query and change horizontal position of the view."""
3123 if not what:
3124 return self._getdoubles(self.tk.call(self._w, 'xview'))
3125 self.tk.call((self._w, 'xview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003126 def xview_moveto(self, fraction):
3127 """Adjusts the view in the window so that FRACTION of the
3128 total width of the canvas is off-screen to the left."""
3129 self.tk.call(self._w, 'xview', 'moveto', fraction)
3130 def xview_scroll(self, number, what):
3131 """Shift the x-view according to NUMBER which is measured
3132 in "units" or "pages" (WHAT)."""
3133 self.tk.call(self._w, 'xview', 'scroll', number, what)
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003134 def yview(self, *what):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003135 """Query and change vertical position of the view."""
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003136 if not what:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003137 return self._getdoubles(self.tk.call(self._w, 'yview'))
Fredrik Lundh8fffa202000-08-09 18:51:01 +00003138 self.tk.call((self._w, 'yview') + what)
Fredrik Lundh5bd2cd62000-08-09 18:29:51 +00003139 def yview_moveto(self, fraction):
3140 """Adjusts the view in the window so that FRACTION of the
3141 total height of the canvas is off-screen to the top."""
3142 self.tk.call(self._w, 'yview', 'moveto', fraction)
3143 def yview_scroll(self, number, what):
3144 """Shift the y-view according to NUMBER which is measured
3145 in "units" or "pages" (WHAT)."""
3146 self.tk.call(self._w, 'yview', 'scroll', number, what)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003147 def yview_pickplace(self, *what):
3148 """Obsolete function, use see."""
3149 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003150
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003151
Guido van Rossum28574b51996-10-21 15:16:51 +00003152class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003153 """Internal class. It wraps the command in the widget OptionMenu."""
3154 def __init__(self, var, value, callback=None):
3155 self.__value = value
3156 self.__var = var
3157 self.__callback = callback
3158 def __call__(self, *args):
3159 self.__var.set(self.__value)
3160 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003161 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003162
3163class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003164 """OptionMenu which allows the user to select a value from a menu."""
3165 def __init__(self, master, variable, value, *values, **kwargs):
3166 """Construct an optionmenu widget with the parent MASTER, with
3167 the resource textvariable set to VARIABLE, the initially selected
3168 value VALUE, the other menu values VALUES and an additional
3169 keyword argument command."""
3170 kw = {"borderwidth": 2, "textvariable": variable,
3171 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3172 "highlightthickness": 2}
3173 Widget.__init__(self, master, "menubutton", kw)
3174 self.widgetName = 'tk_optionMenu'
3175 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3176 self.menuname = menu._w
3177 # 'command' is the only supported keyword
3178 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003179 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003180 del kwargs['command']
3181 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003182 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003183 menu.add_command(label=value,
3184 command=_setit(variable, value, callback))
3185 for v in values:
3186 menu.add_command(label=v,
3187 command=_setit(variable, v, callback))
3188 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003189
Fredrik Lundh06d28152000-08-09 18:03:12 +00003190 def __getitem__(self, name):
3191 if name == 'menu':
3192 return self.__menu
3193 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003194
Fredrik Lundh06d28152000-08-09 18:03:12 +00003195 def destroy(self):
3196 """Destroy this widget and the associated menu."""
3197 Menubutton.destroy(self)
3198 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003199
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003200class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003201 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003202 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003203 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3204 self.name = None
3205 if not master:
3206 master = _default_root
3207 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003208 raise RuntimeError('Too early to create image')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003209 self.tk = master.tk
3210 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003211 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003212 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003213 # The following is needed for systems where id(x)
3214 # can return a negative number, such as Linux/m68k:
3215 if name[0] == '-': name = '_' + name[1:]
3216 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3217 elif kw: cnf = kw
3218 options = ()
3219 for k, v in cnf.items():
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003220 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003221 v = self._register(v)
3222 options = options + ('-'+k, v)
3223 self.tk.call(('image', 'create', imgtype, name,) + options)
3224 self.name = name
3225 def __str__(self): return self.name
3226 def __del__(self):
3227 if self.name:
3228 try:
3229 self.tk.call('image', 'delete', self.name)
3230 except TclError:
3231 # May happen if the root was destroyed
3232 pass
3233 def __setitem__(self, key, value):
3234 self.tk.call(self.name, 'configure', '-'+key, value)
3235 def __getitem__(self, key):
3236 return self.tk.call(self.name, 'configure', '-'+key)
3237 def configure(self, **kw):
3238 """Configure the image."""
3239 res = ()
3240 for k, v in _cnfmerge(kw).items():
3241 if v is not None:
3242 if k[-1] == '_': k = k[:-1]
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003243 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003244 v = self._register(v)
3245 res = res + ('-'+k, v)
3246 self.tk.call((self.name, 'config') + res)
3247 config = configure
3248 def height(self):
3249 """Return the height of the image."""
3250 return getint(
3251 self.tk.call('image', 'height', self.name))
3252 def type(self):
3253 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3254 return self.tk.call('image', 'type', self.name)
3255 def width(self):
3256 """Return the width of the image."""
3257 return getint(
3258 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003259
3260class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003261 """Widget which can display colored images in GIF, PPM/PGM format."""
3262 def __init__(self, name=None, cnf={}, master=None, **kw):
3263 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003264
Fredrik Lundh06d28152000-08-09 18:03:12 +00003265 Valid resource names: data, format, file, gamma, height, palette,
3266 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003267 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003268 def blank(self):
3269 """Display a transparent image."""
3270 self.tk.call(self.name, 'blank')
3271 def cget(self, option):
3272 """Return the value of OPTION."""
3273 return self.tk.call(self.name, 'cget', '-' + option)
3274 # XXX config
3275 def __getitem__(self, key):
3276 return self.tk.call(self.name, 'cget', '-' + key)
3277 # XXX copy -from, -to, ...?
3278 def copy(self):
3279 """Return a new PhotoImage with the same image as this widget."""
3280 destImage = PhotoImage()
3281 self.tk.call(destImage, 'copy', self.name)
3282 return destImage
3283 def zoom(self,x,y=''):
3284 """Return a new PhotoImage with the same image as this widget
3285 but zoom it with X and Y."""
3286 destImage = PhotoImage()
3287 if y=='': y=x
3288 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3289 return destImage
3290 def subsample(self,x,y=''):
3291 """Return a new PhotoImage based on the same image as this widget
3292 but use only every Xth or Yth pixel."""
3293 destImage = PhotoImage()
3294 if y=='': y=x
3295 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3296 return destImage
3297 def get(self, x, y):
3298 """Return the color (red, green, blue) of the pixel at X,Y."""
3299 return self.tk.call(self.name, 'get', x, y)
3300 def put(self, data, to=None):
3301 """Put row formated colors to image starting from
3302 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3303 args = (self.name, 'put', data)
3304 if to:
3305 if to[0] == '-to':
3306 to = to[1:]
3307 args = args + ('-to',) + tuple(to)
3308 self.tk.call(args)
3309 # XXX read
3310 def write(self, filename, format=None, from_coords=None):
3311 """Write image to file FILENAME in FORMAT starting from
3312 position FROM_COORDS."""
3313 args = (self.name, 'write', filename)
3314 if format:
3315 args = args + ('-format', format)
3316 if from_coords:
3317 args = args + ('-from',) + tuple(from_coords)
3318 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003319
3320class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003321 """Widget which can display a bitmap."""
3322 def __init__(self, name=None, cnf={}, master=None, **kw):
3323 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003324
Fredrik Lundh06d28152000-08-09 18:03:12 +00003325 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003326 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003327
3328def image_names(): return _default_root.tk.call('image', 'names')
3329def image_types(): return _default_root.tk.call('image', 'types')
3330
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003331
3332class Spinbox(Widget):
3333 """spinbox widget."""
3334 def __init__(self, master=None, cnf={}, **kw):
3335 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003336
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003337 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003338
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003339 activebackground, background, borderwidth,
3340 cursor, exportselection, font, foreground,
3341 highlightbackground, highlightcolor,
3342 highlightthickness, insertbackground,
3343 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003344 insertontime, insertwidth, justify, relief,
3345 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003346 selectbackground, selectborderwidth
3347 selectforeground, takefocus, textvariable
3348 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003349
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003350 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003351
3352 buttonbackground, buttoncursor,
3353 buttondownrelief, buttonuprelief,
3354 command, disabledbackground,
3355 disabledforeground, format, from,
3356 invalidcommand, increment,
3357 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003358 validate, validatecommand values,
3359 width, wrap,
3360 """
3361 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003362
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003363 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003364 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3365 rectangle which encloses the character given by index.
3366
3367 The first two elements of the list give the x and y
3368 coordinates of the upper-left corner of the screen
3369 area covered by the character (in pixels relative
3370 to the widget) and the last two elements give the
3371 width and height of the character, in pixels. The
3372 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003373 visible area of the window.
3374 """
3375 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003376
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003377 def delete(self, first, last=None):
3378 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003379
3380 First is the index of the first character to delete,
3381 and last is the index of the character just after
3382 the last one to delete. If last isn't specified it
3383 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003384 deleted. This command returns an empty string.
3385 """
3386 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003387
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003388 def get(self):
3389 """Returns the spinbox's string"""
3390 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003391
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003392 def icursor(self, index):
3393 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003394
3395 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003396 the character given by index. Returns an empty string
3397 """
3398 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003399
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003400 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003401 """Returns the name of the widget at position x, y
3402
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003403 Return value is one of: none, buttondown, buttonup, entry
3404 """
3405 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003406
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003407 def index(self, index):
3408 """Returns the numerical index corresponding to index
3409 """
3410 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003411
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003412 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003413 """Insert string s at index
3414
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003415 Returns an empty string.
3416 """
3417 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003418
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003419 def invoke(self, element):
3420 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003421
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003422 The element could be buttondown or buttonup
3423 triggering the action associated with it.
3424 """
3425 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003426
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003427 def scan(self, *args):
3428 """Internal function."""
3429 return self._getints(
3430 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003431
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003432 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003433 """Records x and the current view in the spinbox window;
3434
3435 used in conjunction with later scan dragto commands.
3436 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003437 press in the widget. It returns an empty string.
3438 """
3439 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003440
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003441 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003442 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003443 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003444
3445 It then adjusts the view left or right by 10 times the
3446 difference in x-coordinates. This command is typically
3447 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003448 produce the effect of dragging the spinbox at high speed
3449 through the window. The return value is an empty string.
3450 """
3451 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003452
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003453 def selection(self, *args):
3454 """Internal function."""
3455 return self._getints(
3456 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003457
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003458 def selection_adjust(self, index):
3459 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003460 given by index,
3461
3462 Then adjust that end of the selection to be at index
3463 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003464 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003465 select to commands. If the selection isn't currently in
3466 the spinbox, then a new selection is created to include
3467 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003468 anchor point, inclusive. Returns an empty string.
3469 """
3470 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003471
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003472 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003473 """Clear the selection
3474
3475 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003476 command has no effect. Returns an empty string.
3477 """
3478 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003479
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003480 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003481 """Sets or gets the currently selected element.
3482
3483 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003484 displayed depressed
3485 """
3486 return self.selection("element", element)
3487
3488###########################################################################
3489
3490class LabelFrame(Widget):
3491 """labelframe widget."""
3492 def __init__(self, master=None, cnf={}, **kw):
3493 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003494
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003495 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003496
3497 borderwidth, cursor, font, foreground,
3498 highlightbackground, highlightcolor,
3499 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003500 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003501
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003502 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003503
3504 background, class, colormap, container,
3505 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003506 visual, width
3507 """
3508 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003509
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003510########################################################################
3511
3512class PanedWindow(Widget):
3513 """panedwindow widget."""
3514 def __init__(self, master=None, cnf={}, **kw):
3515 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003516
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003517 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003518
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003519 background, borderwidth, cursor, height,
3520 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003522 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003523
3524 handlepad, handlesize, opaqueresize,
3525 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003526 sashwidth, showhandle,
3527 """
3528 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3529
3530 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003531 """Add a child widget to the panedwindow in a new pane.
3532
3533 The child argument is the name of the child widget
3534 followed by pairs of arguments that specify how to
3535 manage the windows. Options may have any of the values
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003536 accepted by the configure subcommand.
3537 """
3538 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003539
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003540 def remove(self, child):
3541 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003542
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003543 All geometry management options for child will be forgotten.
3544 """
3545 self.tk.call(self._w, 'forget', child)
3546 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003547
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003548 def identify(self, x, y):
3549 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003550
3551 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003552 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003553 handle, and a word indicating whether it is over a sash
3554 or a handle, such as {0 sash} or {2 handle}. If the point
3555 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003556 an empty list.
3557 """
3558 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003559
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003560 def proxy(self, *args):
3561 """Internal function."""
3562 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003563 self.tk.call((self._w, 'proxy') + args)) or ()
3564
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003565 def proxy_coord(self):
3566 """Return the x and y pair of the most recent proxy location
3567 """
3568 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003569
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003570 def proxy_forget(self):
3571 """Remove the proxy from the display.
3572 """
3573 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003574
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003575 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003576 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003577 """
3578 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003579
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003580 def sash(self, *args):
3581 """Internal function."""
3582 return self._getints(
3583 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003584
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003585 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003586 """Return the current x and y pair for the sash given by index.
3587
3588 Index must be an integer between 0 and 1 less than the
3589 number of panes in the panedwindow. The coordinates given are
3590 those of the top left corner of the region containing the sash.
3591 pathName sash dragto index x y This command computes the
3592 difference between the given coordinates and the coordinates
3593 given to the last sash coord command for the given sash. It then
3594 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003595 empty string.
3596 """
3597 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003598
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003599 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003600 """Records x and y for the sash given by index;
3601
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003602 Used in conjunction with later dragto commands to move the sash.
3603 """
3604 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003605
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003606 def sash_place(self, index, x, y):
3607 """Place the sash given by index at the given coordinates
3608 """
3609 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003610
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003611 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003612 """Query a management option for window.
3613
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003614 Option may be any value allowed by the paneconfigure subcommand
3615 """
3616 return self.tk.call(
3617 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003618
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003619 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003620 """Query or modify the management options for window.
3621
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003622 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003623 of the available options for pathName. If option is
3624 specified with no value, then the command returns a list
3625 describing the one named option (this list will be identical
3626 to the corresponding sublist of the value returned if no
3627 option is specified). If one or more option-value pairs are
3628 specified, then the command modifies the given widget
3629 option(s) to have the given value(s); in this case the
3630 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003631 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003632
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003633 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003634 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003635 should be the name of a window already managed by pathName.
3636 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003637 Insert the window before 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 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003640 Specify a height for the window. The height will be the
3641 outer dimension of the window including its border, if
3642 any. If size is an empty string, or if -height is not
3643 specified, then the height requested internally by the
3644 window will be used initially; the height may later be
3645 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003646 Size may be any value accepted by Tk_GetPixels.
3647 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003648 Specifies that the size of the window cannot be made
3649 less than n. This constraint only affects the size of
3650 the widget in the paned dimension -- the x dimension
3651 for horizontal panedwindows, the y dimension for
3652 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003653 Tk_GetPixels.
3654 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003655 Specifies a non-negative value indicating how much
3656 extra space to leave on each side of the window in
3657 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003658 accepted by Tk_GetPixels.
3659 pady n
3660 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003661 extra space to leave on each side of the window in
3662 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003663 accepted by Tk_GetPixels.
3664 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003665 If a window's pane is larger than the requested
3666 dimensions of the window, this option may be used
3667 to position (or stretch) the window within its pane.
3668 Style is a string that contains zero or more of the
3669 characters n, s, e or w. The string can optionally
3670 contains spaces or commas, but they are ignored. Each
3671 letter refers to a side (north, south, east, or west)
3672 that the window will "stick" to. If both n and s
3673 (or e and w) are specified, the window will be
3674 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003675 its cavity.
3676 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003677 Specify a width for the window. The width will be
3678 the outer dimension of the window including its
3679 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003680 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003681 internally by the window will be used initially; the
3682 width may later be adjusted by the movement of sashes
3683 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003684 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003685
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003686 """
3687 if cnf is None and not kw:
3688 cnf = {}
3689 for x in self.tk.split(
3690 self.tk.call(self._w,
3691 'paneconfigure', tagOrId)):
3692 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3693 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00003694 if isinstance(cnf, str) and not kw:
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003695 x = self.tk.split(self.tk.call(
3696 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3697 return (x[0][1:],) + x[1:]
3698 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3699 self._options(cnf, kw))
3700 paneconfig = paneconfigure
3701
3702 def panes(self):
3703 """Returns an ordered list of the child panes."""
3704 return self.tk.call(self._w, 'panes')
3705
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003706######################################################################
3707# Extensions:
3708
3709class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003710 def __init__(self, master=None, cnf={}, **kw):
3711 Widget.__init__(self, master, 'studbutton', cnf, kw)
3712 self.bind('<Any-Enter>', self.tkButtonEnter)
3713 self.bind('<Any-Leave>', self.tkButtonLeave)
3714 self.bind('<1>', self.tkButtonDown)
3715 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003716
3717class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003718 def __init__(self, master=None, cnf={}, **kw):
3719 Widget.__init__(self, master, 'tributton', cnf, kw)
3720 self.bind('<Any-Enter>', self.tkButtonEnter)
3721 self.bind('<Any-Leave>', self.tkButtonLeave)
3722 self.bind('<1>', self.tkButtonDown)
3723 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3724 self['fg'] = self['bg']
3725 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003726
Guido van Rossumc417ef81996-08-21 23:38:59 +00003727######################################################################
3728# Test:
3729
3730def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003731 root = Tk()
3732 text = "This is Tcl/Tk version %s" % TclVersion
3733 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003734 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003735 label = Label(root, text=text)
3736 label.pack()
3737 test = Button(root, text="Click me!",
3738 command=lambda root=root: root.test.configure(
3739 text="[%s]" % root.test['text']))
3740 test.pack()
3741 root.test = test
3742 quit = Button(root, text="QUIT", command=root.destroy)
3743 quit.pack()
3744 # The following three commands are needed so the window pops
3745 # up on top on Windows...
3746 root.iconify()
3747 root.update()
3748 root.deiconify()
3749 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003750
3751if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003752 _test()