blob: 61f2ff9ea72eb80a65096bb4ad8d669d772ec6ec [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):
Georg Brandl14fc4272008-05-17 18:39:55 +000021import tkinter
22from tkinter.constants import *
23tk = tkinter.Tk()
24frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
Guido van Rossum5917ecb2000-06-29 16:30:50 +000025frame.pack(fill=BOTH,expand=1)
Georg Brandl14fc4272008-05-17 18:39:55 +000026label = tkinter.Label(frame, text="Hello, World")
Guido van Rossum5917ecb2000-06-29 16:30:50 +000027label.pack(fill=X, expand=1)
Georg Brandl14fc4272008-05-17 18:39:55 +000028button = tkinter.Button(frame,text="Exit",command=tk.destroy)
Guido van Rossum5917ecb2000-06-29 16:30:50 +000029button.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":
Georg Brandl14fc4272008-05-17 18:39:55 +000037 # Attempt to configure Tcl/Tk without requiring PATH
38 from tkinter import _fix
Guido van Rossumf8d579c1999-01-04 18:06:45 +000039import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000040TclError = _tkinter.TclError
Georg Brandl14fc4272008-05-17 18:39:55 +000041from tkinter.constants import *
Guido van Rossum18468821994-06-20 07:49:28 +000042
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000043wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000044
Eric S. Raymondfc170b12001-02-09 11:51:27 +000045TkVersion = float(_tkinter.TK_VERSION)
46TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000047
Guido van Rossumd6615ab1997-08-05 02:35:01 +000048READABLE = _tkinter.READABLE
49WRITABLE = _tkinter.WRITABLE
50EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000051
Fredrik Lundh06d28152000-08-09 18:03:12 +000052
Guido van Rossum13257902007-06-07 23:15:56 +000053def _flatten(seq):
Fredrik Lundh06d28152000-08-09 18:03:12 +000054 """Internal function."""
55 res = ()
Guido van Rossum13257902007-06-07 23:15:56 +000056 for item in seq:
57 if isinstance(item, (tuple, list)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000058 res = res + _flatten(item)
59 elif item is not None:
60 res = res + (item,)
61 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000062
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000063try: _flatten = _tkinter._flatten
64except AttributeError: pass
65
Guido van Rossum2dcf5291994-07-06 09:23:20 +000066def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000067 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +000068 if isinstance(cnfs, dict):
Fredrik Lundh06d28152000-08-09 18:03:12 +000069 return cnfs
Guido van Rossum13257902007-06-07 23:15:56 +000070 elif isinstance(cnfs, (type(None), str)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000071 return cnfs
72 else:
73 cnf = {}
74 for c in _flatten(cnfs):
75 try:
76 cnf.update(c)
Guido van Rossumb940e112007-01-10 16:19:56 +000077 except (AttributeError, TypeError) as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000078 print("_cnfmerge: fallback due to:", msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +000079 for k, v in c.items():
80 cnf[k] = v
81 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000082
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000083try: _cnfmerge = _tkinter._cnfmerge
84except AttributeError: pass
85
Guido van Rossum2dcf5291994-07-06 09:23:20 +000086class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000087 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000088
Fredrik Lundh06d28152000-08-09 18:03:12 +000089 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +000090
Fredrik Lundh06d28152000-08-09 18:03:12 +000091 KeyPress, KeyRelease - for keyboard events
92 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
93 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
94 Colormap, Gravity, Reparent, Property, Destroy, Activate,
95 Deactivate - for window events.
96
97 If a callback function for one of these events is registered
98 using bind, bind_all, bind_class, or tag_bind, the callback is
99 called with an Event as first argument. It will have the
100 following attributes (in braces are the event types for which
101 the attribute is valid):
102
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000103 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000104 num - mouse button pressed (ButtonPress, ButtonRelease)
105 focus - whether the window has the focus (Enter, Leave)
106 height - height of the exposed window (Configure, Expose)
107 width - width of the exposed window (Configure, Expose)
108 keycode - keycode of the pressed key (KeyPress, KeyRelease)
109 state - state of the event as a number (ButtonPress, ButtonRelease,
110 Enter, KeyPress, KeyRelease,
111 Leave, Motion)
112 state - state as a string (Visibility)
113 time - when the event occurred
114 x - x-position of the mouse
115 y - y-position of the mouse
116 x_root - x-position of the mouse on the screen
117 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
118 y_root - y-position of the mouse on the screen
119 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
120 char - pressed character (KeyPress, KeyRelease)
121 send_event - see X/Windows documentation
Walter Dörwald966c2642005-11-09 17:12:43 +0000122 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000123 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
124 type - type of the event as a number
125 widget - widget in which the event occurred
126 delta - delta of wheel movement (MouseWheel)
127 """
128 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000129
Guido van Rossumc4570481998-03-20 20:45:49 +0000130_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000131_default_root = None
132
Guido van Rossumc4570481998-03-20 20:45:49 +0000133def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000134 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000135
Fredrik Lundh06d28152000-08-09 18:03:12 +0000136 Call this function to inhibit that the first instance of
137 Tk is used for windows without an explicit parent window.
138 """
139 global _support_default_root
140 _support_default_root = 0
141 global _default_root
142 _default_root = None
143 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000144
Guido van Rossum45853db1994-06-20 12:19:19 +0000145def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000146 """Internal function."""
147 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000148
Guido van Rossum97aeca11994-07-07 13:12:12 +0000149def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000150 """Internal function. Calling it will throw the exception SystemExit."""
Collin Winterce36ad82007-08-30 01:19:48 +0000151 raise SystemExit(code)
Guido van Rossum97aeca11994-07-07 13:12:12 +0000152
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000153_varnum = 0
154class Variable:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000155 """Class to define value holders for e.g. buttons.
156
157 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
158 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000159 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160 def __init__(self, master=None, value=None, name=None):
161 """Construct a variable
162
163 MASTER can be given as master widget.
164 VALUE is an optional value (defaults to "")
165 NAME is an optional Tcl name (defaults to PY_VARnum).
166
167 If NAME matches an existing variable and VALUE is omitted
168 then the existing value is retained.
Fredrik Lundh06d28152000-08-09 18:03:12 +0000169 """
170 global _varnum
171 if not master:
172 master = _default_root
173 self._master = master
174 self._tk = master.tk
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000175 if name:
176 self._name = name
177 else:
178 self._name = 'PY_VAR' + repr(_varnum)
179 _varnum += 1
Benjamin Peterson2a691a82008-03-31 01:51:45 +0000180 if value is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000181 self.set(value)
182 elif not self._tk.call("info", "exists", self._name):
183 self.set(self._default)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000184 def __del__(self):
185 """Unset the variable in Tcl."""
186 self._tk.globalunsetvar(self._name)
187 def __str__(self):
188 """Return the name of the variable in Tcl."""
189 return self._name
190 def set(self, value):
191 """Set the variable to VALUE."""
192 return self._tk.globalsetvar(self._name, value)
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000193 def get(self):
194 """Return value of variable."""
195 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000196 def trace_variable(self, mode, callback):
197 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000198
Fredrik Lundh06d28152000-08-09 18:03:12 +0000199 MODE is one of "r", "w", "u" for read, write, undefine.
200 CALLBACK must be a function which is called when
201 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000202
Fredrik Lundh06d28152000-08-09 18:03:12 +0000203 Return the name of the callback.
204 """
205 cbname = self._master._register(callback)
206 self._tk.call("trace", "variable", self._name, mode, cbname)
207 return cbname
208 trace = trace_variable
209 def trace_vdelete(self, mode, cbname):
210 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000211
Fredrik Lundh06d28152000-08-09 18:03:12 +0000212 MODE is one of "r", "w", "u" for read, write, undefine.
213 CBNAME is the name of the callback returned from trace_variable or trace.
214 """
215 self._tk.call("trace", "vdelete", self._name, mode, cbname)
216 self._master.deletecommand(cbname)
217 def trace_vinfo(self):
218 """Return all trace callback information."""
219 return map(self._tk.split, self._tk.splitlist(
220 self._tk.call("trace", "vinfo", self._name)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000221 def __eq__(self, other):
222 """Comparison for equality (==).
223
224 Note: if the Variable's master matters to behavior
225 also compare self._master == other._master
226 """
227 return self.__class__.__name__ == other.__class__.__name__ \
228 and self._name == other._name
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000229
230class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000231 """Value holder for strings variables."""
232 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000233 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000234 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000235
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000236 MASTER can be given as master widget.
237 VALUE is an optional value (defaults to "")
238 NAME is an optional Tcl name (defaults to PY_VARnum).
239
240 If NAME matches an existing variable and VALUE is omitted
241 then the existing value is retained.
242 """
243 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000244
Fredrik Lundh06d28152000-08-09 18:03:12 +0000245 def get(self):
246 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000247 value = self._tk.globalgetvar(self._name)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000248 if isinstance(value, str):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000249 return value
250 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000251
252class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000253 """Value holder for integer variables."""
254 _default = 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000255 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000256 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000257
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000258 MASTER can be given as master widget.
259 VALUE is an optional value (defaults to 0)
260 NAME is an optional Tcl name (defaults to PY_VARnum).
261
262 If NAME matches an existing variable and VALUE is omitted
263 then the existing value is retained.
264 """
265 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000266
Martin v. Löwis70c3dda2003-01-22 09:17:38 +0000267 def set(self, value):
268 """Set the variable to value, converting booleans to integers."""
269 if isinstance(value, bool):
270 value = int(value)
271 return Variable.set(self, value)
272
Fredrik Lundh06d28152000-08-09 18:03:12 +0000273 def get(self):
274 """Return the value of the variable as an integer."""
275 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000276
277class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000278 """Value holder for float variables."""
279 _default = 0.0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000280 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000281 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000282
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000283 MASTER can be given as master widget.
284 VALUE is an optional value (defaults to 0.0)
285 NAME is an optional Tcl name (defaults to PY_VARnum).
286
287 If NAME matches an existing variable and VALUE is omitted
288 then the existing value is retained.
289 """
290 Variable.__init__(self, master, value, name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000291
292 def get(self):
293 """Return the value of the variable as a float."""
294 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000295
296class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000297 """Value holder for boolean variables."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298 _default = False
299 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000300 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000301
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000302 MASTER can be given as master widget.
303 VALUE is an optional value (defaults to False)
304 NAME is an optional Tcl name (defaults to PY_VARnum).
305
306 If NAME matches an existing variable and VALUE is omitted
307 then the existing value is retained.
308 """
309 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000310
Fredrik Lundh06d28152000-08-09 18:03:12 +0000311 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000312 """Return the value of the variable as a bool."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000313 return self._tk.getboolean(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000314
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000315def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000316 """Run the main loop of Tcl."""
317 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000318
Guido van Rossum0132f691998-04-30 17:50:36 +0000319getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000320
Guido van Rossum0132f691998-04-30 17:50:36 +0000321getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000322
323def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000324 """Convert true and false to integer values 1 and 0."""
325 return _default_root.tk.getboolean(s)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000326
Guido van Rossum368e06b1997-11-07 20:38:49 +0000327# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000328class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000329 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000330
Fredrik Lundh06d28152000-08-09 18:03:12 +0000331 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000332
Fredrik Lundh06d28152000-08-09 18:03:12 +0000333 # XXX font command?
334 _tclCommands = None
335 def destroy(self):
336 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000337
Fredrik Lundh06d28152000-08-09 18:03:12 +0000338 Delete all Tcl commands created for
339 this widget in the Tcl interpreter."""
340 if self._tclCommands is not None:
341 for name in self._tclCommands:
342 #print '- Tkinter: deleted command', name
343 self.tk.deletecommand(name)
344 self._tclCommands = None
345 def deletecommand(self, name):
346 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000347
Fredrik Lundh06d28152000-08-09 18:03:12 +0000348 Delete the Tcl command provided in NAME."""
349 #print '- Tkinter: deleted command', name
350 self.tk.deletecommand(name)
351 try:
352 self._tclCommands.remove(name)
353 except ValueError:
354 pass
355 def tk_strictMotif(self, boolean=None):
356 """Set Tcl internal variable, whether the look and feel
357 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000358
Fredrik Lundh06d28152000-08-09 18:03:12 +0000359 A parameter of 1 means adhere to Motif (e.g. no color
360 change if mouse passes over slider).
361 Returns the set value."""
362 return self.tk.getboolean(self.tk.call(
363 'set', 'tk_strictMotif', boolean))
364 def tk_bisque(self):
365 """Change the color scheme to light brown as used in Tk 3.6 and before."""
366 self.tk.call('tk_bisque')
367 def tk_setPalette(self, *args, **kw):
368 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000369
Fredrik Lundh06d28152000-08-09 18:03:12 +0000370 A single color as argument will cause that all colors of Tk
371 widget elements are derived from this.
372 Alternatively several keyword parameters and its associated
373 colors can be given. The following keywords are valid:
374 activeBackground, foreground, selectColor,
375 activeForeground, highlightBackground, selectBackground,
376 background, highlightColor, selectForeground,
377 disabledForeground, insertBackground, troughColor."""
378 self.tk.call(('tk_setPalette',)
379 + _flatten(args) + _flatten(kw.items()))
380 def tk_menuBar(self, *args):
381 """Do not use. Needed in Tk 3.6 and earlier."""
382 pass # obsolete since Tk 4.0
383 def wait_variable(self, name='PY_VAR'):
384 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000385
Fredrik Lundh06d28152000-08-09 18:03:12 +0000386 A parameter of type IntVar, StringVar, DoubleVar or
387 BooleanVar must be given."""
388 self.tk.call('tkwait', 'variable', name)
389 waitvar = wait_variable # XXX b/w compat
390 def wait_window(self, window=None):
391 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000392
Fredrik Lundh06d28152000-08-09 18:03:12 +0000393 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000394 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000395 window = self
396 self.tk.call('tkwait', 'window', window._w)
397 def wait_visibility(self, window=None):
398 """Wait until the visibility of a WIDGET changes
399 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000400
Fredrik Lundh06d28152000-08-09 18:03:12 +0000401 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000402 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000403 window = self
404 self.tk.call('tkwait', 'visibility', window._w)
405 def setvar(self, name='PY_VAR', value='1'):
406 """Set Tcl variable NAME to VALUE."""
407 self.tk.setvar(name, value)
408 def getvar(self, name='PY_VAR'):
409 """Return value of Tcl variable NAME."""
410 return self.tk.getvar(name)
411 getint = int
412 getdouble = float
413 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000414 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000415 return self.tk.getboolean(s)
416 def focus_set(self):
417 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000418
Fredrik Lundh06d28152000-08-09 18:03:12 +0000419 If the application currently does not have the focus
420 this widget will get the focus if the application gets
421 the focus through the window manager."""
422 self.tk.call('focus', self._w)
423 focus = focus_set # XXX b/w compat?
424 def focus_force(self):
425 """Direct input focus to this widget even if the
426 application does not have the focus. Use with
427 caution!"""
428 self.tk.call('focus', '-force', self._w)
429 def focus_get(self):
430 """Return the widget which has currently the focus in the
431 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000432
Fredrik Lundh06d28152000-08-09 18:03:12 +0000433 Use focus_displayof to allow working with several
434 displays. Return None if application does not have
435 the focus."""
436 name = self.tk.call('focus')
437 if name == 'none' or not name: return None
438 return self._nametowidget(name)
439 def focus_displayof(self):
440 """Return the widget which has currently the focus on the
441 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000442
Fredrik Lundh06d28152000-08-09 18:03:12 +0000443 Return None if the application does not have the focus."""
444 name = self.tk.call('focus', '-displayof', self._w)
445 if name == 'none' or not name: return None
446 return self._nametowidget(name)
447 def focus_lastfor(self):
448 """Return the widget which would have the focus if top level
449 for this widget gets the focus from the window manager."""
450 name = self.tk.call('focus', '-lastfor', self._w)
451 if name == 'none' or not name: return None
452 return self._nametowidget(name)
453 def tk_focusFollowsMouse(self):
454 """The widget under mouse will get automatically focus. Can not
455 be disabled easily."""
456 self.tk.call('tk_focusFollowsMouse')
457 def tk_focusNext(self):
458 """Return the next widget in the focus order which follows
459 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000460
Fredrik Lundh06d28152000-08-09 18:03:12 +0000461 The focus order first goes to the next child, then to
462 the children of the child recursively and then to the
463 next sibling which is higher in the stacking order. A
464 widget is omitted if it has the takefocus resource set
465 to 0."""
466 name = self.tk.call('tk_focusNext', self._w)
467 if not name: return None
468 return self._nametowidget(name)
469 def tk_focusPrev(self):
470 """Return previous widget in the focus order. See tk_focusNext for details."""
471 name = self.tk.call('tk_focusPrev', self._w)
472 if not name: return None
473 return self._nametowidget(name)
474 def after(self, ms, func=None, *args):
475 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000476
Fredrik Lundh06d28152000-08-09 18:03:12 +0000477 MS specifies the time in milliseconds. FUNC gives the
478 function which shall be called. Additional parameters
479 are given as parameters to the function call. Return
480 identifier to cancel scheduling with after_cancel."""
481 if not func:
482 # I'd rather use time.sleep(ms*0.001)
483 self.tk.call('after', ms)
484 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000485 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000486 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000487 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000488 finally:
489 try:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000491 except TclError:
492 pass
493 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000494 return self.tk.call('after', ms, name)
495 def after_idle(self, func, *args):
496 """Call FUNC once if the Tcl main loop has no event to
497 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000498
Fredrik Lundh06d28152000-08-09 18:03:12 +0000499 Return an identifier to cancel the scheduling with
500 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000501 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000502 def after_cancel(self, id):
503 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000504
Fredrik Lundh06d28152000-08-09 18:03:12 +0000505 Identifier returned by after or after_idle must be
506 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000507 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000508 data = self.tk.call('after', 'info', id)
509 # In Tk 8.3, splitlist returns: (script, type)
510 # In Tk 8.4, splitlist may return (script, type) or (script,)
511 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000512 self.deletecommand(script)
513 except TclError:
514 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000515 self.tk.call('after', 'cancel', id)
516 def bell(self, displayof=0):
517 """Ring a display's bell."""
518 self.tk.call(('bell',) + self._displayof(displayof))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000519
Fredrik Lundh06d28152000-08-09 18:03:12 +0000520 # Clipboard handling:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521 def clipboard_get(self, **kw):
522 """Retrieve data from the clipboard on window's display.
523
524 The window keyword defaults to the root window of the Tkinter
525 application.
526
527 The type keyword specifies the form in which the data is
528 to be returned and should be an atom name such as STRING
529 or FILE_NAME. Type defaults to STRING.
530
531 This command is equivalent to:
532
533 selection_get(CLIPBOARD)
534 """
535 return self.tk.call(('clipboard', 'get') + self._options(kw))
536
Fredrik Lundh06d28152000-08-09 18:03:12 +0000537 def clipboard_clear(self, **kw):
538 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000539
Fredrik Lundh06d28152000-08-09 18:03:12 +0000540 A widget specified for the optional displayof keyword
541 argument specifies the target display."""
Guido van Rossume014a132006-08-19 16:53:45 +0000542 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000543 self.tk.call(('clipboard', 'clear') + self._options(kw))
544 def clipboard_append(self, string, **kw):
545 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000546
Fredrik Lundh06d28152000-08-09 18:03:12 +0000547 A widget specified at the optional displayof keyword
548 argument specifies the target display. The clipboard
549 can be retrieved with selection_get."""
Guido van Rossume014a132006-08-19 16:53:45 +0000550 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000551 self.tk.call(('clipboard', 'append') + self._options(kw)
552 + ('--', string))
553 # XXX grab current w/o window argument
554 def grab_current(self):
555 """Return widget which has currently the grab in this application
556 or None."""
557 name = self.tk.call('grab', 'current', self._w)
558 if not name: return None
559 return self._nametowidget(name)
560 def grab_release(self):
561 """Release grab for this widget if currently set."""
562 self.tk.call('grab', 'release', self._w)
563 def grab_set(self):
564 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000565
Fredrik Lundh06d28152000-08-09 18:03:12 +0000566 A grab directs all events to this and descendant
567 widgets in the application."""
568 self.tk.call('grab', 'set', self._w)
569 def grab_set_global(self):
570 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000571
Fredrik Lundh06d28152000-08-09 18:03:12 +0000572 A global grab directs all events to this and
573 descendant widgets on the display. Use with caution -
574 other applications do not get events anymore."""
575 self.tk.call('grab', 'set', '-global', self._w)
576 def grab_status(self):
577 """Return None, "local" or "global" if this widget has
578 no, a local or a global grab."""
579 status = self.tk.call('grab', 'status', self._w)
580 if status == 'none': status = None
581 return status
Fredrik Lundh06d28152000-08-09 18:03:12 +0000582 def option_add(self, pattern, value, priority = None):
583 """Set a VALUE (second parameter) for an option
584 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000585
Fredrik Lundh06d28152000-08-09 18:03:12 +0000586 An optional third parameter gives the numeric priority
587 (defaults to 80)."""
588 self.tk.call('option', 'add', pattern, value, priority)
589 def option_clear(self):
590 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000591
Fredrik Lundh06d28152000-08-09 18:03:12 +0000592 It will be reloaded if option_add is called."""
593 self.tk.call('option', 'clear')
594 def option_get(self, name, className):
595 """Return the value for an option NAME for this widget
596 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000597
Fredrik Lundh06d28152000-08-09 18:03:12 +0000598 Values with higher priority override lower values."""
599 return self.tk.call('option', 'get', self._w, name, className)
600 def option_readfile(self, fileName, priority = None):
601 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000602
Fredrik Lundh06d28152000-08-09 18:03:12 +0000603 An optional second parameter gives the numeric
604 priority."""
605 self.tk.call('option', 'readfile', fileName, priority)
606 def selection_clear(self, **kw):
607 """Clear the current X selection."""
Guido van Rossume014a132006-08-19 16:53:45 +0000608 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000609 self.tk.call(('selection', 'clear') + self._options(kw))
610 def selection_get(self, **kw):
611 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000612
Fredrik Lundh06d28152000-08-09 18:03:12 +0000613 A keyword parameter selection specifies the name of
614 the selection and defaults to PRIMARY. A keyword
615 parameter displayof specifies a widget on the display
616 to use."""
Guido van Rossume014a132006-08-19 16:53:45 +0000617 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000618 return self.tk.call(('selection', 'get') + self._options(kw))
619 def selection_handle(self, command, **kw):
620 """Specify a function COMMAND to call if the X
621 selection owned by this widget is queried by another
622 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000623
Fredrik Lundh06d28152000-08-09 18:03:12 +0000624 This function must return the contents of the
625 selection. The function will be called with the
626 arguments OFFSET and LENGTH which allows the chunking
627 of very long selections. The following keyword
628 parameters can be provided:
629 selection - name of the selection (default PRIMARY),
630 type - type of the selection (e.g. STRING, FILE_NAME)."""
631 name = self._register(command)
632 self.tk.call(('selection', 'handle') + self._options(kw)
633 + (self._w, name))
634 def selection_own(self, **kw):
635 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000636
Fredrik Lundh06d28152000-08-09 18:03:12 +0000637 A keyword parameter selection specifies the name of
638 the selection (default PRIMARY)."""
639 self.tk.call(('selection', 'own') +
640 self._options(kw) + (self._w,))
641 def selection_own_get(self, **kw):
642 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000643
Fredrik Lundh06d28152000-08-09 18:03:12 +0000644 The following keyword parameter can
645 be provided:
646 selection - name of the selection (default PRIMARY),
647 type - type of the selection (e.g. STRING, FILE_NAME)."""
Guido van Rossume014a132006-08-19 16:53:45 +0000648 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000649 name = self.tk.call(('selection', 'own') + self._options(kw))
650 if not name: return None
651 return self._nametowidget(name)
652 def send(self, interp, cmd, *args):
653 """Send Tcl command CMD to different interpreter INTERP to be executed."""
654 return self.tk.call(('send', interp, cmd) + args)
655 def lower(self, belowThis=None):
656 """Lower this widget in the stacking order."""
657 self.tk.call('lower', self._w, belowThis)
658 def tkraise(self, aboveThis=None):
659 """Raise this widget in the stacking order."""
660 self.tk.call('raise', self._w, aboveThis)
661 lift = tkraise
662 def colormodel(self, value=None):
663 """Useless. Not implemented in Tk."""
664 return self.tk.call('tk', 'colormodel', self._w, value)
665 def winfo_atom(self, name, displayof=0):
666 """Return integer which represents atom NAME."""
667 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
668 return getint(self.tk.call(args))
669 def winfo_atomname(self, id, displayof=0):
670 """Return name of atom with identifier ID."""
671 args = ('winfo', 'atomname') \
672 + self._displayof(displayof) + (id,)
673 return self.tk.call(args)
674 def winfo_cells(self):
675 """Return number of cells in the colormap for this widget."""
676 return getint(
677 self.tk.call('winfo', 'cells', self._w))
678 def winfo_children(self):
679 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000680 result = []
681 for child in self.tk.splitlist(
682 self.tk.call('winfo', 'children', self._w)):
683 try:
684 # Tcl sometimes returns extra windows, e.g. for
685 # menus; those need to be skipped
686 result.append(self._nametowidget(child))
687 except KeyError:
688 pass
689 return result
690
Fredrik Lundh06d28152000-08-09 18:03:12 +0000691 def winfo_class(self):
692 """Return window class name of this widget."""
693 return self.tk.call('winfo', 'class', self._w)
694 def winfo_colormapfull(self):
695 """Return true if at the last color request the colormap was full."""
696 return self.tk.getboolean(
697 self.tk.call('winfo', 'colormapfull', self._w))
698 def winfo_containing(self, rootX, rootY, displayof=0):
699 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
700 args = ('winfo', 'containing') \
701 + self._displayof(displayof) + (rootX, rootY)
702 name = self.tk.call(args)
703 if not name: return None
704 return self._nametowidget(name)
705 def winfo_depth(self):
706 """Return the number of bits per pixel."""
707 return getint(self.tk.call('winfo', 'depth', self._w))
708 def winfo_exists(self):
709 """Return true if this widget exists."""
710 return getint(
711 self.tk.call('winfo', 'exists', self._w))
712 def winfo_fpixels(self, number):
713 """Return the number of pixels for the given distance NUMBER
714 (e.g. "3c") as float."""
715 return getdouble(self.tk.call(
716 'winfo', 'fpixels', self._w, number))
717 def winfo_geometry(self):
718 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
719 return self.tk.call('winfo', 'geometry', self._w)
720 def winfo_height(self):
721 """Return height of this widget."""
722 return getint(
723 self.tk.call('winfo', 'height', self._w))
724 def winfo_id(self):
725 """Return identifier ID for this widget."""
726 return self.tk.getint(
727 self.tk.call('winfo', 'id', self._w))
728 def winfo_interps(self, displayof=0):
729 """Return the name of all Tcl interpreters for this display."""
730 args = ('winfo', 'interps') + self._displayof(displayof)
731 return self.tk.splitlist(self.tk.call(args))
732 def winfo_ismapped(self):
733 """Return true if this widget is mapped."""
734 return getint(
735 self.tk.call('winfo', 'ismapped', self._w))
736 def winfo_manager(self):
737 """Return the window mananger name for this widget."""
738 return self.tk.call('winfo', 'manager', self._w)
739 def winfo_name(self):
740 """Return the name of this widget."""
741 return self.tk.call('winfo', 'name', self._w)
742 def winfo_parent(self):
743 """Return the name of the parent of this widget."""
744 return self.tk.call('winfo', 'parent', self._w)
745 def winfo_pathname(self, id, displayof=0):
746 """Return the pathname of the widget given by ID."""
747 args = ('winfo', 'pathname') \
748 + self._displayof(displayof) + (id,)
749 return self.tk.call(args)
750 def winfo_pixels(self, number):
751 """Rounded integer value of winfo_fpixels."""
752 return getint(
753 self.tk.call('winfo', 'pixels', self._w, number))
754 def winfo_pointerx(self):
755 """Return the x coordinate of the pointer on the root window."""
756 return getint(
757 self.tk.call('winfo', 'pointerx', self._w))
758 def winfo_pointerxy(self):
759 """Return a tuple of x and y coordinates of the pointer on the root window."""
760 return self._getints(
761 self.tk.call('winfo', 'pointerxy', self._w))
762 def winfo_pointery(self):
763 """Return the y coordinate of the pointer on the root window."""
764 return getint(
765 self.tk.call('winfo', 'pointery', self._w))
766 def winfo_reqheight(self):
767 """Return requested height of this widget."""
768 return getint(
769 self.tk.call('winfo', 'reqheight', self._w))
770 def winfo_reqwidth(self):
771 """Return requested width of this widget."""
772 return getint(
773 self.tk.call('winfo', 'reqwidth', self._w))
774 def winfo_rgb(self, color):
775 """Return tuple of decimal values for red, green, blue for
776 COLOR in this widget."""
777 return self._getints(
778 self.tk.call('winfo', 'rgb', self._w, color))
779 def winfo_rootx(self):
780 """Return x coordinate of upper left corner of this widget on the
781 root window."""
782 return getint(
783 self.tk.call('winfo', 'rootx', self._w))
784 def winfo_rooty(self):
785 """Return y coordinate of upper left corner of this widget on the
786 root window."""
787 return getint(
788 self.tk.call('winfo', 'rooty', self._w))
789 def winfo_screen(self):
790 """Return the screen name of this widget."""
791 return self.tk.call('winfo', 'screen', self._w)
792 def winfo_screencells(self):
793 """Return the number of the cells in the colormap of the screen
794 of this widget."""
795 return getint(
796 self.tk.call('winfo', 'screencells', self._w))
797 def winfo_screendepth(self):
798 """Return the number of bits per pixel of the root window of the
799 screen of this widget."""
800 return getint(
801 self.tk.call('winfo', 'screendepth', self._w))
802 def winfo_screenheight(self):
803 """Return the number of pixels of the height of the screen of this widget
804 in pixel."""
805 return getint(
806 self.tk.call('winfo', 'screenheight', self._w))
807 def winfo_screenmmheight(self):
808 """Return the number of pixels of the height of the screen of
809 this widget in mm."""
810 return getint(
811 self.tk.call('winfo', 'screenmmheight', self._w))
812 def winfo_screenmmwidth(self):
813 """Return the number of pixels of the width of the screen of
814 this widget in mm."""
815 return getint(
816 self.tk.call('winfo', 'screenmmwidth', self._w))
817 def winfo_screenvisual(self):
818 """Return one of the strings directcolor, grayscale, pseudocolor,
819 staticcolor, staticgray, or truecolor for the default
820 colormodel of this screen."""
821 return self.tk.call('winfo', 'screenvisual', self._w)
822 def winfo_screenwidth(self):
823 """Return the number of pixels of the width of the screen of
824 this widget in pixel."""
825 return getint(
826 self.tk.call('winfo', 'screenwidth', self._w))
827 def winfo_server(self):
828 """Return information of the X-Server of the screen of this widget in
829 the form "XmajorRminor vendor vendorVersion"."""
830 return self.tk.call('winfo', 'server', self._w)
831 def winfo_toplevel(self):
832 """Return the toplevel widget of this widget."""
833 return self._nametowidget(self.tk.call(
834 'winfo', 'toplevel', self._w))
835 def winfo_viewable(self):
836 """Return true if the widget and all its higher ancestors are mapped."""
837 return getint(
838 self.tk.call('winfo', 'viewable', self._w))
839 def winfo_visual(self):
840 """Return one of the strings directcolor, grayscale, pseudocolor,
841 staticcolor, staticgray, or truecolor for the
842 colormodel of this widget."""
843 return self.tk.call('winfo', 'visual', self._w)
844 def winfo_visualid(self):
845 """Return the X identifier for the visual for this widget."""
846 return self.tk.call('winfo', 'visualid', self._w)
847 def winfo_visualsavailable(self, includeids=0):
848 """Return a list of all visuals available for the screen
849 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000850
Fredrik Lundh06d28152000-08-09 18:03:12 +0000851 Each item in the list consists of a visual name (see winfo_visual), a
852 depth and if INCLUDEIDS=1 is given also the X identifier."""
853 data = self.tk.split(
854 self.tk.call('winfo', 'visualsavailable', self._w,
855 includeids and 'includeids' or None))
Guido van Rossum13257902007-06-07 23:15:56 +0000856 if isinstance(data, str):
Fredrik Lundh24037f72000-08-09 19:26:47 +0000857 data = [self.tk.split(data)]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000858 return map(self.__winfo_parseitem, data)
859 def __winfo_parseitem(self, t):
860 """Internal function."""
861 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
862 def __winfo_getint(self, x):
863 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000864 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000865 def winfo_vrootheight(self):
866 """Return the height of the virtual root window associated with this
867 widget in pixels. If there is no virtual root window return the
868 height of the screen."""
869 return getint(
870 self.tk.call('winfo', 'vrootheight', self._w))
871 def winfo_vrootwidth(self):
872 """Return the width of the virtual root window associated with this
873 widget in pixel. If there is no virtual root window return the
874 width of the screen."""
875 return getint(
876 self.tk.call('winfo', 'vrootwidth', self._w))
877 def winfo_vrootx(self):
878 """Return the x offset of the virtual root relative to the root
879 window of the screen of this widget."""
880 return getint(
881 self.tk.call('winfo', 'vrootx', self._w))
882 def winfo_vrooty(self):
883 """Return the y offset of the virtual root relative to the root
884 window of the screen of this widget."""
885 return getint(
886 self.tk.call('winfo', 'vrooty', self._w))
887 def winfo_width(self):
888 """Return the width of this widget."""
889 return getint(
890 self.tk.call('winfo', 'width', self._w))
891 def winfo_x(self):
892 """Return the x coordinate of the upper left corner of this widget
893 in the parent."""
894 return getint(
895 self.tk.call('winfo', 'x', self._w))
896 def winfo_y(self):
897 """Return the y coordinate of the upper left corner of this widget
898 in the parent."""
899 return getint(
900 self.tk.call('winfo', 'y', self._w))
901 def update(self):
902 """Enter event loop until all pending events have been processed by Tcl."""
903 self.tk.call('update')
904 def update_idletasks(self):
905 """Enter event loop until all idle callbacks have been called. This
906 will update the display of windows but not process events caused by
907 the user."""
908 self.tk.call('update', 'idletasks')
909 def bindtags(self, tagList=None):
910 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000911
Fredrik Lundh06d28152000-08-09 18:03:12 +0000912 With no argument return the list of all bindtags associated with
913 this widget. With a list of strings as argument the bindtags are
914 set to this list. The bindtags determine in which order events are
915 processed (see bind)."""
916 if tagList is None:
917 return self.tk.splitlist(
918 self.tk.call('bindtags', self._w))
919 else:
920 self.tk.call('bindtags', self._w, tagList)
921 def _bind(self, what, sequence, func, add, needcleanup=1):
922 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +0000923 if isinstance(func, str):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000924 self.tk.call(what + (sequence, func))
925 elif func:
926 funcid = self._register(func, self._substitute,
927 needcleanup)
928 cmd = ('%sif {"[%s %s]" == "break"} break\n'
929 %
930 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000931 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000932 self.tk.call(what + (sequence, cmd))
933 return funcid
934 elif sequence:
935 return self.tk.call(what + (sequence,))
936 else:
937 return self.tk.splitlist(self.tk.call(what))
938 def bind(self, sequence=None, func=None, add=None):
939 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000940
Fredrik Lundh06d28152000-08-09 18:03:12 +0000941 SEQUENCE is a string of concatenated event
942 patterns. An event pattern is of the form
943 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
944 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
945 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
946 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
947 Mod1, M1. TYPE is one of Activate, Enter, Map,
948 ButtonPress, Button, Expose, Motion, ButtonRelease
949 FocusIn, MouseWheel, Circulate, FocusOut, Property,
950 Colormap, Gravity Reparent, Configure, KeyPress, Key,
951 Unmap, Deactivate, KeyRelease Visibility, Destroy,
952 Leave and DETAIL is the button number for ButtonPress,
953 ButtonRelease and DETAIL is the Keysym for KeyPress and
954 KeyRelease. Examples are
955 <Control-Button-1> for pressing Control and mouse button 1 or
956 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
957 An event pattern can also be a virtual event of the form
958 <<AString>> where AString can be arbitrary. This
959 event can be generated by event_generate.
960 If events are concatenated they must appear shortly
961 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000962
Fredrik Lundh06d28152000-08-09 18:03:12 +0000963 FUNC will be called if the event sequence occurs with an
964 instance of Event as argument. If the return value of FUNC is
965 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000966
Fredrik Lundh06d28152000-08-09 18:03:12 +0000967 An additional boolean parameter ADD specifies whether FUNC will
968 be called additionally to the other bound function or whether
969 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000970
Fredrik Lundh06d28152000-08-09 18:03:12 +0000971 Bind will return an identifier to allow deletion of the bound function with
972 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000973
Fredrik Lundh06d28152000-08-09 18:03:12 +0000974 If FUNC or SEQUENCE is omitted the bound function or list
975 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000976
Fredrik Lundh06d28152000-08-09 18:03:12 +0000977 return self._bind(('bind', self._w), sequence, func, add)
978 def unbind(self, sequence, funcid=None):
979 """Unbind for this widget for event SEQUENCE the
980 function identified with FUNCID."""
981 self.tk.call('bind', self._w, sequence, '')
982 if funcid:
983 self.deletecommand(funcid)
984 def bind_all(self, sequence=None, func=None, add=None):
985 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
986 An additional boolean parameter ADD specifies whether FUNC will
987 be called additionally to the other bound function or whether
988 it will replace the previous function. See bind for the return value."""
989 return self._bind(('bind', 'all'), sequence, func, add, 0)
990 def unbind_all(self, sequence):
991 """Unbind for all widgets for event SEQUENCE all functions."""
992 self.tk.call('bind', 'all' , sequence, '')
993 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000994
Fredrik Lundh06d28152000-08-09 18:03:12 +0000995 """Bind to widgets with bindtag CLASSNAME at event
996 SEQUENCE a call of function FUNC. An additional
997 boolean parameter ADD specifies whether FUNC will be
998 called additionally to the other bound function or
999 whether it will replace the previous function. See bind for
1000 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001001
Fredrik Lundh06d28152000-08-09 18:03:12 +00001002 return self._bind(('bind', className), sequence, func, add, 0)
1003 def unbind_class(self, className, sequence):
1004 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1005 all functions."""
1006 self.tk.call('bind', className , sequence, '')
1007 def mainloop(self, n=0):
1008 """Call the mainloop of Tk."""
1009 self.tk.mainloop(n)
1010 def quit(self):
1011 """Quit the Tcl interpreter. All widgets will be destroyed."""
1012 self.tk.quit()
1013 def _getints(self, string):
1014 """Internal function."""
1015 if string:
1016 return tuple(map(getint, self.tk.splitlist(string)))
1017 def _getdoubles(self, string):
1018 """Internal function."""
1019 if string:
1020 return tuple(map(getdouble, self.tk.splitlist(string)))
1021 def _getboolean(self, string):
1022 """Internal function."""
1023 if string:
1024 return self.tk.getboolean(string)
1025 def _displayof(self, displayof):
1026 """Internal function."""
1027 if displayof:
1028 return ('-displayof', displayof)
1029 if displayof is None:
1030 return ('-displayof', self._w)
1031 return ()
1032 def _options(self, cnf, kw = None):
1033 """Internal function."""
1034 if kw:
1035 cnf = _cnfmerge((cnf, kw))
1036 else:
1037 cnf = _cnfmerge(cnf)
1038 res = ()
1039 for k, v in cnf.items():
1040 if v is not None:
1041 if k[-1] == '_': k = k[:-1]
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001042 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001043 v = self._register(v)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001044 elif isinstance(v, (tuple, list)):
Georg Brandl3b550032008-06-03 10:25:47 +00001045 nv = []
Georg Brandlbf1eb632008-05-29 07:19:00 +00001046 for item in v:
Georg Brandl3b550032008-06-03 10:25:47 +00001047 if isinstance(item, int):
1048 nv.append(str(item))
1049 elif isinstance(item, str):
1050 nv.append(('{%s}' if ' ' in item else '%s') % item)
1051 else:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001052 break
1053 else:
Georg Brandl3b550032008-06-03 10:25:47 +00001054 v = ' '.join(nv)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001055 res = res + ('-'+k, v)
1056 return res
1057 def nametowidget(self, name):
1058 """Return the Tkinter instance of a widget identified by
1059 its Tcl name NAME."""
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001060 name = str(name).split('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001061 w = self
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001062
1063 if not name[0]:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001064 w = w._root()
1065 name = name[1:]
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001066
1067 for n in name:
1068 if not n:
1069 break
1070 w = w.children[n]
1071
Fredrik Lundh06d28152000-08-09 18:03:12 +00001072 return w
1073 _nametowidget = nametowidget
1074 def _register(self, func, subst=None, needcleanup=1):
1075 """Return a newly created Tcl function. If this
1076 function is called, the Python function FUNC will
1077 be executed. An optional function SUBST can
1078 be given which will be executed before FUNC."""
1079 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001080 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001081 try:
Christian Heimesff737952007-11-27 10:40:20 +00001082 func = func.__func__
Fredrik Lundh06d28152000-08-09 18:03:12 +00001083 except AttributeError:
1084 pass
1085 try:
1086 name = name + func.__name__
1087 except AttributeError:
1088 pass
1089 self.tk.createcommand(name, f)
1090 if needcleanup:
1091 if self._tclCommands is None:
1092 self._tclCommands = []
1093 self._tclCommands.append(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001094 return name
1095 register = _register
1096 def _root(self):
1097 """Internal function."""
1098 w = self
1099 while w.master: w = w.master
1100 return w
1101 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1102 '%s', '%t', '%w', '%x', '%y',
1103 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001104 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001105 def _substitute(self, *args):
1106 """Internal function."""
1107 if len(args) != len(self._subst_format): return args
1108 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001109
Fredrik Lundh06d28152000-08-09 18:03:12 +00001110 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001111 def getint_event(s):
1112 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1113 try:
1114 return int(s)
1115 except ValueError:
1116 return s
1117
Fredrik Lundh06d28152000-08-09 18:03:12 +00001118 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1119 # Missing: (a, c, d, m, o, v, B, R)
1120 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001121 # serial field: valid vor all events
1122 # number of button: ButtonPress and ButtonRelease events only
1123 # height field: Configure, ConfigureRequest, Create,
1124 # ResizeRequest, and Expose events only
1125 # keycode field: KeyPress and KeyRelease events only
1126 # time field: "valid for events that contain a time field"
1127 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1128 # and Expose events only
1129 # x field: "valid for events that contain a x field"
1130 # y field: "valid for events that contain a y field"
1131 # keysym as decimal: KeyPress and KeyRelease events only
1132 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1133 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001134 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001135 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001136 try: e.focus = getboolean(f)
1137 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001138 e.height = getint_event(h)
1139 e.keycode = getint_event(k)
1140 e.state = getint_event(s)
1141 e.time = getint_event(t)
1142 e.width = getint_event(w)
1143 e.x = getint_event(x)
1144 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001145 e.char = A
1146 try: e.send_event = getboolean(E)
1147 except TclError: pass
1148 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001149 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001150 e.type = T
1151 try:
1152 e.widget = self._nametowidget(W)
1153 except KeyError:
1154 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001155 e.x_root = getint_event(X)
1156 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001157 try:
1158 e.delta = getint(D)
1159 except ValueError:
1160 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001161 return (e,)
1162 def _report_exception(self):
1163 """Internal function."""
1164 import sys
Neal Norwitzac3625f2006-03-17 05:49:33 +00001165 exc, val, tb = sys.exc_info()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001166 root = self._root()
1167 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001168 def _configure(self, cmd, cnf, kw):
1169 """Internal function."""
1170 if kw:
1171 cnf = _cnfmerge((cnf, kw))
1172 elif cnf:
1173 cnf = _cnfmerge(cnf)
1174 if cnf is None:
1175 cnf = {}
1176 for x in self.tk.split(
1177 self.tk.call(_flatten((self._w, cmd)))):
1178 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1179 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00001180 if isinstance(cnf, str):
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001181 x = self.tk.split(
1182 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1183 return (x[0][1:],) + x[1:]
1184 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001185 # These used to be defined in Widget:
1186 def configure(self, cnf=None, **kw):
1187 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001188
Fredrik Lundh06d28152000-08-09 18:03:12 +00001189 The values for resources are specified as keyword
1190 arguments. To get an overview about
1191 the allowed keyword arguments call the method keys.
1192 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001193 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001194 config = configure
1195 def cget(self, key):
1196 """Return the resource value for a KEY given as string."""
1197 return self.tk.call(self._w, 'cget', '-' + key)
1198 __getitem__ = cget
1199 def __setitem__(self, key, value):
1200 self.configure({key: value})
1201 def keys(self):
1202 """Return a list of all resource names of this widget."""
1203 return map(lambda x: x[0][1:],
1204 self.tk.split(self.tk.call(self._w, 'configure')))
1205 def __str__(self):
1206 """Return the window path name of this widget."""
1207 return self._w
1208 # Pack methods that apply to the master
1209 _noarg_ = ['_noarg_']
1210 def pack_propagate(self, flag=_noarg_):
1211 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001212
Fredrik Lundh06d28152000-08-09 18:03:12 +00001213 A boolean argument specifies whether the geometry information
1214 of the slaves will determine the size of this widget. If no argument
1215 is given the current setting will be returned.
1216 """
1217 if flag is Misc._noarg_:
1218 return self._getboolean(self.tk.call(
1219 'pack', 'propagate', self._w))
1220 else:
1221 self.tk.call('pack', 'propagate', self._w, flag)
1222 propagate = pack_propagate
1223 def pack_slaves(self):
1224 """Return a list of all slaves of this widget
1225 in its packing order."""
1226 return map(self._nametowidget,
1227 self.tk.splitlist(
1228 self.tk.call('pack', 'slaves', self._w)))
1229 slaves = pack_slaves
1230 # Place method that applies to the master
1231 def place_slaves(self):
1232 """Return a list of all slaves of this widget
1233 in its packing order."""
1234 return map(self._nametowidget,
1235 self.tk.splitlist(
1236 self.tk.call(
1237 'place', 'slaves', self._w)))
1238 # Grid methods that apply to the master
1239 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1240 """Return a tuple of integer coordinates for the bounding
1241 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001242
Fredrik Lundh06d28152000-08-09 18:03:12 +00001243 If COLUMN, ROW is given the bounding box applies from
1244 the cell with row and column 0 to the specified
1245 cell. If COL2 and ROW2 are given the bounding box
1246 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001247
Fredrik Lundh06d28152000-08-09 18:03:12 +00001248 The returned integers specify the offset of the upper left
1249 corner in the master widget and the width and height.
1250 """
1251 args = ('grid', 'bbox', self._w)
1252 if column is not None and row is not None:
1253 args = args + (column, row)
1254 if col2 is not None and row2 is not None:
1255 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001256 return self._getints(self.tk.call(*args)) or None
Guido van Rossum18468821994-06-20 07:49:28 +00001257
Fredrik Lundh06d28152000-08-09 18:03:12 +00001258 bbox = grid_bbox
1259 def _grid_configure(self, command, index, cnf, kw):
1260 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001261 if isinstance(cnf, str) and not kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001262 if cnf[-1:] == '_':
1263 cnf = cnf[:-1]
1264 if cnf[:1] != '-':
1265 cnf = '-'+cnf
1266 options = (cnf,)
1267 else:
1268 options = self._options(cnf, kw)
1269 if not options:
1270 res = self.tk.call('grid',
1271 command, self._w, index)
1272 words = self.tk.splitlist(res)
1273 dict = {}
1274 for i in range(0, len(words), 2):
1275 key = words[i][1:]
1276 value = words[i+1]
1277 if not value:
1278 value = None
1279 elif '.' in value:
1280 value = getdouble(value)
1281 else:
1282 value = getint(value)
1283 dict[key] = value
1284 return dict
1285 res = self.tk.call(
1286 ('grid', command, self._w, index)
1287 + options)
1288 if len(options) == 1:
1289 if not res: return None
1290 # In Tk 7.5, -width can be a float
1291 if '.' in res: return getdouble(res)
1292 return getint(res)
1293 def grid_columnconfigure(self, index, cnf={}, **kw):
1294 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001295
Fredrik Lundh06d28152000-08-09 18:03:12 +00001296 Valid resources are minsize (minimum size of the column),
1297 weight (how much does additional space propagate to this column)
1298 and pad (how much space to let additionally)."""
1299 return self._grid_configure('columnconfigure', index, cnf, kw)
1300 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001301 def grid_location(self, x, y):
1302 """Return a tuple of column and row which identify the cell
1303 at which the pixel at position X and Y inside the master
1304 widget is located."""
1305 return self._getints(
1306 self.tk.call(
1307 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001308 def grid_propagate(self, flag=_noarg_):
1309 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001310
Fredrik Lundh06d28152000-08-09 18:03:12 +00001311 A boolean argument specifies whether the geometry information
1312 of the slaves will determine the size of this widget. If no argument
1313 is given, the current setting will be returned.
1314 """
1315 if flag is Misc._noarg_:
1316 return self._getboolean(self.tk.call(
1317 'grid', 'propagate', self._w))
1318 else:
1319 self.tk.call('grid', 'propagate', self._w, flag)
1320 def grid_rowconfigure(self, index, cnf={}, **kw):
1321 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001322
Fredrik Lundh06d28152000-08-09 18:03:12 +00001323 Valid resources are minsize (minimum size of the row),
1324 weight (how much does additional space propagate to this row)
1325 and pad (how much space to let additionally)."""
1326 return self._grid_configure('rowconfigure', index, cnf, kw)
1327 rowconfigure = grid_rowconfigure
1328 def grid_size(self):
1329 """Return a tuple of the number of column and rows in the grid."""
1330 return self._getints(
1331 self.tk.call('grid', 'size', self._w)) or None
1332 size = grid_size
1333 def grid_slaves(self, row=None, column=None):
1334 """Return a list of all slaves of this widget
1335 in its packing order."""
1336 args = ()
1337 if row is not None:
1338 args = args + ('-row', row)
1339 if column is not None:
1340 args = args + ('-column', column)
1341 return map(self._nametowidget,
1342 self.tk.splitlist(self.tk.call(
1343 ('grid', 'slaves', self._w) + args)))
Guido van Rossum80f8be81997-12-02 19:51:39 +00001344
Fredrik Lundh06d28152000-08-09 18:03:12 +00001345 # Support for the "event" command, new in Tk 4.2.
1346 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001347
Fredrik Lundh06d28152000-08-09 18:03:12 +00001348 def event_add(self, virtual, *sequences):
1349 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1350 to an event SEQUENCE such that the virtual event is triggered
1351 whenever SEQUENCE occurs."""
1352 args = ('event', 'add', virtual) + sequences
1353 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001354
Fredrik Lundh06d28152000-08-09 18:03:12 +00001355 def event_delete(self, virtual, *sequences):
1356 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1357 args = ('event', 'delete', virtual) + sequences
1358 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001359
Fredrik Lundh06d28152000-08-09 18:03:12 +00001360 def event_generate(self, sequence, **kw):
1361 """Generate an event SEQUENCE. Additional
1362 keyword arguments specify parameter of the event
1363 (e.g. x, y, rootx, rooty)."""
1364 args = ('event', 'generate', self._w, sequence)
1365 for k, v in kw.items():
1366 args = args + ('-%s' % k, str(v))
1367 self.tk.call(args)
1368
1369 def event_info(self, virtual=None):
1370 """Return a list of all virtual events or the information
1371 about the SEQUENCE bound to the virtual event VIRTUAL."""
1372 return self.tk.splitlist(
1373 self.tk.call('event', 'info', virtual))
1374
1375 # Image related commands
1376
1377 def image_names(self):
1378 """Return a list of all existing image names."""
1379 return self.tk.call('image', 'names')
1380
1381 def image_types(self):
1382 """Return a list of all available image types (e.g. phote bitmap)."""
1383 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001384
Guido van Rossum80f8be81997-12-02 19:51:39 +00001385
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001386class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001387 """Internal class. Stores function to call when some user
1388 defined Tcl function is called e.g. after an event occurred."""
1389 def __init__(self, func, subst, widget):
1390 """Store FUNC, SUBST and WIDGET as members."""
1391 self.func = func
1392 self.subst = subst
1393 self.widget = widget
1394 def __call__(self, *args):
1395 """Apply first function SUBST to arguments, than FUNC."""
1396 try:
1397 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001398 args = self.subst(*args)
1399 return self.func(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001400 except SystemExit as msg:
Collin Winterce36ad82007-08-30 01:19:48 +00001401 raise SystemExit(msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001402 except:
1403 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001404
Guido van Rossume365a591998-05-01 19:48:20 +00001405
Guilherme Polo1fff0082009-08-14 15:05:30 +00001406class XView:
1407 """Mix-in class for querying and changing the horizontal position
1408 of a widget's window."""
1409
1410 def xview(self, *args):
1411 """Query and change the horizontal position of the view."""
1412 res = self.tk.call(self._w, 'xview', *args)
1413 if not args:
1414 return self._getdoubles(res)
1415
1416 def xview_moveto(self, fraction):
1417 """Adjusts the view in the window so that FRACTION of the
1418 total width of the canvas is off-screen to the left."""
1419 self.tk.call(self._w, 'xview', 'moveto', fraction)
1420
1421 def xview_scroll(self, number, what):
1422 """Shift the x-view according to NUMBER which is measured in "units"
1423 or "pages" (WHAT)."""
1424 self.tk.call(self._w, 'xview', 'scroll', number, what)
1425
1426
1427class YView:
1428 """Mix-in class for querying and changing the vertical position
1429 of a widget's window."""
1430
1431 def yview(self, *args):
1432 """Query and change the vertical position of the view."""
1433 res = self.tk.call(self._w, 'yview', *args)
1434 if not args:
1435 return self._getdoubles(res)
1436
1437 def yview_moveto(self, fraction):
1438 """Adjusts the view in the window so that FRACTION of the
1439 total height of the canvas is off-screen to the top."""
1440 self.tk.call(self._w, 'yview', 'moveto', fraction)
1441
1442 def yview_scroll(self, number, what):
1443 """Shift the y-view according to NUMBER which is measured in
1444 "units" or "pages" (WHAT)."""
1445 self.tk.call(self._w, 'yview', 'scroll', number, what)
1446
1447
Guido van Rossum18468821994-06-20 07:49:28 +00001448class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001449 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001450
Fredrik Lundh06d28152000-08-09 18:03:12 +00001451 def wm_aspect(self,
1452 minNumer=None, minDenom=None,
1453 maxNumer=None, maxDenom=None):
1454 """Instruct the window manager to set the aspect ratio (width/height)
1455 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1456 of the actual values if no argument is given."""
1457 return self._getints(
1458 self.tk.call('wm', 'aspect', self._w,
1459 minNumer, minDenom,
1460 maxNumer, maxDenom))
1461 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001462
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001463 def wm_attributes(self, *args):
1464 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001465
1466 The first form returns a list of the platform specific flags and
1467 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001468 option. The third form sets one or more of the values. The values
1469 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001470
1471 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001472 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001473 to toolwindow (as defined in the MSDN). -topmost gets or sets
1474 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001475 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001476
1477 On Macintosh, XXXXX
1478
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001479 On Unix, there are currently no special attribute values.
1480 """
1481 args = ('wm', 'attributes', self._w) + args
1482 return self.tk.call(args)
1483 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001484
Fredrik Lundh06d28152000-08-09 18:03:12 +00001485 def wm_client(self, name=None):
1486 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1487 current value."""
1488 return self.tk.call('wm', 'client', self._w, name)
1489 client = wm_client
1490 def wm_colormapwindows(self, *wlist):
1491 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1492 of this widget. This list contains windows whose colormaps differ from their
1493 parents. Return current list of widgets if WLIST is empty."""
1494 if len(wlist) > 1:
1495 wlist = (wlist,) # Tk needs a list of windows here
1496 args = ('wm', 'colormapwindows', self._w) + wlist
1497 return map(self._nametowidget, self.tk.call(args))
1498 colormapwindows = wm_colormapwindows
1499 def wm_command(self, value=None):
1500 """Store VALUE in WM_COMMAND property. It is the command
1501 which shall be used to invoke the application. Return current
1502 command if VALUE is None."""
1503 return self.tk.call('wm', 'command', self._w, value)
1504 command = wm_command
1505 def wm_deiconify(self):
1506 """Deiconify this widget. If it was never mapped it will not be mapped.
1507 On Windows it will raise this widget and give it the focus."""
1508 return self.tk.call('wm', 'deiconify', self._w)
1509 deiconify = wm_deiconify
1510 def wm_focusmodel(self, model=None):
1511 """Set focus model to MODEL. "active" means that this widget will claim
1512 the focus itself, "passive" means that the window manager shall give
1513 the focus. Return current focus model if MODEL is None."""
1514 return self.tk.call('wm', 'focusmodel', self._w, model)
1515 focusmodel = wm_focusmodel
1516 def wm_frame(self):
1517 """Return identifier for decorative frame of this widget if present."""
1518 return self.tk.call('wm', 'frame', self._w)
1519 frame = wm_frame
1520 def wm_geometry(self, newGeometry=None):
1521 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1522 current value if None is given."""
1523 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1524 geometry = wm_geometry
1525 def wm_grid(self,
1526 baseWidth=None, baseHeight=None,
1527 widthInc=None, heightInc=None):
1528 """Instruct the window manager that this widget shall only be
1529 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1530 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1531 number of grid units requested in Tk_GeometryRequest."""
1532 return self._getints(self.tk.call(
1533 'wm', 'grid', self._w,
1534 baseWidth, baseHeight, widthInc, heightInc))
1535 grid = wm_grid
1536 def wm_group(self, pathName=None):
1537 """Set the group leader widgets for related widgets to PATHNAME. Return
1538 the group leader of this widget if None is given."""
1539 return self.tk.call('wm', 'group', self._w, pathName)
1540 group = wm_group
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001541 def wm_iconbitmap(self, bitmap=None, default=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001542 """Set bitmap for the iconified widget to BITMAP. Return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001543 the bitmap if None is given.
1544
1545 Under Windows, the DEFAULT parameter can be used to set the icon
1546 for the widget and any descendents that don't have an icon set
1547 explicitly. DEFAULT can be the relative path to a .ico file
1548 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1549 documentation for more information."""
1550 if default:
1551 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1552 else:
1553 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001554 iconbitmap = wm_iconbitmap
1555 def wm_iconify(self):
1556 """Display widget as icon."""
1557 return self.tk.call('wm', 'iconify', self._w)
1558 iconify = wm_iconify
1559 def wm_iconmask(self, bitmap=None):
1560 """Set mask for the icon bitmap of this widget. Return the
1561 mask if None is given."""
1562 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1563 iconmask = wm_iconmask
1564 def wm_iconname(self, newName=None):
1565 """Set the name of the icon for this widget. Return the name if
1566 None is given."""
1567 return self.tk.call('wm', 'iconname', self._w, newName)
1568 iconname = wm_iconname
1569 def wm_iconposition(self, x=None, y=None):
1570 """Set the position of the icon of this widget to X and Y. Return
1571 a tuple of the current values of X and X if None is given."""
1572 return self._getints(self.tk.call(
1573 'wm', 'iconposition', self._w, x, y))
1574 iconposition = wm_iconposition
1575 def wm_iconwindow(self, pathName=None):
1576 """Set widget PATHNAME to be displayed instead of icon. Return the current
1577 value if None is given."""
1578 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1579 iconwindow = wm_iconwindow
1580 def wm_maxsize(self, width=None, height=None):
1581 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1582 the values are given in grid units. Return the current values if None
1583 is given."""
1584 return self._getints(self.tk.call(
1585 'wm', 'maxsize', self._w, width, height))
1586 maxsize = wm_maxsize
1587 def wm_minsize(self, width=None, height=None):
1588 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1589 the values are given in grid units. Return the current values if None
1590 is given."""
1591 return self._getints(self.tk.call(
1592 'wm', 'minsize', self._w, width, height))
1593 minsize = wm_minsize
1594 def wm_overrideredirect(self, boolean=None):
1595 """Instruct the window manager to ignore this widget
1596 if BOOLEAN is given with 1. Return the current value if None
1597 is given."""
1598 return self._getboolean(self.tk.call(
1599 'wm', 'overrideredirect', self._w, boolean))
1600 overrideredirect = wm_overrideredirect
1601 def wm_positionfrom(self, who=None):
1602 """Instruct the window manager that the position of this widget shall
1603 be defined by the user if WHO is "user", and by its own policy if WHO is
1604 "program"."""
1605 return self.tk.call('wm', 'positionfrom', self._w, who)
1606 positionfrom = wm_positionfrom
1607 def wm_protocol(self, name=None, func=None):
1608 """Bind function FUNC to command NAME for this widget.
1609 Return the function bound to NAME if None is given. NAME could be
1610 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001611 if hasattr(func, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001612 command = self._register(func)
1613 else:
1614 command = func
1615 return self.tk.call(
1616 'wm', 'protocol', self._w, name, command)
1617 protocol = wm_protocol
1618 def wm_resizable(self, width=None, height=None):
1619 """Instruct the window manager whether this width can be resized
1620 in WIDTH or HEIGHT. Both values are boolean values."""
1621 return self.tk.call('wm', 'resizable', self._w, width, height)
1622 resizable = wm_resizable
1623 def wm_sizefrom(self, who=None):
1624 """Instruct the window manager that the size of this widget shall
1625 be defined by the user if WHO is "user", and by its own policy if WHO is
1626 "program"."""
1627 return self.tk.call('wm', 'sizefrom', self._w, who)
1628 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001629 def wm_state(self, newstate=None):
1630 """Query or set the state of this widget as one of normal, icon,
1631 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1632 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001633 state = wm_state
1634 def wm_title(self, string=None):
1635 """Set the title of this widget."""
1636 return self.tk.call('wm', 'title', self._w, string)
1637 title = wm_title
1638 def wm_transient(self, master=None):
1639 """Instruct the window manager that this widget is transient
1640 with regard to widget MASTER."""
1641 return self.tk.call('wm', 'transient', self._w, master)
1642 transient = wm_transient
1643 def wm_withdraw(self):
1644 """Withdraw this widget from the screen such that it is unmapped
1645 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1646 return self.tk.call('wm', 'withdraw', self._w)
1647 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001648
Guido van Rossum18468821994-06-20 07:49:28 +00001649
1650class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001651 """Toplevel widget of Tk which represents mostly the main window
1652 of an appliation. It has an associated Tcl interpreter."""
1653 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001654 def __init__(self, screenName=None, baseName=None, className='Tk',
1655 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001656 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1657 be created. BASENAME will be used for the identification of the profile file (see
1658 readprofile).
1659 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1660 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001661 self.master = None
1662 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001663 self._tkloaded = 0
1664 # to avoid recursions in the getattr code in case of failure, we
1665 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001666 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001667 if baseName is None:
1668 import sys, os
1669 baseName = os.path.basename(sys.argv[0])
1670 baseName, ext = os.path.splitext(baseName)
1671 if ext not in ('.py', '.pyc', '.pyo'):
1672 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001673 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001674 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001675 if useTk:
1676 self._loadtk()
1677 self.readprofile(baseName, className)
1678 def loadtk(self):
1679 if not self._tkloaded:
1680 self.tk.loadtk()
1681 self._loadtk()
1682 def _loadtk(self):
1683 self._tkloaded = 1
1684 global _default_root
Fredrik Lundh06d28152000-08-09 18:03:12 +00001685 # Version sanity checks
1686 tk_version = self.tk.getvar('tk_version')
1687 if tk_version != _tkinter.TK_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001688 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
1689 % (_tkinter.TK_VERSION, tk_version))
Martin v. Löwis54895972003-05-24 11:37:15 +00001690 # Under unknown circumstances, tcl_version gets coerced to float
1691 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001692 if tcl_version != _tkinter.TCL_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001693 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1694 % (_tkinter.TCL_VERSION, tcl_version))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001695 if TkVersion < 4.0:
Collin Winterce36ad82007-08-30 01:19:48 +00001696 raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
1697 % str(TkVersion))
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001698 # Create and register the tkerror and exit commands
1699 # We need to inline parts of _register here, _ register
1700 # would register differently-named commands.
1701 if self._tclCommands is None:
1702 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001703 self.tk.createcommand('tkerror', _tkerror)
1704 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001705 self._tclCommands.append('tkerror')
1706 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001707 if _support_default_root and not _default_root:
1708 _default_root = self
1709 self.protocol("WM_DELETE_WINDOW", self.destroy)
1710 def destroy(self):
1711 """Destroy this and all descendants widgets. This will
1712 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001713 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001714 self.tk.call('destroy', self._w)
1715 Misc.destroy(self)
1716 global _default_root
1717 if _support_default_root and _default_root is self:
1718 _default_root = None
1719 def readprofile(self, baseName, className):
1720 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001721 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1722 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001723 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001724 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001725 else: home = os.curdir
1726 class_tcl = os.path.join(home, '.%s.tcl' % className)
1727 class_py = os.path.join(home, '.%s.py' % className)
1728 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1729 base_py = os.path.join(home, '.%s.py' % baseName)
1730 dir = {'self': self}
Georg Brandl14fc4272008-05-17 18:39:55 +00001731 exec('from tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001732 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001733 self.tk.call('source', class_tcl)
1734 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001735 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001736 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001737 self.tk.call('source', base_tcl)
1738 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001739 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001740 def report_callback_exception(self, exc, val, tb):
1741 """Internal function. It reports exception on sys.stderr."""
1742 import traceback, sys
1743 sys.stderr.write("Exception in Tkinter callback\n")
1744 sys.last_type = exc
1745 sys.last_value = val
1746 sys.last_traceback = tb
1747 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001748 def __getattr__(self, attr):
1749 "Delegate attribute access to the interpreter object"
1750 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001751
Guido van Rossum368e06b1997-11-07 20:38:49 +00001752# Ideally, the classes Pack, Place and Grid disappear, the
1753# pack/place/grid methods are defined on the Widget class, and
1754# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1755# ...), with pack(), place() and grid() being short for
1756# pack_configure(), place_configure() and grid_columnconfigure(), and
1757# forget() being short for pack_forget(). As a practical matter, I'm
1758# afraid that there is too much code out there that may be using the
1759# Pack, Place or Grid class, so I leave them intact -- but only as
1760# backwards compatibility features. Also note that those methods that
1761# take a master as argument (e.g. pack_propagate) have been moved to
1762# the Misc class (which now incorporates all methods common between
1763# toplevel and interior widgets). Again, for compatibility, these are
1764# copied into the Pack, Place or Grid class.
1765
David Aschere2b4b322004-02-18 05:59:53 +00001766
1767def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1768 return Tk(screenName, baseName, className, useTk)
1769
Guido van Rossum18468821994-06-20 07:49:28 +00001770class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001771 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001772
Fredrik Lundh06d28152000-08-09 18:03:12 +00001773 Base class to use the methods pack_* in every widget."""
1774 def pack_configure(self, cnf={}, **kw):
1775 """Pack a widget in the parent widget. Use as options:
1776 after=widget - pack it after you have packed widget
1777 anchor=NSEW (or subset) - position widget according to
1778 given direction
Georg Brandlbf1eb632008-05-29 07:19:00 +00001779 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001780 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001781 fill=NONE or X or Y or BOTH - fill widget if widget grows
1782 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001783 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001784 ipadx=amount - add internal padding in x direction
1785 ipady=amount - add internal padding in y direction
1786 padx=amount - add padding in x direction
1787 pady=amount - add padding in y direction
1788 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1789 """
1790 self.tk.call(
1791 ('pack', 'configure', self._w)
1792 + self._options(cnf, kw))
1793 pack = configure = config = pack_configure
1794 def pack_forget(self):
1795 """Unmap this widget and do not use it for the packing order."""
1796 self.tk.call('pack', 'forget', self._w)
1797 forget = pack_forget
1798 def pack_info(self):
1799 """Return information about the packing options
1800 for this widget."""
1801 words = self.tk.splitlist(
1802 self.tk.call('pack', 'info', self._w))
1803 dict = {}
1804 for i in range(0, len(words), 2):
1805 key = words[i][1:]
1806 value = words[i+1]
1807 if value[:1] == '.':
1808 value = self._nametowidget(value)
1809 dict[key] = value
1810 return dict
1811 info = pack_info
1812 propagate = pack_propagate = Misc.pack_propagate
1813 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001814
1815class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001816 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001817
Fredrik Lundh06d28152000-08-09 18:03:12 +00001818 Base class to use the methods place_* in every widget."""
1819 def place_configure(self, cnf={}, **kw):
1820 """Place a widget in the parent widget. Use as options:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001821 in=master - master relative to which the widget is placed
1822 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001823 x=amount - locate anchor of this widget at position x of master
1824 y=amount - locate anchor of this widget at position y of master
1825 relx=amount - locate anchor of this widget between 0.0 and 1.0
1826 relative to width of master (1.0 is right edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001827 rely=amount - locate anchor of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001828 relative to height of master (1.0 is bottom edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001829 anchor=NSEW (or subset) - position anchor according to given direction
Fredrik Lundh06d28152000-08-09 18:03:12 +00001830 width=amount - width of this widget in pixel
1831 height=amount - height of this widget in pixel
1832 relwidth=amount - width of this widget between 0.0 and 1.0
1833 relative to width of master (1.0 is the same width
Georg Brandlbf1eb632008-05-29 07:19:00 +00001834 as the master)
1835 relheight=amount - height of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001836 relative to height of master (1.0 is the same
Georg Brandlbf1eb632008-05-29 07:19:00 +00001837 height as the master)
1838 bordermode="inside" or "outside" - whether to take border width of
1839 master widget into account
1840 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001841 self.tk.call(
1842 ('place', 'configure', self._w)
1843 + self._options(cnf, kw))
1844 place = configure = config = place_configure
1845 def place_forget(self):
1846 """Unmap this widget."""
1847 self.tk.call('place', 'forget', self._w)
1848 forget = place_forget
1849 def place_info(self):
1850 """Return information about the placing options
1851 for this widget."""
1852 words = self.tk.splitlist(
1853 self.tk.call('place', 'info', self._w))
1854 dict = {}
1855 for i in range(0, len(words), 2):
1856 key = words[i][1:]
1857 value = words[i+1]
1858 if value[:1] == '.':
1859 value = self._nametowidget(value)
1860 dict[key] = value
1861 return dict
1862 info = place_info
1863 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001864
Guido van Rossum37dcab11996-05-16 16:00:19 +00001865class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001866 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001867
Fredrik Lundh06d28152000-08-09 18:03:12 +00001868 Base class to use the methods grid_* in every widget."""
1869 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1870 def grid_configure(self, cnf={}, **kw):
1871 """Position a widget in the parent widget in a grid. Use as options:
1872 column=number - use cell identified with given column (starting with 0)
1873 columnspan=number - this widget will span several columns
1874 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001875 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001876 ipadx=amount - add internal padding in x direction
1877 ipady=amount - add internal padding in y direction
1878 padx=amount - add padding in x direction
1879 pady=amount - add padding in y direction
1880 row=number - use cell identified with given row (starting with 0)
1881 rowspan=number - this widget will span several rows
1882 sticky=NSEW - if cell is larger on which sides will this
1883 widget stick to the cell boundary
1884 """
1885 self.tk.call(
1886 ('grid', 'configure', self._w)
1887 + self._options(cnf, kw))
1888 grid = configure = config = grid_configure
1889 bbox = grid_bbox = Misc.grid_bbox
1890 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1891 def grid_forget(self):
1892 """Unmap this widget."""
1893 self.tk.call('grid', 'forget', self._w)
1894 forget = grid_forget
1895 def grid_remove(self):
1896 """Unmap this widget but remember the grid options."""
1897 self.tk.call('grid', 'remove', self._w)
1898 def grid_info(self):
1899 """Return information about the options
1900 for positioning this widget in a grid."""
1901 words = self.tk.splitlist(
1902 self.tk.call('grid', 'info', self._w))
1903 dict = {}
1904 for i in range(0, len(words), 2):
1905 key = words[i][1:]
1906 value = words[i+1]
1907 if value[:1] == '.':
1908 value = self._nametowidget(value)
1909 dict[key] = value
1910 return dict
1911 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001912 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001913 propagate = grid_propagate = Misc.grid_propagate
1914 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1915 size = grid_size = Misc.grid_size
1916 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001917
Guido van Rossum368e06b1997-11-07 20:38:49 +00001918class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001919 """Internal class."""
1920 def _setup(self, master, cnf):
1921 """Internal function. Sets up information about children."""
1922 if _support_default_root:
1923 global _default_root
1924 if not master:
1925 if not _default_root:
1926 _default_root = Tk()
1927 master = _default_root
1928 self.master = master
1929 self.tk = master.tk
1930 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00001931 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001932 name = cnf['name']
1933 del cnf['name']
1934 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001935 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001936 self._name = name
1937 if master._w=='.':
1938 self._w = '.' + name
1939 else:
1940 self._w = master._w + '.' + name
1941 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00001942 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001943 self.master.children[self._name].destroy()
1944 self.master.children[self._name] = self
1945 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1946 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1947 and appropriate options."""
1948 if kw:
1949 cnf = _cnfmerge((cnf, kw))
1950 self.widgetName = widgetName
1951 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00001952 if self._tclCommands is None:
1953 self._tclCommands = []
Guilherme Polob212b752008-09-04 11:21:31 +00001954 classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
1955 for k, v in classes:
1956 del cnf[k]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001957 self.tk.call(
1958 (widgetName, self._w) + extra + self._options(cnf))
1959 for k, v in classes:
1960 k.configure(self, v)
1961 def destroy(self):
1962 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00001963 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001964 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00001965 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001966 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001967 Misc.destroy(self)
1968 def _do(self, name, args=()):
1969 # XXX Obsolete -- better use self.tk.call directly!
1970 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00001971
Guido van Rossum368e06b1997-11-07 20:38:49 +00001972class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001973 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001974
Fredrik Lundh06d28152000-08-09 18:03:12 +00001975 Base class for a widget which can be positioned with the geometry managers
1976 Pack, Place or Grid."""
1977 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00001978
1979class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001980 """Toplevel widget, e.g. for dialogs."""
1981 def __init__(self, master=None, cnf={}, **kw):
1982 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001983
Fredrik Lundh06d28152000-08-09 18:03:12 +00001984 Valid resource names: background, bd, bg, borderwidth, class,
1985 colormap, container, cursor, height, highlightbackground,
1986 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
1987 use, visual, width."""
1988 if kw:
1989 cnf = _cnfmerge((cnf, kw))
1990 extra = ()
1991 for wmkey in ['screen', 'class_', 'class', 'visual',
1992 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00001993 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001994 val = cnf[wmkey]
1995 # TBD: a hack needed because some keys
1996 # are not valid as keyword arguments
1997 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
1998 else: opt = '-'+wmkey
1999 extra = extra + (opt, val)
2000 del cnf[wmkey]
2001 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2002 root = self._root()
2003 self.iconname(root.iconname())
2004 self.title(root.title())
2005 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00002006
2007class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002008 """Button widget."""
2009 def __init__(self, master=None, cnf={}, **kw):
2010 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002011
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002012 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002013
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002014 activebackground, activeforeground, anchor,
2015 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002016 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002017 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002018 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002019 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002020 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002021 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002022
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002023 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002024
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002025 command, compound, default, height,
2026 overrelief, state, width
2027 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002028 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002029
Fredrik Lundh06d28152000-08-09 18:03:12 +00002030 def tkButtonEnter(self, *dummy):
2031 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002032
Fredrik Lundh06d28152000-08-09 18:03:12 +00002033 def tkButtonLeave(self, *dummy):
2034 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002035
Fredrik Lundh06d28152000-08-09 18:03:12 +00002036 def tkButtonDown(self, *dummy):
2037 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002038
Fredrik Lundh06d28152000-08-09 18:03:12 +00002039 def tkButtonUp(self, *dummy):
2040 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002041
Fredrik Lundh06d28152000-08-09 18:03:12 +00002042 def tkButtonInvoke(self, *dummy):
2043 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002044
Fredrik Lundh06d28152000-08-09 18:03:12 +00002045 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002046 """Flash the button.
2047
2048 This is accomplished by redisplaying
2049 the button several times, alternating between active and
2050 normal colors. At the end of the flash the button is left
2051 in the same normal/active state as when the command was
2052 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002053 disabled.
2054 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002055 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002056
Fredrik Lundh06d28152000-08-09 18:03:12 +00002057 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002058 """Invoke the command associated with the button.
2059
2060 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002061 or an empty string if there is no command associated with
2062 the button. This command is ignored if the button's state
2063 is disabled.
2064 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002065 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002066
2067# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002068# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00002069def AtEnd():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002070 return 'end'
Guido van Rossum1e9e4001994-06-20 09:09:51 +00002071def AtInsert(*args):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002072 s = 'insert'
2073 for a in args:
2074 if a: s = s + (' ' + a)
2075 return s
Guido van Rossum18468821994-06-20 07:49:28 +00002076def AtSelFirst():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002077 return 'sel.first'
Guido van Rossum18468821994-06-20 07:49:28 +00002078def AtSelLast():
Fredrik Lundh06d28152000-08-09 18:03:12 +00002079 return 'sel.last'
Guido van Rossum18468821994-06-20 07:49:28 +00002080def At(x, y=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002081 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002082 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002083 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002084 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002085
Guilherme Polo1fff0082009-08-14 15:05:30 +00002086class Canvas(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002087 """Canvas widget to display graphical elements like lines or text."""
2088 def __init__(self, master=None, cnf={}, **kw):
2089 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002090
Fredrik Lundh06d28152000-08-09 18:03:12 +00002091 Valid resource names: background, bd, bg, borderwidth, closeenough,
2092 confine, cursor, height, highlightbackground, highlightcolor,
2093 highlightthickness, insertbackground, insertborderwidth,
2094 insertofftime, insertontime, insertwidth, offset, relief,
2095 scrollregion, selectbackground, selectborderwidth, selectforeground,
2096 state, takefocus, width, xscrollcommand, xscrollincrement,
2097 yscrollcommand, yscrollincrement."""
2098 Widget.__init__(self, master, 'canvas', cnf, kw)
2099 def addtag(self, *args):
2100 """Internal function."""
2101 self.tk.call((self._w, 'addtag') + args)
2102 def addtag_above(self, newtag, tagOrId):
2103 """Add tag NEWTAG to all items above TAGORID."""
2104 self.addtag(newtag, 'above', tagOrId)
2105 def addtag_all(self, newtag):
2106 """Add tag NEWTAG to all items."""
2107 self.addtag(newtag, 'all')
2108 def addtag_below(self, newtag, tagOrId):
2109 """Add tag NEWTAG to all items below TAGORID."""
2110 self.addtag(newtag, 'below', tagOrId)
2111 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2112 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2113 If several match take the top-most.
2114 All items closer than HALO are considered overlapping (all are
2115 closests). If START is specified the next below this tag is taken."""
2116 self.addtag(newtag, 'closest', x, y, halo, start)
2117 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2118 """Add tag NEWTAG to all items in the rectangle defined
2119 by X1,Y1,X2,Y2."""
2120 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2121 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2122 """Add tag NEWTAG to all items which overlap the rectangle
2123 defined by X1,Y1,X2,Y2."""
2124 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2125 def addtag_withtag(self, newtag, tagOrId):
2126 """Add tag NEWTAG to all items with TAGORID."""
2127 self.addtag(newtag, 'withtag', tagOrId)
2128 def bbox(self, *args):
2129 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2130 which encloses all items with tags specified as arguments."""
2131 return self._getints(
2132 self.tk.call((self._w, 'bbox') + args)) or None
2133 def tag_unbind(self, tagOrId, sequence, funcid=None):
2134 """Unbind for all items with TAGORID for event SEQUENCE the
2135 function identified with FUNCID."""
2136 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2137 if funcid:
2138 self.deletecommand(funcid)
2139 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2140 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002141
Fredrik Lundh06d28152000-08-09 18:03:12 +00002142 An additional boolean parameter ADD specifies whether FUNC will be
2143 called additionally to the other bound function or whether it will
2144 replace the previous function. See bind for the return value."""
2145 return self._bind((self._w, 'bind', tagOrId),
2146 sequence, func, add)
2147 def canvasx(self, screenx, gridspacing=None):
2148 """Return the canvas x coordinate of pixel position SCREENX rounded
2149 to nearest multiple of GRIDSPACING units."""
2150 return getdouble(self.tk.call(
2151 self._w, 'canvasx', screenx, gridspacing))
2152 def canvasy(self, screeny, gridspacing=None):
2153 """Return the canvas y coordinate of pixel position SCREENY rounded
2154 to nearest multiple of GRIDSPACING units."""
2155 return getdouble(self.tk.call(
2156 self._w, 'canvasy', screeny, gridspacing))
2157 def coords(self, *args):
2158 """Return a list of coordinates for the item given in ARGS."""
2159 # XXX Should use _flatten on args
2160 return map(getdouble,
Guido van Rossum0bd54331998-05-19 21:18:13 +00002161 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002162 self.tk.call((self._w, 'coords') + args)))
2163 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2164 """Internal function."""
2165 args = _flatten(args)
2166 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002167 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002168 args = args[:-1]
2169 else:
2170 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002171 return getint(self.tk.call(
2172 self._w, 'create', itemType,
2173 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002174 def create_arc(self, *args, **kw):
2175 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2176 return self._create('arc', args, kw)
2177 def create_bitmap(self, *args, **kw):
2178 """Create bitmap with coordinates x1,y1."""
2179 return self._create('bitmap', args, kw)
2180 def create_image(self, *args, **kw):
2181 """Create image item with coordinates x1,y1."""
2182 return self._create('image', args, kw)
2183 def create_line(self, *args, **kw):
2184 """Create line with coordinates x1,y1,...,xn,yn."""
2185 return self._create('line', args, kw)
2186 def create_oval(self, *args, **kw):
2187 """Create oval with coordinates x1,y1,x2,y2."""
2188 return self._create('oval', args, kw)
2189 def create_polygon(self, *args, **kw):
2190 """Create polygon with coordinates x1,y1,...,xn,yn."""
2191 return self._create('polygon', args, kw)
2192 def create_rectangle(self, *args, **kw):
2193 """Create rectangle with coordinates x1,y1,x2,y2."""
2194 return self._create('rectangle', args, kw)
2195 def create_text(self, *args, **kw):
2196 """Create text with coordinates x1,y1."""
2197 return self._create('text', args, kw)
2198 def create_window(self, *args, **kw):
2199 """Create window with coordinates x1,y1,x2,y2."""
2200 return self._create('window', args, kw)
2201 def dchars(self, *args):
2202 """Delete characters of text items identified by tag or id in ARGS (possibly
2203 several times) from FIRST to LAST character (including)."""
2204 self.tk.call((self._w, 'dchars') + args)
2205 def delete(self, *args):
2206 """Delete items identified by all tag or ids contained in ARGS."""
2207 self.tk.call((self._w, 'delete') + args)
2208 def dtag(self, *args):
2209 """Delete tag or id given as last arguments in ARGS from items
2210 identified by first argument in ARGS."""
2211 self.tk.call((self._w, 'dtag') + args)
2212 def find(self, *args):
2213 """Internal function."""
2214 return self._getints(
2215 self.tk.call((self._w, 'find') + args)) or ()
2216 def find_above(self, tagOrId):
2217 """Return items above TAGORID."""
2218 return self.find('above', tagOrId)
2219 def find_all(self):
2220 """Return all items."""
2221 return self.find('all')
2222 def find_below(self, tagOrId):
2223 """Return all items below TAGORID."""
2224 return self.find('below', tagOrId)
2225 def find_closest(self, x, y, halo=None, start=None):
2226 """Return item which is closest to pixel at X, Y.
2227 If several match take the top-most.
2228 All items closer than HALO are considered overlapping (all are
2229 closests). If START is specified the next below this tag is taken."""
2230 return self.find('closest', x, y, halo, start)
2231 def find_enclosed(self, x1, y1, x2, y2):
2232 """Return all items in rectangle defined
2233 by X1,Y1,X2,Y2."""
2234 return self.find('enclosed', x1, y1, x2, y2)
2235 def find_overlapping(self, x1, y1, x2, y2):
2236 """Return all items which overlap the rectangle
2237 defined by X1,Y1,X2,Y2."""
2238 return self.find('overlapping', x1, y1, x2, y2)
2239 def find_withtag(self, tagOrId):
2240 """Return all items with TAGORID."""
2241 return self.find('withtag', tagOrId)
2242 def focus(self, *args):
2243 """Set focus to the first item specified in ARGS."""
2244 return self.tk.call((self._w, 'focus') + args)
2245 def gettags(self, *args):
2246 """Return tags associated with the first item specified in ARGS."""
2247 return self.tk.splitlist(
2248 self.tk.call((self._w, 'gettags') + args))
2249 def icursor(self, *args):
2250 """Set cursor at position POS in the item identified by TAGORID.
2251 In ARGS TAGORID must be first."""
2252 self.tk.call((self._w, 'icursor') + args)
2253 def index(self, *args):
2254 """Return position of cursor as integer in item specified in ARGS."""
2255 return getint(self.tk.call((self._w, 'index') + args))
2256 def insert(self, *args):
2257 """Insert TEXT in item TAGORID at position POS. ARGS must
2258 be TAGORID POS TEXT."""
2259 self.tk.call((self._w, 'insert') + args)
2260 def itemcget(self, tagOrId, option):
2261 """Return the resource value for an OPTION for item TAGORID."""
2262 return self.tk.call(
2263 (self._w, 'itemcget') + (tagOrId, '-'+option))
2264 def itemconfigure(self, tagOrId, cnf=None, **kw):
2265 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002266
Fredrik Lundh06d28152000-08-09 18:03:12 +00002267 The values for resources are specified as keyword
2268 arguments. To get an overview about
2269 the allowed keyword arguments call the method without arguments.
2270 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002271 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002272 itemconfig = itemconfigure
2273 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2274 # so the preferred name for them is tag_lower, tag_raise
2275 # (similar to tag_bind, and similar to the Text widget);
2276 # unfortunately can't delete the old ones yet (maybe in 1.6)
2277 def tag_lower(self, *args):
2278 """Lower an item TAGORID given in ARGS
2279 (optional below another item)."""
2280 self.tk.call((self._w, 'lower') + args)
2281 lower = tag_lower
2282 def move(self, *args):
2283 """Move an item TAGORID given in ARGS."""
2284 self.tk.call((self._w, 'move') + args)
2285 def postscript(self, cnf={}, **kw):
2286 """Print the contents of the canvas to a postscript
2287 file. Valid options: colormap, colormode, file, fontmap,
2288 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2289 rotate, witdh, x, y."""
2290 return self.tk.call((self._w, 'postscript') +
2291 self._options(cnf, kw))
2292 def tag_raise(self, *args):
2293 """Raise an item TAGORID given in ARGS
2294 (optional above another item)."""
2295 self.tk.call((self._w, 'raise') + args)
2296 lift = tkraise = tag_raise
2297 def scale(self, *args):
2298 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2299 self.tk.call((self._w, 'scale') + args)
2300 def scan_mark(self, x, y):
2301 """Remember the current X, Y coordinates."""
2302 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002303 def scan_dragto(self, x, y, gain=10):
2304 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002305 difference between X and Y and the coordinates given in
2306 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002307 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002308 def select_adjust(self, tagOrId, index):
2309 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2310 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2311 def select_clear(self):
2312 """Clear the selection if it is in this widget."""
2313 self.tk.call(self._w, 'select', 'clear')
2314 def select_from(self, tagOrId, index):
2315 """Set the fixed end of a selection in item TAGORID to INDEX."""
2316 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2317 def select_item(self):
2318 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002319 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002320 def select_to(self, tagOrId, index):
2321 """Set the variable end of a selection in item TAGORID to INDEX."""
2322 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2323 def type(self, tagOrId):
2324 """Return the type of the item TAGORID."""
2325 return self.tk.call(self._w, 'type', tagOrId) or None
Guido van Rossum18468821994-06-20 07:49:28 +00002326
2327class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002328 """Checkbutton widget which is either in on- or off-state."""
2329 def __init__(self, master=None, cnf={}, **kw):
2330 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002331
Fredrik Lundh06d28152000-08-09 18:03:12 +00002332 Valid resource names: activebackground, activeforeground, anchor,
2333 background, bd, bg, bitmap, borderwidth, command, cursor,
2334 disabledforeground, fg, font, foreground, height,
2335 highlightbackground, highlightcolor, highlightthickness, image,
2336 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2337 selectcolor, selectimage, state, takefocus, text, textvariable,
2338 underline, variable, width, wraplength."""
2339 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2340 def deselect(self):
2341 """Put the button in off-state."""
2342 self.tk.call(self._w, 'deselect')
2343 def flash(self):
2344 """Flash the button."""
2345 self.tk.call(self._w, 'flash')
2346 def invoke(self):
2347 """Toggle the button and invoke a command if given as resource."""
2348 return self.tk.call(self._w, 'invoke')
2349 def select(self):
2350 """Put the button in on-state."""
2351 self.tk.call(self._w, 'select')
2352 def toggle(self):
2353 """Toggle the button."""
2354 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002355
Guilherme Polo1fff0082009-08-14 15:05:30 +00002356class Entry(Widget, XView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002357 """Entry widget which allows to display simple text."""
2358 def __init__(self, master=None, cnf={}, **kw):
2359 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002360
Fredrik Lundh06d28152000-08-09 18:03:12 +00002361 Valid resource names: background, bd, bg, borderwidth, cursor,
2362 exportselection, fg, font, foreground, highlightbackground,
2363 highlightcolor, highlightthickness, insertbackground,
2364 insertborderwidth, insertofftime, insertontime, insertwidth,
2365 invalidcommand, invcmd, justify, relief, selectbackground,
2366 selectborderwidth, selectforeground, show, state, takefocus,
2367 textvariable, validate, validatecommand, vcmd, width,
2368 xscrollcommand."""
2369 Widget.__init__(self, master, 'entry', cnf, kw)
2370 def delete(self, first, last=None):
2371 """Delete text from FIRST to LAST (not included)."""
2372 self.tk.call(self._w, 'delete', first, last)
2373 def get(self):
2374 """Return the text."""
2375 return self.tk.call(self._w, 'get')
2376 def icursor(self, index):
2377 """Insert cursor at INDEX."""
2378 self.tk.call(self._w, 'icursor', index)
2379 def index(self, index):
2380 """Return position of cursor."""
2381 return getint(self.tk.call(
2382 self._w, 'index', index))
2383 def insert(self, index, string):
2384 """Insert STRING at INDEX."""
2385 self.tk.call(self._w, 'insert', index, string)
2386 def scan_mark(self, x):
2387 """Remember the current X, Y coordinates."""
2388 self.tk.call(self._w, 'scan', 'mark', x)
2389 def scan_dragto(self, x):
2390 """Adjust the view of the canvas to 10 times the
2391 difference between X and Y and the coordinates given in
2392 scan_mark."""
2393 self.tk.call(self._w, 'scan', 'dragto', x)
2394 def selection_adjust(self, index):
2395 """Adjust the end of the selection near the cursor to INDEX."""
2396 self.tk.call(self._w, 'selection', 'adjust', index)
2397 select_adjust = selection_adjust
2398 def selection_clear(self):
2399 """Clear the selection if it is in this widget."""
2400 self.tk.call(self._w, 'selection', 'clear')
2401 select_clear = selection_clear
2402 def selection_from(self, index):
2403 """Set the fixed end of a selection to INDEX."""
2404 self.tk.call(self._w, 'selection', 'from', index)
2405 select_from = selection_from
2406 def selection_present(self):
Guilherme Polo1fff0082009-08-14 15:05:30 +00002407 """Return True if there are characters selected in the entry, False
2408 otherwise."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002409 return self.tk.getboolean(
2410 self.tk.call(self._w, 'selection', 'present'))
2411 select_present = selection_present
2412 def selection_range(self, start, end):
2413 """Set the selection from START to END (not included)."""
2414 self.tk.call(self._w, 'selection', 'range', start, end)
2415 select_range = selection_range
2416 def selection_to(self, index):
2417 """Set the variable end of a selection to INDEX."""
2418 self.tk.call(self._w, 'selection', 'to', index)
2419 select_to = selection_to
Guido van Rossum18468821994-06-20 07:49:28 +00002420
2421class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002422 """Frame widget which may contain other widgets and can have a 3D border."""
2423 def __init__(self, master=None, cnf={}, **kw):
2424 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002425
Fredrik Lundh06d28152000-08-09 18:03:12 +00002426 Valid resource names: background, bd, bg, borderwidth, class,
2427 colormap, container, cursor, height, highlightbackground,
2428 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2429 cnf = _cnfmerge((cnf, kw))
2430 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002431 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002432 extra = ('-class', cnf['class_'])
2433 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002434 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002435 extra = ('-class', cnf['class'])
2436 del cnf['class']
2437 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002438
2439class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002440 """Label widget which can display text and bitmaps."""
2441 def __init__(self, master=None, cnf={}, **kw):
2442 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002443
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002444 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002445
2446 activebackground, activeforeground, anchor,
2447 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002448 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002449 highlightbackground, highlightcolor,
2450 highlightthickness, image, justify,
2451 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002452 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002453
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002454 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002455
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002456 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002457
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002458 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002459 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002460
Guilherme Polo1fff0082009-08-14 15:05:30 +00002461class Listbox(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002462 """Listbox widget which can display a list of strings."""
2463 def __init__(self, master=None, cnf={}, **kw):
2464 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002465
Fredrik Lundh06d28152000-08-09 18:03:12 +00002466 Valid resource names: background, bd, bg, borderwidth, cursor,
2467 exportselection, fg, font, foreground, height, highlightbackground,
2468 highlightcolor, highlightthickness, relief, selectbackground,
2469 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2470 width, xscrollcommand, yscrollcommand, listvariable."""
2471 Widget.__init__(self, master, 'listbox', cnf, kw)
2472 def activate(self, index):
2473 """Activate item identified by INDEX."""
2474 self.tk.call(self._w, 'activate', index)
2475 def bbox(self, *args):
2476 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2477 which encloses the item identified by index in ARGS."""
2478 return self._getints(
2479 self.tk.call((self._w, 'bbox') + args)) or None
2480 def curselection(self):
2481 """Return list of indices of currently selected item."""
2482 # XXX Ought to apply self._getints()...
2483 return self.tk.splitlist(self.tk.call(
2484 self._w, 'curselection'))
2485 def delete(self, first, last=None):
2486 """Delete items from FIRST to LAST (not included)."""
2487 self.tk.call(self._w, 'delete', first, last)
2488 def get(self, first, last=None):
2489 """Get list of items from FIRST to LAST (not included)."""
2490 if last:
2491 return self.tk.splitlist(self.tk.call(
2492 self._w, 'get', first, last))
2493 else:
2494 return self.tk.call(self._w, 'get', first)
2495 def index(self, index):
2496 """Return index of item identified with INDEX."""
2497 i = self.tk.call(self._w, 'index', index)
2498 if i == 'none': return None
2499 return getint(i)
2500 def insert(self, index, *elements):
2501 """Insert ELEMENTS at INDEX."""
2502 self.tk.call((self._w, 'insert', index) + elements)
2503 def nearest(self, y):
2504 """Get index of item which is nearest to y coordinate Y."""
2505 return getint(self.tk.call(
2506 self._w, 'nearest', y))
2507 def scan_mark(self, x, y):
2508 """Remember the current X, Y coordinates."""
2509 self.tk.call(self._w, 'scan', 'mark', x, y)
2510 def scan_dragto(self, x, y):
2511 """Adjust the view of the listbox to 10 times the
2512 difference between X and Y and the coordinates given in
2513 scan_mark."""
2514 self.tk.call(self._w, 'scan', 'dragto', x, y)
2515 def see(self, index):
2516 """Scroll such that INDEX is visible."""
2517 self.tk.call(self._w, 'see', index)
2518 def selection_anchor(self, index):
2519 """Set the fixed end oft the selection to INDEX."""
2520 self.tk.call(self._w, 'selection', 'anchor', index)
2521 select_anchor = selection_anchor
2522 def selection_clear(self, first, last=None):
2523 """Clear the selection from FIRST to LAST (not included)."""
2524 self.tk.call(self._w,
2525 'selection', 'clear', first, last)
2526 select_clear = selection_clear
2527 def selection_includes(self, index):
2528 """Return 1 if INDEX is part of the selection."""
2529 return self.tk.getboolean(self.tk.call(
2530 self._w, 'selection', 'includes', index))
2531 select_includes = selection_includes
2532 def selection_set(self, first, last=None):
2533 """Set the selection from FIRST to LAST (not included) without
2534 changing the currently selected elements."""
2535 self.tk.call(self._w, 'selection', 'set', first, last)
2536 select_set = selection_set
2537 def size(self):
2538 """Return the number of elements in the listbox."""
2539 return getint(self.tk.call(self._w, 'size'))
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002540 def itemcget(self, index, option):
2541 """Return the resource value for an ITEM and an OPTION."""
2542 return self.tk.call(
2543 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002544 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002545 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002546
2547 The values for resources are specified as keyword arguments.
2548 To get an overview about the allowed keyword arguments
2549 call the method without arguments.
2550 Valid resource names: background, bg, foreground, fg,
2551 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002552 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002553 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002554
2555class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002556 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2557 def __init__(self, master=None, cnf={}, **kw):
2558 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002559
Fredrik Lundh06d28152000-08-09 18:03:12 +00002560 Valid resource names: activebackground, activeborderwidth,
2561 activeforeground, background, bd, bg, borderwidth, cursor,
2562 disabledforeground, fg, font, foreground, postcommand, relief,
2563 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2564 Widget.__init__(self, master, 'menu', cnf, kw)
2565 def tk_bindForTraversal(self):
2566 pass # obsolete since Tk 4.0
2567 def tk_mbPost(self):
2568 self.tk.call('tk_mbPost', self._w)
2569 def tk_mbUnpost(self):
2570 self.tk.call('tk_mbUnpost')
2571 def tk_traverseToMenu(self, char):
2572 self.tk.call('tk_traverseToMenu', self._w, char)
2573 def tk_traverseWithinMenu(self, char):
2574 self.tk.call('tk_traverseWithinMenu', self._w, char)
2575 def tk_getMenuButtons(self):
2576 return self.tk.call('tk_getMenuButtons', self._w)
2577 def tk_nextMenu(self, count):
2578 self.tk.call('tk_nextMenu', count)
2579 def tk_nextMenuEntry(self, count):
2580 self.tk.call('tk_nextMenuEntry', count)
2581 def tk_invokeMenu(self):
2582 self.tk.call('tk_invokeMenu', self._w)
2583 def tk_firstMenu(self):
2584 self.tk.call('tk_firstMenu', self._w)
2585 def tk_mbButtonDown(self):
2586 self.tk.call('tk_mbButtonDown', self._w)
2587 def tk_popup(self, x, y, entry=""):
2588 """Post the menu at position X,Y with entry ENTRY."""
2589 self.tk.call('tk_popup', self._w, x, y, entry)
2590 def activate(self, index):
2591 """Activate entry at INDEX."""
2592 self.tk.call(self._w, 'activate', index)
2593 def add(self, itemType, cnf={}, **kw):
2594 """Internal function."""
2595 self.tk.call((self._w, 'add', itemType) +
2596 self._options(cnf, kw))
2597 def add_cascade(self, cnf={}, **kw):
2598 """Add hierarchical menu item."""
2599 self.add('cascade', cnf or kw)
2600 def add_checkbutton(self, cnf={}, **kw):
2601 """Add checkbutton menu item."""
2602 self.add('checkbutton', cnf or kw)
2603 def add_command(self, cnf={}, **kw):
2604 """Add command menu item."""
2605 self.add('command', cnf or kw)
2606 def add_radiobutton(self, cnf={}, **kw):
2607 """Addd radio menu item."""
2608 self.add('radiobutton', cnf or kw)
2609 def add_separator(self, cnf={}, **kw):
2610 """Add separator."""
2611 self.add('separator', cnf or kw)
2612 def insert(self, index, itemType, cnf={}, **kw):
2613 """Internal function."""
2614 self.tk.call((self._w, 'insert', index, itemType) +
2615 self._options(cnf, kw))
2616 def insert_cascade(self, index, cnf={}, **kw):
2617 """Add hierarchical menu item at INDEX."""
2618 self.insert(index, 'cascade', cnf or kw)
2619 def insert_checkbutton(self, index, cnf={}, **kw):
2620 """Add checkbutton menu item at INDEX."""
2621 self.insert(index, 'checkbutton', cnf or kw)
2622 def insert_command(self, index, cnf={}, **kw):
2623 """Add command menu item at INDEX."""
2624 self.insert(index, 'command', cnf or kw)
2625 def insert_radiobutton(self, index, cnf={}, **kw):
2626 """Addd radio menu item at INDEX."""
2627 self.insert(index, 'radiobutton', cnf or kw)
2628 def insert_separator(self, index, cnf={}, **kw):
2629 """Add separator at INDEX."""
2630 self.insert(index, 'separator', cnf or kw)
2631 def delete(self, index1, index2=None):
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002632 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002633 if index2 is None:
2634 index2 = index1
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002635
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002636 num_index1, num_index2 = self.index(index1), self.index(index2)
2637 if (num_index1 is None) or (num_index2 is None):
2638 num_index1, num_index2 = 0, -1
2639
2640 for i in range(num_index1, num_index2 + 1):
2641 if 'command' in self.entryconfig(i):
2642 c = str(self.entrycget(i, 'command'))
2643 if c:
2644 self.deletecommand(c)
2645 self.tk.call(self._w, 'delete', index1, index2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002646 def entrycget(self, index, option):
2647 """Return the resource value of an menu item for OPTION at INDEX."""
2648 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2649 def entryconfigure(self, index, cnf=None, **kw):
2650 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002651 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002652 entryconfig = entryconfigure
2653 def index(self, index):
2654 """Return the index of a menu item identified by INDEX."""
2655 i = self.tk.call(self._w, 'index', index)
2656 if i == 'none': return None
2657 return getint(i)
2658 def invoke(self, index):
2659 """Invoke a menu item identified by INDEX and execute
2660 the associated command."""
2661 return self.tk.call(self._w, 'invoke', index)
2662 def post(self, x, y):
2663 """Display a menu at position X,Y."""
2664 self.tk.call(self._w, 'post', x, y)
2665 def type(self, index):
2666 """Return the type of the menu item at INDEX."""
2667 return self.tk.call(self._w, 'type', index)
2668 def unpost(self):
2669 """Unmap a menu."""
2670 self.tk.call(self._w, 'unpost')
2671 def yposition(self, index):
2672 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2673 return getint(self.tk.call(
2674 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002675
2676class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002677 """Menubutton widget, obsolete since Tk8.0."""
2678 def __init__(self, master=None, cnf={}, **kw):
2679 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002680
2681class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002682 """Message widget to display multiline text. Obsolete since Label does it too."""
2683 def __init__(self, master=None, cnf={}, **kw):
2684 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002685
2686class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002687 """Radiobutton widget which shows only one of several buttons in on-state."""
2688 def __init__(self, master=None, cnf={}, **kw):
2689 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002690
Fredrik Lundh06d28152000-08-09 18:03:12 +00002691 Valid resource names: activebackground, activeforeground, anchor,
2692 background, bd, bg, bitmap, borderwidth, command, cursor,
2693 disabledforeground, fg, font, foreground, height,
2694 highlightbackground, highlightcolor, highlightthickness, image,
2695 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2696 state, takefocus, text, textvariable, underline, value, variable,
2697 width, wraplength."""
2698 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2699 def deselect(self):
2700 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002701
Fredrik Lundh06d28152000-08-09 18:03:12 +00002702 self.tk.call(self._w, 'deselect')
2703 def flash(self):
2704 """Flash the button."""
2705 self.tk.call(self._w, 'flash')
2706 def invoke(self):
2707 """Toggle the button and invoke a command if given as resource."""
2708 return self.tk.call(self._w, 'invoke')
2709 def select(self):
2710 """Put the button in on-state."""
2711 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002712
2713class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002714 """Scale widget which can display a numerical scale."""
2715 def __init__(self, master=None, cnf={}, **kw):
2716 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002717
Fredrik Lundh06d28152000-08-09 18:03:12 +00002718 Valid resource names: activebackground, background, bigincrement, bd,
2719 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2720 highlightbackground, highlightcolor, highlightthickness, label,
2721 length, orient, relief, repeatdelay, repeatinterval, resolution,
2722 showvalue, sliderlength, sliderrelief, state, takefocus,
2723 tickinterval, to, troughcolor, variable, width."""
2724 Widget.__init__(self, master, 'scale', cnf, kw)
2725 def get(self):
2726 """Get the current value as integer or float."""
2727 value = self.tk.call(self._w, 'get')
2728 try:
2729 return getint(value)
2730 except ValueError:
2731 return getdouble(value)
2732 def set(self, value):
2733 """Set the value to VALUE."""
2734 self.tk.call(self._w, 'set', value)
2735 def coords(self, value=None):
2736 """Return a tuple (X,Y) of the point along the centerline of the
2737 trough that corresponds to VALUE or the current value if None is
2738 given."""
2739
2740 return self._getints(self.tk.call(self._w, 'coords', value))
2741 def identify(self, x, y):
2742 """Return where the point X,Y lies. Valid return values are "slider",
2743 "though1" and "though2"."""
2744 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002745
2746class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002747 """Scrollbar widget which displays a slider at a certain position."""
2748 def __init__(self, master=None, cnf={}, **kw):
2749 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002750
Fredrik Lundh06d28152000-08-09 18:03:12 +00002751 Valid resource names: activebackground, activerelief,
2752 background, bd, bg, borderwidth, command, cursor,
2753 elementborderwidth, highlightbackground,
2754 highlightcolor, highlightthickness, jump, orient,
2755 relief, repeatdelay, repeatinterval, takefocus,
2756 troughcolor, width."""
2757 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2758 def activate(self, index):
2759 """Display the element at INDEX with activebackground and activerelief.
2760 INDEX can be "arrow1","slider" or "arrow2"."""
2761 self.tk.call(self._w, 'activate', index)
2762 def delta(self, deltax, deltay):
2763 """Return the fractional change of the scrollbar setting if it
2764 would be moved by DELTAX or DELTAY pixels."""
2765 return getdouble(
2766 self.tk.call(self._w, 'delta', deltax, deltay))
2767 def fraction(self, x, y):
2768 """Return the fractional value which corresponds to a slider
2769 position of X,Y."""
2770 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2771 def identify(self, x, y):
2772 """Return the element under position X,Y as one of
2773 "arrow1","slider","arrow2" or ""."""
2774 return self.tk.call(self._w, 'identify', x, y)
2775 def get(self):
2776 """Return the current fractional values (upper and lower end)
2777 of the slider position."""
2778 return self._getdoubles(self.tk.call(self._w, 'get'))
2779 def set(self, *args):
2780 """Set the fractional values of the slider position (upper and
2781 lower ends as value between 0 and 1)."""
2782 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002783
2784
2785
Guilherme Polo1fff0082009-08-14 15:05:30 +00002786class Text(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002787 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002788 def __init__(self, master=None, cnf={}, **kw):
2789 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002790
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002791 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002792
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002793 background, borderwidth, cursor,
2794 exportselection, font, foreground,
2795 highlightbackground, highlightcolor,
2796 highlightthickness, insertbackground,
2797 insertborderwidth, insertofftime,
2798 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002799 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002800 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002801 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002802 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002803
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002804 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002805
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002806 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002807 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002808 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002809
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002810 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002811 Widget.__init__(self, master, 'text', cnf, kw)
2812 def bbox(self, *args):
2813 """Return a tuple of (x,y,width,height) which gives the bounding
2814 box of the visible part of the character at the index in ARGS."""
2815 return self._getints(
2816 self.tk.call((self._w, 'bbox') + args)) or None
2817 def tk_textSelectTo(self, index):
2818 self.tk.call('tk_textSelectTo', self._w, index)
2819 def tk_textBackspace(self):
2820 self.tk.call('tk_textBackspace', self._w)
2821 def tk_textIndexCloser(self, a, b, c):
2822 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2823 def tk_textResetAnchor(self, index):
2824 self.tk.call('tk_textResetAnchor', self._w, index)
2825 def compare(self, index1, op, index2):
2826 """Return whether between index INDEX1 and index INDEX2 the
2827 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2828 return self.tk.getboolean(self.tk.call(
2829 self._w, 'compare', index1, op, index2))
2830 def debug(self, boolean=None):
2831 """Turn on the internal consistency checks of the B-Tree inside the text
2832 widget according to BOOLEAN."""
2833 return self.tk.getboolean(self.tk.call(
2834 self._w, 'debug', boolean))
2835 def delete(self, index1, index2=None):
2836 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2837 self.tk.call(self._w, 'delete', index1, index2)
2838 def dlineinfo(self, index):
2839 """Return tuple (x,y,width,height,baseline) giving the bounding box
2840 and baseline position of the visible part of the line containing
2841 the character at INDEX."""
2842 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002843 def dump(self, index1, index2=None, command=None, **kw):
2844 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002845
Guido van Rossum256705b2002-04-23 13:29:43 +00002846 The type of contents returned in filtered based on the keyword
2847 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2848 given and true, then the corresponding items are returned. The result
2849 is a list of triples of the form (key, value, index). If none of the
2850 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002851
Guido van Rossum256705b2002-04-23 13:29:43 +00002852 If the 'command' argument is given, it is called once for each element
2853 of the list of triples, with the values of each triple serving as the
2854 arguments to the function. In this case the list is not returned."""
2855 args = []
2856 func_name = None
2857 result = None
2858 if not command:
2859 # Never call the dump command without the -command flag, since the
2860 # output could involve Tcl quoting and would be a pain to parse
2861 # right. Instead just set the command to build a list of triples
2862 # as if we had done the parsing.
2863 result = []
2864 def append_triple(key, value, index, result=result):
2865 result.append((key, value, index))
2866 command = append_triple
2867 try:
2868 if not isinstance(command, str):
2869 func_name = command = self._register(command)
2870 args += ["-command", command]
2871 for key in kw:
2872 if kw[key]: args.append("-" + key)
2873 args.append(index1)
2874 if index2:
2875 args.append(index2)
2876 self.tk.call(self._w, "dump", *args)
2877 return result
2878 finally:
2879 if func_name:
2880 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002881
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002882 ## new in tk8.4
2883 def edit(self, *args):
2884 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002885
2886 This method controls the undo mechanism and
2887 the modified flag. The exact behavior of the
2888 command depends on the option argument that
2889 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002890 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002891
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002892 edit_modified, edit_redo, edit_reset, edit_separator
2893 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002894
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002895 """
Georg Brandlb533e262008-05-25 18:19:30 +00002896 return self.tk.call(self._w, 'edit', *args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002897
2898 def edit_modified(self, arg=None):
2899 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002900
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002901 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002902 flag of the widget. The insert, delete, edit undo and
2903 edit redo commands or the user can set or clear the
2904 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002905 modified flag of the widget to arg.
2906 """
2907 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002908
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002909 def edit_redo(self):
2910 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002911
2912 When the undo option is true, reapplies the last
2913 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002914 then. Generates an error when the redo stack is empty.
2915 Does nothing when the undo option is false.
2916 """
2917 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002918
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002919 def edit_reset(self):
2920 """Clears the undo and redo stacks
2921 """
2922 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002923
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002924 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002925 """Inserts a separator (boundary) on the undo stack.
2926
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002927 Does nothing when the undo option is false
2928 """
2929 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002930
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002931 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002932 """Undoes the last edit action
2933
2934 If the undo option is true. An edit action is defined
2935 as all the insert and delete commands that are recorded
2936 on the undo stack in between two separators. Generates
2937 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002938 when the undo option is false
2939 """
2940 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00002941
Fredrik Lundh06d28152000-08-09 18:03:12 +00002942 def get(self, index1, index2=None):
2943 """Return the text from INDEX1 to INDEX2 (not included)."""
2944 return self.tk.call(self._w, 'get', index1, index2)
2945 # (Image commands are new in 8.0)
2946 def image_cget(self, index, option):
2947 """Return the value of OPTION of an embedded image at INDEX."""
2948 if option[:1] != "-":
2949 option = "-" + option
2950 if option[-1:] == "_":
2951 option = option[:-1]
2952 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002953 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002954 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002955 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002956 def image_create(self, index, cnf={}, **kw):
2957 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00002958 return self.tk.call(
2959 self._w, "image", "create", index,
2960 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002961 def image_names(self):
2962 """Return all names of embedded images in this widget."""
2963 return self.tk.call(self._w, "image", "names")
2964 def index(self, index):
2965 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00002966 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002967 def insert(self, index, chars, *args):
2968 """Insert CHARS before the characters at INDEX. An additional
2969 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
2970 self.tk.call((self._w, 'insert', index, chars) + args)
2971 def mark_gravity(self, markName, direction=None):
2972 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2973 Return the current value if None is given for DIRECTION."""
2974 return self.tk.call(
2975 (self._w, 'mark', 'gravity', markName, direction))
2976 def mark_names(self):
2977 """Return all mark names."""
2978 return self.tk.splitlist(self.tk.call(
2979 self._w, 'mark', 'names'))
2980 def mark_set(self, markName, index):
2981 """Set mark MARKNAME before the character at INDEX."""
2982 self.tk.call(self._w, 'mark', 'set', markName, index)
2983 def mark_unset(self, *markNames):
2984 """Delete all marks in MARKNAMES."""
2985 self.tk.call((self._w, 'mark', 'unset') + markNames)
2986 def mark_next(self, index):
2987 """Return the name of the next mark after INDEX."""
2988 return self.tk.call(self._w, 'mark', 'next', index) or None
2989 def mark_previous(self, index):
2990 """Return the name of the previous mark before INDEX."""
2991 return self.tk.call(self._w, 'mark', 'previous', index) or None
2992 def scan_mark(self, x, y):
2993 """Remember the current X, Y coordinates."""
2994 self.tk.call(self._w, 'scan', 'mark', x, y)
2995 def scan_dragto(self, x, y):
2996 """Adjust the view of the text to 10 times the
2997 difference between X and Y and the coordinates given in
2998 scan_mark."""
2999 self.tk.call(self._w, 'scan', 'dragto', x, y)
3000 def search(self, pattern, index, stopindex=None,
3001 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003002 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003003 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Poloae098992009-02-09 16:44:24 +00003004 Return the index of the first character of a match or an
3005 empty string."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00003006 args = [self._w, 'search']
3007 if forwards: args.append('-forwards')
3008 if backwards: args.append('-backwards')
3009 if exact: args.append('-exact')
3010 if regexp: args.append('-regexp')
3011 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003012 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003013 if count: args.append('-count'); args.append(count)
Guilherme Poloae098992009-02-09 16:44:24 +00003014 if pattern and pattern[0] == '-': args.append('--')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003015 args.append(pattern)
3016 args.append(index)
3017 if stopindex: args.append(stopindex)
Guilherme Polo56f5be52009-03-07 01:54:57 +00003018 return str(self.tk.call(tuple(args)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003019 def see(self, index):
3020 """Scroll such that the character at INDEX is visible."""
3021 self.tk.call(self._w, 'see', index)
3022 def tag_add(self, tagName, index1, *args):
3023 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3024 Additional pairs of indices may follow in ARGS."""
3025 self.tk.call(
3026 (self._w, 'tag', 'add', tagName, index1) + args)
3027 def tag_unbind(self, tagName, sequence, funcid=None):
3028 """Unbind for all characters with TAGNAME for event SEQUENCE the
3029 function identified with FUNCID."""
3030 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3031 if funcid:
3032 self.deletecommand(funcid)
3033 def tag_bind(self, tagName, sequence, func, add=None):
3034 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003035
Fredrik Lundh06d28152000-08-09 18:03:12 +00003036 An additional boolean parameter ADD specifies whether FUNC will be
3037 called additionally to the other bound function or whether it will
3038 replace the previous function. See bind for the return value."""
3039 return self._bind((self._w, 'tag', 'bind', tagName),
3040 sequence, func, add)
3041 def tag_cget(self, tagName, option):
3042 """Return the value of OPTION for tag TAGNAME."""
3043 if option[:1] != '-':
3044 option = '-' + option
3045 if option[-1:] == '_':
3046 option = option[:-1]
3047 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003048 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003049 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003050 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003051 tag_config = tag_configure
3052 def tag_delete(self, *tagNames):
3053 """Delete all tags in TAGNAMES."""
3054 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3055 def tag_lower(self, tagName, belowThis=None):
3056 """Change the priority of tag TAGNAME such that it is lower
3057 than the priority of BELOWTHIS."""
3058 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3059 def tag_names(self, index=None):
3060 """Return a list of all tag names."""
3061 return self.tk.splitlist(
3062 self.tk.call(self._w, 'tag', 'names', index))
3063 def tag_nextrange(self, tagName, index1, index2=None):
3064 """Return a list of start and end index for the first sequence of
3065 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3066 The text is searched forward from INDEX1."""
3067 return self.tk.splitlist(self.tk.call(
3068 self._w, 'tag', 'nextrange', tagName, index1, index2))
3069 def tag_prevrange(self, tagName, index1, index2=None):
3070 """Return a list of start and end index for the first sequence of
3071 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3072 The text is searched backwards from INDEX1."""
3073 return self.tk.splitlist(self.tk.call(
3074 self._w, 'tag', 'prevrange', tagName, index1, index2))
3075 def tag_raise(self, tagName, aboveThis=None):
3076 """Change the priority of tag TAGNAME such that it is higher
3077 than the priority of ABOVETHIS."""
3078 self.tk.call(
3079 self._w, 'tag', 'raise', tagName, aboveThis)
3080 def tag_ranges(self, tagName):
3081 """Return a list of ranges of text which have tag TAGNAME."""
3082 return self.tk.splitlist(self.tk.call(
3083 self._w, 'tag', 'ranges', tagName))
3084 def tag_remove(self, tagName, index1, index2=None):
3085 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3086 self.tk.call(
3087 self._w, 'tag', 'remove', tagName, index1, index2)
3088 def window_cget(self, index, option):
3089 """Return the value of OPTION of an embedded window at INDEX."""
3090 if option[:1] != '-':
3091 option = '-' + option
3092 if option[-1:] == '_':
3093 option = option[:-1]
3094 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003095 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003096 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003097 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003098 window_config = window_configure
3099 def window_create(self, index, cnf={}, **kw):
3100 """Create a window at INDEX."""
3101 self.tk.call(
3102 (self._w, 'window', 'create', index)
3103 + self._options(cnf, kw))
3104 def window_names(self):
3105 """Return all names of embedded windows in this widget."""
3106 return self.tk.splitlist(
3107 self.tk.call(self._w, 'window', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003108 def yview_pickplace(self, *what):
3109 """Obsolete function, use see."""
3110 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003111
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003112
Guido van Rossum28574b51996-10-21 15:16:51 +00003113class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003114 """Internal class. It wraps the command in the widget OptionMenu."""
3115 def __init__(self, var, value, callback=None):
3116 self.__value = value
3117 self.__var = var
3118 self.__callback = callback
3119 def __call__(self, *args):
3120 self.__var.set(self.__value)
3121 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003122 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003123
3124class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003125 """OptionMenu which allows the user to select a value from a menu."""
3126 def __init__(self, master, variable, value, *values, **kwargs):
3127 """Construct an optionmenu widget with the parent MASTER, with
3128 the resource textvariable set to VARIABLE, the initially selected
3129 value VALUE, the other menu values VALUES and an additional
3130 keyword argument command."""
3131 kw = {"borderwidth": 2, "textvariable": variable,
3132 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3133 "highlightthickness": 2}
3134 Widget.__init__(self, master, "menubutton", kw)
3135 self.widgetName = 'tk_optionMenu'
3136 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3137 self.menuname = menu._w
3138 # 'command' is the only supported keyword
3139 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003140 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003141 del kwargs['command']
3142 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003143 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003144 menu.add_command(label=value,
3145 command=_setit(variable, value, callback))
3146 for v in values:
3147 menu.add_command(label=v,
3148 command=_setit(variable, v, callback))
3149 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003150
Fredrik Lundh06d28152000-08-09 18:03:12 +00003151 def __getitem__(self, name):
3152 if name == 'menu':
3153 return self.__menu
3154 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003155
Fredrik Lundh06d28152000-08-09 18:03:12 +00003156 def destroy(self):
3157 """Destroy this widget and the associated menu."""
3158 Menubutton.destroy(self)
3159 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003160
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003161class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003162 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003163 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003164 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3165 self.name = None
3166 if not master:
3167 master = _default_root
3168 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003169 raise RuntimeError('Too early to create image')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003170 self.tk = master.tk
3171 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003172 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003173 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003174 # The following is needed for systems where id(x)
3175 # can return a negative number, such as Linux/m68k:
3176 if name[0] == '-': name = '_' + name[1:]
3177 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3178 elif kw: cnf = kw
3179 options = ()
3180 for k, v in cnf.items():
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003181 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003182 v = self._register(v)
3183 options = options + ('-'+k, v)
3184 self.tk.call(('image', 'create', imgtype, name,) + options)
3185 self.name = name
3186 def __str__(self): return self.name
3187 def __del__(self):
3188 if self.name:
3189 try:
3190 self.tk.call('image', 'delete', self.name)
3191 except TclError:
3192 # May happen if the root was destroyed
3193 pass
3194 def __setitem__(self, key, value):
3195 self.tk.call(self.name, 'configure', '-'+key, value)
3196 def __getitem__(self, key):
3197 return self.tk.call(self.name, 'configure', '-'+key)
3198 def configure(self, **kw):
3199 """Configure the image."""
3200 res = ()
3201 for k, v in _cnfmerge(kw).items():
3202 if v is not None:
3203 if k[-1] == '_': k = k[:-1]
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003204 if hasattr(v, '__call__'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003205 v = self._register(v)
3206 res = res + ('-'+k, v)
3207 self.tk.call((self.name, 'config') + res)
3208 config = configure
3209 def height(self):
3210 """Return the height of the image."""
3211 return getint(
3212 self.tk.call('image', 'height', self.name))
3213 def type(self):
3214 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3215 return self.tk.call('image', 'type', self.name)
3216 def width(self):
3217 """Return the width of the image."""
3218 return getint(
3219 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003220
3221class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003222 """Widget which can display colored images in GIF, PPM/PGM format."""
3223 def __init__(self, name=None, cnf={}, master=None, **kw):
3224 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003225
Fredrik Lundh06d28152000-08-09 18:03:12 +00003226 Valid resource names: data, format, file, gamma, height, palette,
3227 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003228 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003229 def blank(self):
3230 """Display a transparent image."""
3231 self.tk.call(self.name, 'blank')
3232 def cget(self, option):
3233 """Return the value of OPTION."""
3234 return self.tk.call(self.name, 'cget', '-' + option)
3235 # XXX config
3236 def __getitem__(self, key):
3237 return self.tk.call(self.name, 'cget', '-' + key)
3238 # XXX copy -from, -to, ...?
3239 def copy(self):
3240 """Return a new PhotoImage with the same image as this widget."""
3241 destImage = PhotoImage()
3242 self.tk.call(destImage, 'copy', self.name)
3243 return destImage
3244 def zoom(self,x,y=''):
3245 """Return a new PhotoImage with the same image as this widget
3246 but zoom it with X and Y."""
3247 destImage = PhotoImage()
3248 if y=='': y=x
3249 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3250 return destImage
3251 def subsample(self,x,y=''):
3252 """Return a new PhotoImage based on the same image as this widget
3253 but use only every Xth or Yth pixel."""
3254 destImage = PhotoImage()
3255 if y=='': y=x
3256 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3257 return destImage
3258 def get(self, x, y):
3259 """Return the color (red, green, blue) of the pixel at X,Y."""
3260 return self.tk.call(self.name, 'get', x, y)
3261 def put(self, data, to=None):
Mark Dickinson934896d2009-02-21 20:59:32 +00003262 """Put row formatted colors to image starting from
Fredrik Lundh06d28152000-08-09 18:03:12 +00003263 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3264 args = (self.name, 'put', data)
3265 if to:
3266 if to[0] == '-to':
3267 to = to[1:]
3268 args = args + ('-to',) + tuple(to)
3269 self.tk.call(args)
3270 # XXX read
3271 def write(self, filename, format=None, from_coords=None):
3272 """Write image to file FILENAME in FORMAT starting from
3273 position FROM_COORDS."""
3274 args = (self.name, 'write', filename)
3275 if format:
3276 args = args + ('-format', format)
3277 if from_coords:
3278 args = args + ('-from',) + tuple(from_coords)
3279 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003280
3281class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003282 """Widget which can display a bitmap."""
3283 def __init__(self, name=None, cnf={}, master=None, **kw):
3284 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003285
Fredrik Lundh06d28152000-08-09 18:03:12 +00003286 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003287 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003288
3289def image_names(): return _default_root.tk.call('image', 'names')
3290def image_types(): return _default_root.tk.call('image', 'types')
3291
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003292
Guilherme Polo1fff0082009-08-14 15:05:30 +00003293class Spinbox(Widget, XView):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003294 """spinbox widget."""
3295 def __init__(self, master=None, cnf={}, **kw):
3296 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003297
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003298 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003299
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003300 activebackground, background, borderwidth,
3301 cursor, exportselection, font, foreground,
3302 highlightbackground, highlightcolor,
3303 highlightthickness, insertbackground,
3304 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003305 insertontime, insertwidth, justify, relief,
3306 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003307 selectbackground, selectborderwidth
3308 selectforeground, takefocus, textvariable
3309 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003310
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003311 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003312
3313 buttonbackground, buttoncursor,
3314 buttondownrelief, buttonuprelief,
3315 command, disabledbackground,
3316 disabledforeground, format, from,
3317 invalidcommand, increment,
3318 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003319 validate, validatecommand values,
3320 width, wrap,
3321 """
3322 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003323
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003324 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003325 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3326 rectangle which encloses the character given by index.
3327
3328 The first two elements of the list give the x and y
3329 coordinates of the upper-left corner of the screen
3330 area covered by the character (in pixels relative
3331 to the widget) and the last two elements give the
3332 width and height of the character, in pixels. The
3333 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003334 visible area of the window.
3335 """
3336 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003337
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003338 def delete(self, first, last=None):
3339 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003340
3341 First is the index of the first character to delete,
3342 and last is the index of the character just after
3343 the last one to delete. If last isn't specified it
3344 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003345 deleted. This command returns an empty string.
3346 """
3347 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003348
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003349 def get(self):
3350 """Returns the spinbox's string"""
3351 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003352
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003353 def icursor(self, index):
3354 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003355
3356 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003357 the character given by index. Returns an empty string
3358 """
3359 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003360
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003361 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003362 """Returns the name of the widget at position x, y
3363
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003364 Return value is one of: none, buttondown, buttonup, entry
3365 """
3366 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003367
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003368 def index(self, index):
3369 """Returns the numerical index corresponding to index
3370 """
3371 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003372
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003373 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003374 """Insert string s at index
3375
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003376 Returns an empty string.
3377 """
3378 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003379
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003380 def invoke(self, element):
3381 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003382
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003383 The element could be buttondown or buttonup
3384 triggering the action associated with it.
3385 """
3386 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003387
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003388 def scan(self, *args):
3389 """Internal function."""
3390 return self._getints(
3391 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003392
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003393 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003394 """Records x and the current view in the spinbox window;
3395
3396 used in conjunction with later scan dragto commands.
3397 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003398 press in the widget. It returns an empty string.
3399 """
3400 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003401
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003402 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003403 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003404 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003405
3406 It then adjusts the view left or right by 10 times the
3407 difference in x-coordinates. This command is typically
3408 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003409 produce the effect of dragging the spinbox at high speed
3410 through the window. The return value is an empty string.
3411 """
3412 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003413
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003414 def selection(self, *args):
3415 """Internal function."""
3416 return self._getints(
3417 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003418
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003419 def selection_adjust(self, index):
3420 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003421 given by index,
3422
3423 Then adjust that end of the selection to be at index
3424 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003425 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003426 select to commands. If the selection isn't currently in
3427 the spinbox, then a new selection is created to include
3428 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003429 anchor point, inclusive. Returns an empty string.
3430 """
3431 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003432
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003433 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003434 """Clear the selection
3435
3436 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003437 command has no effect. Returns an empty string.
3438 """
3439 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003440
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003441 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003442 """Sets or gets the currently selected element.
3443
3444 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003445 displayed depressed
3446 """
3447 return self.selection("element", element)
3448
3449###########################################################################
3450
3451class LabelFrame(Widget):
3452 """labelframe widget."""
3453 def __init__(self, master=None, cnf={}, **kw):
3454 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003455
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003456 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003457
3458 borderwidth, cursor, font, foreground,
3459 highlightbackground, highlightcolor,
3460 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003461 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003462
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003463 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003464
3465 background, class, colormap, container,
3466 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003467 visual, width
3468 """
3469 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003470
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003471########################################################################
3472
3473class PanedWindow(Widget):
3474 """panedwindow widget."""
3475 def __init__(self, master=None, cnf={}, **kw):
3476 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003477
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003478 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003479
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003480 background, borderwidth, cursor, height,
3481 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003482
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003483 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003484
3485 handlepad, handlesize, opaqueresize,
3486 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003487 sashwidth, showhandle,
3488 """
3489 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3490
3491 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003492 """Add a child widget to the panedwindow in a new pane.
3493
3494 The child argument is the name of the child widget
3495 followed by pairs of arguments that specify how to
Guilherme Polo86425562009-05-31 21:35:23 +00003496 manage the windows. The possible options and values
3497 are the ones accepted by the paneconfigure method.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003498 """
3499 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003500
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003501 def remove(self, child):
3502 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003503
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003504 All geometry management options for child will be forgotten.
3505 """
3506 self.tk.call(self._w, 'forget', child)
3507 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003508
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003509 def identify(self, x, y):
3510 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003511
3512 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003513 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003514 handle, and a word indicating whether it is over a sash
3515 or a handle, such as {0 sash} or {2 handle}. If the point
3516 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003517 an empty list.
3518 """
3519 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003520
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003521 def proxy(self, *args):
3522 """Internal function."""
3523 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003524 self.tk.call((self._w, 'proxy') + args)) or ()
3525
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003526 def proxy_coord(self):
3527 """Return the x and y pair of the most recent proxy location
3528 """
3529 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003530
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003531 def proxy_forget(self):
3532 """Remove the proxy from the display.
3533 """
3534 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003535
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003536 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003537 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003538 """
3539 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003540
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003541 def sash(self, *args):
3542 """Internal function."""
3543 return self._getints(
3544 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003545
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003546 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003547 """Return the current x and y pair for the sash given by index.
3548
3549 Index must be an integer between 0 and 1 less than the
3550 number of panes in the panedwindow. The coordinates given are
3551 those of the top left corner of the region containing the sash.
3552 pathName sash dragto index x y This command computes the
3553 difference between the given coordinates and the coordinates
3554 given to the last sash coord command for the given sash. It then
3555 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003556 empty string.
3557 """
3558 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003559
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003560 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003561 """Records x and y for the sash given by index;
3562
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003563 Used in conjunction with later dragto commands to move the sash.
3564 """
3565 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003566
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003567 def sash_place(self, index, x, y):
3568 """Place the sash given by index at the given coordinates
3569 """
3570 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003571
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003572 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003573 """Query a management option for window.
3574
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003575 Option may be any value allowed by the paneconfigure subcommand
3576 """
3577 return self.tk.call(
3578 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003579
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003580 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003581 """Query or modify the management options for window.
3582
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003583 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003584 of the available options for pathName. If option is
3585 specified with no value, then the command returns a list
3586 describing the one named option (this list will be identical
3587 to the corresponding sublist of the value returned if no
3588 option is specified). If one or more option-value pairs are
3589 specified, then the command modifies the given widget
3590 option(s) to have the given value(s); in this case the
3591 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003592 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003593
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003594 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003595 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003596 should be the name of a window already managed by pathName.
3597 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003598 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003599 should be the name of a window already managed by pathName.
3600 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003601 Specify a height for the window. The height will be the
3602 outer dimension of the window including its border, if
3603 any. If size is an empty string, or if -height is not
3604 specified, then the height requested internally by the
3605 window will be used initially; the height may later be
3606 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003607 Size may be any value accepted by Tk_GetPixels.
3608 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003609 Specifies that the size of the window cannot be made
3610 less than n. This constraint only affects the size of
3611 the widget in the paned dimension -- the x dimension
3612 for horizontal panedwindows, the y dimension for
3613 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003614 Tk_GetPixels.
3615 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003616 Specifies a non-negative value indicating how much
3617 extra space to leave on each side of the window in
3618 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003619 accepted by Tk_GetPixels.
3620 pady n
3621 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003622 extra space to leave on each side of the window in
3623 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003624 accepted by Tk_GetPixels.
3625 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003626 If a window's pane is larger than the requested
3627 dimensions of the window, this option may be used
3628 to position (or stretch) the window within its pane.
3629 Style is a string that contains zero or more of the
3630 characters n, s, e or w. The string can optionally
3631 contains spaces or commas, but they are ignored. Each
3632 letter refers to a side (north, south, east, or west)
3633 that the window will "stick" to. If both n and s
3634 (or e and w) are specified, the window will be
3635 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003636 its cavity.
3637 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003638 Specify a width for the window. The width will be
3639 the outer dimension of the window including its
3640 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003641 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003642 internally by the window will be used initially; the
3643 width may later be adjusted by the movement of sashes
3644 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003645 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003646
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003647 """
3648 if cnf is None and not kw:
3649 cnf = {}
3650 for x in self.tk.split(
3651 self.tk.call(self._w,
3652 'paneconfigure', tagOrId)):
3653 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3654 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00003655 if isinstance(cnf, str) and not kw:
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003656 x = self.tk.split(self.tk.call(
3657 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3658 return (x[0][1:],) + x[1:]
3659 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3660 self._options(cnf, kw))
3661 paneconfig = paneconfigure
3662
3663 def panes(self):
3664 """Returns an ordered list of the child panes."""
3665 return self.tk.call(self._w, 'panes')
3666
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003667######################################################################
3668# Extensions:
3669
3670class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003671 def __init__(self, master=None, cnf={}, **kw):
3672 Widget.__init__(self, master, 'studbutton', cnf, kw)
3673 self.bind('<Any-Enter>', self.tkButtonEnter)
3674 self.bind('<Any-Leave>', self.tkButtonLeave)
3675 self.bind('<1>', self.tkButtonDown)
3676 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003677
3678class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003679 def __init__(self, master=None, cnf={}, **kw):
3680 Widget.__init__(self, master, 'tributton', cnf, kw)
3681 self.bind('<Any-Enter>', self.tkButtonEnter)
3682 self.bind('<Any-Leave>', self.tkButtonLeave)
3683 self.bind('<1>', self.tkButtonDown)
3684 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3685 self['fg'] = self['bg']
3686 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003687
Guido van Rossumc417ef81996-08-21 23:38:59 +00003688######################################################################
3689# Test:
3690
3691def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003692 root = Tk()
3693 text = "This is Tcl/Tk version %s" % TclVersion
3694 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003695 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003696 label = Label(root, text=text)
3697 label.pack()
3698 test = Button(root, text="Click me!",
3699 command=lambda root=root: root.test.configure(
3700 text="[%s]" % root.test['text']))
3701 test.pack()
3702 root.test = test
3703 quit = Button(root, text="QUIT", command=root.destroy)
3704 quit.pack()
3705 # The following three commands are needed so the window pops
3706 # up on top on Windows...
3707 root.iconify()
3708 root.update()
3709 root.deiconify()
3710 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003711
3712if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003713 _test()